blob: e18c7c37a4e98062bfb25b4e434e7f99b8811d10 [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, []
25 try:
Raymond Hettinger32200ae2002-06-01 19:51:15 +000026 mtime = os.stat(path).st_mtime
Guido van Rossum4acc25b2000-02-02 15:10:15 +000027 except os.error:
28 return []
Fred Drake8152d322000-12-12 23:20:45 +000029 if mtime != cached_mtime:
Guido van Rossum4acc25b2000-02-02 15:10:15 +000030 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 Rossumc6360141990-10-13 19:23:40 +000037
38opendir = listdir # XXX backward compatibility
39
Guido van Rossum4acc25b2000-02-02 15:10:15 +000040def 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] + '/'