blob: 7e4f0b508ac74e47495622472b2382370fa3d9d9 [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."""
Brett Cannon0aa6e1b2008-05-10 21:12:57 +00006from warnings import warnpy3k
7warnpy3k("the dircache module has been removed in Python 3.0", stacklevel=2)
8del warnpy3k
Guido van Rossumc6360141990-10-13 19:23:40 +00009
Guido van Rossumc96207a1992-03-31 18:55:40 +000010import os
Guido van Rossumc6360141990-10-13 19:23:40 +000011
Guido van Rossumd1d053c2001-03-02 13:35:37 +000012__all__ = ["listdir", "opendir", "annotate", "reset"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000013
Guido van Rossumc6360141990-10-13 19:23:40 +000014cache = {}
15
Guido van Rossumd1d053c2001-03-02 13:35:37 +000016def reset():
Tim Peters30edd232001-03-16 08:29:48 +000017 """Reset the cache completely."""
18 global cache
19 cache = {}
Guido van Rossumd1d053c2001-03-02 13:35:37 +000020
Guido van Rossum4acc25b2000-02-02 15:10:15 +000021def 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öwisc6bb6c02003-09-20 15:52:21 +000028 mtime = os.stat(path).st_mtime
Fred Drake8152d322000-12-12 23:20:45 +000029 if mtime != cached_mtime:
Martin v. Löwisc6bb6c02003-09-20 15:52:21 +000030 list = os.listdir(path)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000031 list.sort()
32 cache[path] = mtime, list
33 return list
Guido van Rossumc6360141990-10-13 19:23:40 +000034
35opendir = listdir # XXX backward compatibility
36
Guido van Rossum4acc25b2000-02-02 15:10:15 +000037def 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] + '/'