blob: bf13eb5add83c6aa2e2942d12cf74d4d8d05715a [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# Module 'statcache'
2#
3# Maintain a cache of file stats.
4# There are functions to reset the cache or to selectively remove items.
5
6import posix
Guido van Rossum40d93041990-10-21 16:17:34 +00007from stat import *
Guido van Rossumc6360141990-10-13 19:23:40 +00008
9# The cache.
10# Keys are pathnames, values are `posix.stat' outcomes.
11#
12cache = {}
13
14
15# Stat a file, possibly out of the cache.
16#
17def stat(path):
Guido van Rossum40d93041990-10-21 16:17:34 +000018 if cache.has_key(path):
Guido van Rossumc6360141990-10-13 19:23:40 +000019 return cache[path]
Guido van Rossumc6360141990-10-13 19:23:40 +000020 cache[path] = ret = posix.stat(path)
21 return ret
22
23
24# Reset the cache completely.
25# Hack: to reset a global variable, we import this module.
26#
27def reset():
28 import statcache
29 # Check that we really imported the same module
30 if cache is not statcache.cache:
31 raise 'sorry, statcache identity crisis'
32 statcache.cache = {}
33
34
35# Remove a given item from the cache, if it exists.
36#
37def forget(path):
Guido van Rossum40d93041990-10-21 16:17:34 +000038 if cache.has_key(path):
Guido van Rossumc6360141990-10-13 19:23:40 +000039 del cache[path]
Guido van Rossumc6360141990-10-13 19:23:40 +000040
41
42# Remove all pathnames with a given prefix.
43#
44def forget_prefix(prefix):
45 n = len(prefix)
46 for path in cache.keys():
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000047 if path[:n] == prefix:
Guido van Rossumc6360141990-10-13 19:23:40 +000048 del cache[path]
49
50
51# Forget about a directory and all entries in it, but not about
52# entries in subdirectories.
53#
54def forget_dir(prefix):
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000055 if prefix[-1:] == '/' and prefix <> '/':
Guido van Rossumc6360141990-10-13 19:23:40 +000056 prefix = prefix[:-1]
57 forget(prefix)
58 if prefix[-1:] <> '/':
59 prefix = prefix + '/'
60 n = len(prefix)
61 for path in cache.keys():
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000062 if path[:n] == prefix:
Guido van Rossumc6360141990-10-13 19:23:40 +000063 rest = path[n:]
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000064 if rest[-1:] == '/': rest = rest[:-1]
Guido van Rossumc6360141990-10-13 19:23:40 +000065 if '/' not in rest:
66 del cache[path]
67
68
69# Remove all pathnames except with a given prefix.
70# Normally used with prefix = '/' after a chdir().
71#
72def forget_except_prefix(prefix):
73 n = len(prefix)
74 for path in cache.keys():
75 if path[:n] <> prefix:
76 del cache[path]
77
78
79# Check for directory.
80#
81def isdir(path):
82 try:
Guido van Rossum40d93041990-10-21 16:17:34 +000083 st = stat(path)
84 except posix.error:
Guido van Rossumc6360141990-10-13 19:23:40 +000085 return 0
Guido van Rossum40d93041990-10-21 16:17:34 +000086 return S_ISDIR(st[ST_MODE])