blob: a999743a8d109b2a3c953064ebabd8a04a28de8a [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
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00009__all__ = ["listdir","opendir","annotate"]
10
Guido van Rossumc6360141990-10-13 19:23:40 +000011cache = {}
12
Guido van Rossum4acc25b2000-02-02 15:10:15 +000013def listdir(path):
14 """List directory contents, using cache."""
15 try:
16 cached_mtime, list = cache[path]
17 del cache[path]
18 except KeyError:
19 cached_mtime, list = -1, []
20 try:
21 mtime = os.stat(path)[8]
22 except os.error:
23 return []
Fred Drake8152d322000-12-12 23:20:45 +000024 if mtime != cached_mtime:
Guido van Rossum4acc25b2000-02-02 15:10:15 +000025 try:
26 list = os.listdir(path)
27 except os.error:
28 return []
29 list.sort()
30 cache[path] = mtime, list
31 return list
Guido van Rossumc6360141990-10-13 19:23:40 +000032
33opendir = listdir # XXX backward compatibility
34
Guido van Rossum4acc25b2000-02-02 15:10:15 +000035def annotate(head, list):
36 """Add '/' suffixes to directories."""
37 for i in range(len(list)):
38 if os.path.isdir(os.path.join(head, list[i])):
39 list[i] = list[i] + '/'