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, [] |
| 25 | try: |
Raymond Hettinger | 32200ae | 2002-06-01 19:51:15 +0000 | [diff] [blame] | 26 | mtime = os.stat(path).st_mtime |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 27 | except os.error: |
| 28 | return [] |
Fred Drake | 8152d32 | 2000-12-12 23:20:45 +0000 | [diff] [blame] | 29 | if mtime != cached_mtime: |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 30 | try: |
| 31 | list = os.listdir(path) |
| 32 | except os.error: |
| 33 | return [] |
| 34 | list.sort() |
| 35 | cache[path] = mtime, list |
| 36 | return list |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 37 | |
| 38 | opendir = listdir # XXX backward compatibility |
| 39 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 40 | def annotate(head, list): |
| 41 | """Add '/' suffixes to directories.""" |
| 42 | for i in range(len(list)): |
| 43 | if os.path.isdir(os.path.join(head, list[i])): |
| 44 | list[i] = list[i] + '/' |