blob: ef68b429f97c3f27687f187785154fd1905e814a [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# Module 'dircache'
2#
Guido van Rossumc96207a1992-03-31 18:55:40 +00003# Return a sorted list of the files in a directory, using a cache
Guido van Rossumc6360141990-10-13 19:23:40 +00004# to avoid reading the directory more often than necessary.
5# Also contains a subroutine to append slashes to directories.
6
Guido van Rossumc96207a1992-03-31 18:55:40 +00007import os
Guido van Rossumc6360141990-10-13 19:23:40 +00008
9cache = {}
10
11def listdir(path): # List directory contents, using cache
12 try:
13 cached_mtime, list = cache[path]
14 del cache[path]
Guido van Rossum4dedbf71991-12-26 13:03:14 +000015 except KeyError:
Guido van Rossumc6360141990-10-13 19:23:40 +000016 cached_mtime, list = -1, []
17 try:
Guido van Rossumc96207a1992-03-31 18:55:40 +000018 mtime = os.stat(path)[8]
19 except os.error:
Guido van Rossumc6360141990-10-13 19:23:40 +000020 return []
21 if mtime <> cached_mtime:
22 try:
Guido van Rossumc96207a1992-03-31 18:55:40 +000023 list = os.listdir(path)
24 except os.error:
Guido van Rossumc6360141990-10-13 19:23:40 +000025 return []
26 list.sort()
27 cache[path] = mtime, list
28 return list
29
30opendir = listdir # XXX backward compatibility
31
32def annotate(head, list): # Add '/' suffixes to directories
33 for i in range(len(list)):
Guido van Rossumc96207a1992-03-31 18:55:40 +000034 if os.path.isdir(os.path.join(head, list[i])):
Guido van Rossumc6360141990-10-13 19:23:40 +000035 list[i] = list[i] + '/'