Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame^] | 1 | # Module 'statcache' |
| 2 | # |
| 3 | # Maintain a cache of file stats. |
| 4 | # There are functions to reset the cache or to selectively remove items. |
| 5 | |
| 6 | import posix |
| 7 | |
| 8 | |
| 9 | # The cache. |
| 10 | # Keys are pathnames, values are `posix.stat' outcomes. |
| 11 | # |
| 12 | cache = {} |
| 13 | |
| 14 | |
| 15 | # Stat a file, possibly out of the cache. |
| 16 | # |
| 17 | def stat(path): |
| 18 | try: |
| 19 | return cache[path] |
| 20 | except RuntimeError: |
| 21 | pass |
| 22 | cache[path] = ret = posix.stat(path) |
| 23 | return ret |
| 24 | |
| 25 | |
| 26 | # Reset the cache completely. |
| 27 | # Hack: to reset a global variable, we import this module. |
| 28 | # |
| 29 | def reset(): |
| 30 | import statcache |
| 31 | # Check that we really imported the same module |
| 32 | if cache is not statcache.cache: |
| 33 | raise 'sorry, statcache identity crisis' |
| 34 | statcache.cache = {} |
| 35 | |
| 36 | |
| 37 | # Remove a given item from the cache, if it exists. |
| 38 | # |
| 39 | def forget(path): |
| 40 | try: |
| 41 | del cache[path] |
| 42 | except RuntimeError: |
| 43 | pass |
| 44 | |
| 45 | |
| 46 | # Remove all pathnames with a given prefix. |
| 47 | # |
| 48 | def forget_prefix(prefix): |
| 49 | n = len(prefix) |
| 50 | for path in cache.keys(): |
| 51 | if path[:n] = prefix: |
| 52 | del cache[path] |
| 53 | |
| 54 | |
| 55 | # Forget about a directory and all entries in it, but not about |
| 56 | # entries in subdirectories. |
| 57 | # |
| 58 | def forget_dir(prefix): |
| 59 | if prefix[-1:] = '/' and prefix <> '/': |
| 60 | prefix = prefix[:-1] |
| 61 | forget(prefix) |
| 62 | if prefix[-1:] <> '/': |
| 63 | prefix = prefix + '/' |
| 64 | n = len(prefix) |
| 65 | for path in cache.keys(): |
| 66 | if path[:n] = prefix: |
| 67 | rest = path[n:] |
| 68 | if rest[-1:] = '/': rest = rest[:-1] |
| 69 | if '/' not in rest: |
| 70 | del cache[path] |
| 71 | |
| 72 | |
| 73 | # Remove all pathnames except with a given prefix. |
| 74 | # Normally used with prefix = '/' after a chdir(). |
| 75 | # |
| 76 | def forget_except_prefix(prefix): |
| 77 | n = len(prefix) |
| 78 | for path in cache.keys(): |
| 79 | if path[:n] <> prefix: |
| 80 | del cache[path] |
| 81 | |
| 82 | |
| 83 | # Check for directory. |
| 84 | # |
| 85 | def isdir(path): |
| 86 | try: |
| 87 | # mode is st[0]; type is mode/4096; S_IFDIR is 4 |
| 88 | return stat(path)[0] / 4096 = 4 |
| 89 | except RuntimeError: |
| 90 | return 0 |