blob: b5147c233dc545952790a88e3f014d6427565c01 [file] [log] [blame]
Guido van Rossumaad67612000-05-08 17:31:04 +00001"""Maintain a cache of stat() information on files.
2
3There are functions to reset the cache or to selectively remove items.
4"""
Guido van Rossum5c971671996-07-22 15:23:25 +00005
6import os
7from stat import *
8
9# The cache.
10# Keys are pathnames, values are `os.stat' outcomes.
11#
12cache = {}
13
14
Guido van Rossum5c971671996-07-22 15:23:25 +000015def stat(path):
Guido van Rossumaad67612000-05-08 17:31:04 +000016 """Stat a file, possibly out of the cache."""
Guido van Rossum5c971671996-07-22 15:23:25 +000017 if cache.has_key(path):
18 return cache[path]
19 cache[path] = ret = os.stat(path)
20 return ret
21
22
Guido van Rossum5c971671996-07-22 15:23:25 +000023def reset():
Guido van Rossumaad67612000-05-08 17:31:04 +000024 """Reset the cache completely."""
Guido van Rossum5c971671996-07-22 15:23:25 +000025 global cache
26 cache = {}
27
28
Guido van Rossum5c971671996-07-22 15:23:25 +000029def forget(path):
Guido van Rossumaad67612000-05-08 17:31:04 +000030 """Remove a given item from the cache, if it exists."""
Guido van Rossum5c971671996-07-22 15:23:25 +000031 if cache.has_key(path):
32 del cache[path]
33
34
Guido van Rossum5c971671996-07-22 15:23:25 +000035def forget_prefix(prefix):
Guido van Rossumaad67612000-05-08 17:31:04 +000036 """Remove all pathnames with a given prefix."""
Guido van Rossum5c971671996-07-22 15:23:25 +000037 n = len(prefix)
38 for path in cache.keys():
39 if path[:n] == prefix:
40 del cache[path]
41
42
Guido van Rossum5c971671996-07-22 15:23:25 +000043def forget_dir(prefix):
Guido van Rossumaad67612000-05-08 17:31:04 +000044 """Forget about a directory and all entries in it, but not about
45 entries in subdirectories."""
Guido van Rossum5c971671996-07-22 15:23:25 +000046 if prefix[-1:] == '/' and prefix <> '/':
47 prefix = prefix[:-1]
48 forget(prefix)
49 if prefix[-1:] <> '/':
50 prefix = prefix + '/'
51 n = len(prefix)
52 for path in cache.keys():
53 if path[:n] == prefix:
54 rest = path[n:]
55 if rest[-1:] == '/': rest = rest[:-1]
56 if '/' not in rest:
57 del cache[path]
58
59
Guido van Rossum5c971671996-07-22 15:23:25 +000060def forget_except_prefix(prefix):
Guido van Rossumaad67612000-05-08 17:31:04 +000061 """Remove all pathnames except with a given prefix.
62 Normally used with prefix = '/' after a chdir()."""
Guido van Rossum5c971671996-07-22 15:23:25 +000063 n = len(prefix)
64 for path in cache.keys():
65 if path[:n] <> prefix:
66 del cache[path]
67
68
Guido van Rossum5c971671996-07-22 15:23:25 +000069def isdir(path):
Guido van Rossumaad67612000-05-08 17:31:04 +000070 """Check for directory."""
Guido van Rossum5c971671996-07-22 15:23:25 +000071 try:
72 st = stat(path)
73 except os.error:
74 return 0
75 return S_ISDIR(st[ST_MODE])