Guido van Rossum | 4b8c6ea | 2000-02-04 15:39:30 +0000 | [diff] [blame] | 1 | """Read and cache directory listings. |
| 2 | |
| 3 | The listdir() routine returns a sorted list of the files in a directory, |
| 4 | using a cache to avoid reading the directory more often than necessary. |
| 5 | The annotate() routine appends slashes to directories.""" |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | c96207a | 1992-03-31 18:55:40 +0000 | [diff] [blame] | 7 | import os |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | d1d053c | 2001-03-02 13:35:37 +0000 | [diff] [blame] | 9 | __all__ = ["listdir", "opendir", "annotate", "reset"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 11 | cache = {} |
| 12 | |
Guido van Rossum | d1d053c | 2001-03-02 13:35:37 +0000 | [diff] [blame] | 13 | def reset(): |
Tim Peters | 30edd23 | 2001-03-16 08:29:48 +0000 | [diff] [blame] | 14 | """Reset the cache completely.""" |
| 15 | global cache |
| 16 | cache = {} |
Guido van Rossum | d1d053c | 2001-03-02 13:35:37 +0000 | [diff] [blame] | 17 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 18 | def listdir(path): |
| 19 | """List directory contents, using cache.""" |
| 20 | try: |
| 21 | cached_mtime, list = cache[path] |
| 22 | del cache[path] |
| 23 | except KeyError: |
| 24 | cached_mtime, list = -1, [] |
Martin v. Löwis | c6bb6c0 | 2003-09-20 15:52:21 +0000 | [diff] [blame] | 25 | mtime = os.stat(path).st_mtime |
Fred Drake | 8152d32 | 2000-12-12 23:20:45 +0000 | [diff] [blame] | 26 | if mtime != cached_mtime: |
Martin v. Löwis | c6bb6c0 | 2003-09-20 15:52:21 +0000 | [diff] [blame] | 27 | list = os.listdir(path) |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 28 | list.sort() |
| 29 | cache[path] = mtime, list |
| 30 | return list |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 31 | |
| 32 | opendir = listdir # XXX backward compatibility |
| 33 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 34 | def annotate(head, list): |
| 35 | """Add '/' suffixes to directories.""" |
| 36 | for i in range(len(list)): |
| 37 | if os.path.isdir(os.path.join(head, list[i])): |
| 38 | list[i] = list[i] + '/' |