blob: 78ec7fe0f433b3ac535761e147da158569b97ac3 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""Read and cache directory listings.
2
3The listdir() routine returns a sorted list of the files in a directory,
4using a cache to avoid reading the directory more often than necessary.
5The annotate() routine appends slashes to directories."""
Guido van Rossumc6360141990-10-13 19:23:40 +00006
Guido van Rossumc96207a1992-03-31 18:55:40 +00007import os
Guido van Rossumc6360141990-10-13 19:23:40 +00008
Guido van Rossumd1d053c2001-03-02 13:35:37 +00009__all__ = ["listdir", "opendir", "annotate", "reset"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000010
Guido van Rossumc6360141990-10-13 19:23:40 +000011cache = {}
12
Guido van Rossumd1d053c2001-03-02 13:35:37 +000013def reset():
Tim Peters30edd232001-03-16 08:29:48 +000014 """Reset the cache completely."""
15 global cache
16 cache = {}
Guido van Rossumd1d053c2001-03-02 13:35:37 +000017
Guido van Rossum4acc25b2000-02-02 15:10:15 +000018def 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öwisc6bb6c02003-09-20 15:52:21 +000025 mtime = os.stat(path).st_mtime
Fred Drake8152d322000-12-12 23:20:45 +000026 if mtime != cached_mtime:
Martin v. Löwisc6bb6c02003-09-20 15:52:21 +000027 list = os.listdir(path)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000028 list.sort()
29 cache[path] = mtime, list
30 return list
Guido van Rossumc6360141990-10-13 19:23:40 +000031
32opendir = listdir # XXX backward compatibility
33
Guido van Rossum4acc25b2000-02-02 15:10:15 +000034def 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] + '/'