Guido van Rossum | 217a5fa | 1990-12-26 15:40:07 +0000 | [diff] [blame] | 1 | # Module 'maccache' |
| 2 | # |
| 3 | # Maintain a cache of listdir(), isdir(), isfile() or exists() outcomes. |
| 4 | |
| 5 | import mac |
| 6 | import macpath |
| 7 | |
| 8 | |
| 9 | # The cache. |
| 10 | # Keys are absolute pathnames; |
| 11 | # values are 0 (nothing), 1 (file) or [...] (dir). |
| 12 | # |
| 13 | cache = {} |
| 14 | |
| 15 | |
| 16 | # Current working directory. |
| 17 | # |
| 18 | cwd = mac.getcwd() |
| 19 | |
| 20 | |
| 21 | # Constants. |
| 22 | # |
| 23 | NONE = 0 |
| 24 | FILE = 1 |
| 25 | LISTTYPE = type([]) |
| 26 | |
| 27 | def _stat(name): |
| 28 | name = macpath.cat(cwd, name) |
| 29 | if cache.has_key(name): |
| 30 | return cache[name] |
| 31 | if macpath.isfile(name): |
| 32 | cache[name] = FILE |
| 33 | return FILE |
| 34 | try: |
| 35 | list = mac.listdir(name) |
| 36 | except: |
| 37 | cache[name] = NONE |
| 38 | return NONE |
| 39 | cache[name] = list |
| 40 | if name[-1:] = ':': cache[name[:-1]] = list |
| 41 | else: cache[name+':'] = list |
| 42 | return list |
| 43 | |
| 44 | def isdir(name): |
| 45 | st = _stat(name) |
| 46 | return type(st) = LISTTYPE |
| 47 | |
| 48 | def isfile(name): |
| 49 | st = _stat(name) |
| 50 | return st = FILE |
| 51 | |
| 52 | def exists(name): |
| 53 | st = _stat(name) |
| 54 | return st <> NONE |
| 55 | |
| 56 | def listdir(name): |
| 57 | st = _stat(name) |
| 58 | if type(st) = LISTTYPE: |
| 59 | return st |
| 60 | else: |
| 61 | raise RuntimeError, 'list non-directory' |