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.""" |
Brett Cannon | 0aa6e1b | 2008-05-10 21:12:57 +0000 | [diff] [blame] | 6 | from warnings import warnpy3k |
| 7 | warnpy3k("the dircache module has been removed in Python 3.0", stacklevel=2) |
| 8 | del warnpy3k |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 9 | |
Guido van Rossum | c96207a | 1992-03-31 18:55:40 +0000 | [diff] [blame] | 10 | import os |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 11 | |
Guido van Rossum | d1d053c | 2001-03-02 13:35:37 +0000 | [diff] [blame] | 12 | __all__ = ["listdir", "opendir", "annotate", "reset"] |
Skip Montanaro | e99d5ea | 2001-01-20 19:54:20 +0000 | [diff] [blame] | 13 | |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 14 | cache = {} |
| 15 | |
Guido van Rossum | d1d053c | 2001-03-02 13:35:37 +0000 | [diff] [blame] | 16 | def reset(): |
Tim Peters | 30edd23 | 2001-03-16 08:29:48 +0000 | [diff] [blame] | 17 | """Reset the cache completely.""" |
| 18 | global cache |
| 19 | cache = {} |
Guido van Rossum | d1d053c | 2001-03-02 13:35:37 +0000 | [diff] [blame] | 20 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 21 | def listdir(path): |
| 22 | """List directory contents, using cache.""" |
| 23 | try: |
| 24 | cached_mtime, list = cache[path] |
| 25 | del cache[path] |
| 26 | except KeyError: |
| 27 | cached_mtime, list = -1, [] |
Martin v. Löwis | c6bb6c0 | 2003-09-20 15:52:21 +0000 | [diff] [blame] | 28 | mtime = os.stat(path).st_mtime |
Fred Drake | 8152d32 | 2000-12-12 23:20:45 +0000 | [diff] [blame] | 29 | if mtime != cached_mtime: |
Martin v. Löwis | c6bb6c0 | 2003-09-20 15:52:21 +0000 | [diff] [blame] | 30 | list = os.listdir(path) |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 31 | list.sort() |
| 32 | cache[path] = mtime, list |
| 33 | return list |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 34 | |
| 35 | opendir = listdir # XXX backward compatibility |
| 36 | |
Guido van Rossum | 4acc25b | 2000-02-02 15:10:15 +0000 | [diff] [blame] | 37 | def annotate(head, list): |
| 38 | """Add '/' suffixes to directories.""" |
| 39 | for i in range(len(list)): |
| 40 | if os.path.isdir(os.path.join(head, list[i])): |
| 41 | list[i] = list[i] + '/' |