blob: 1e2b3d02b171a65a9a616ea034b2e4905305f484 [file] [log] [blame]
Guido van Rossum217a5fa1990-12-26 15:40:07 +00001# Module 'maccache'
2#
3# Maintain a cache of listdir(), isdir(), isfile() or exists() outcomes.
Guido van Rossum50399ae1992-03-31 19:05:44 +00004# XXX Should merge with module statcache
Guido van Rossum217a5fa1990-12-26 15:40:07 +00005
Guido van Rossum50399ae1992-03-31 19:05:44 +00006import os
Guido van Rossum217a5fa1990-12-26 15:40:07 +00007
8
9# The cache.
10# Keys are absolute pathnames;
11# values are 0 (nothing), 1 (file) or [...] (dir).
12#
13cache = {}
14
15
16# Current working directory.
17#
Guido van Rossum50399ae1992-03-31 19:05:44 +000018cwd = os.getcwd()
Guido van Rossum217a5fa1990-12-26 15:40:07 +000019
20
21# Constants.
22#
23NONE = 0
24FILE = 1
25LISTTYPE = type([])
26
27def _stat(name):
Guido van Rossum50399ae1992-03-31 19:05:44 +000028 name = os.path.join(cwd, name)
Guido van Rossum217a5fa1990-12-26 15:40:07 +000029 if cache.has_key(name):
30 return cache[name]
Guido van Rossum50399ae1992-03-31 19:05:44 +000031 if os.path.isfile(name):
Guido van Rossum217a5fa1990-12-26 15:40:07 +000032 cache[name] = FILE
33 return FILE
34 try:
Guido van Rossum50399ae1992-03-31 19:05:44 +000035 list = os.listdir(name)
Guido van Rossum217a5fa1990-12-26 15:40:07 +000036 except:
37 cache[name] = NONE
38 return NONE
39 cache[name] = list
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000040 if name[-1:] == ':': cache[name[:-1]] = list
Guido van Rossum217a5fa1990-12-26 15:40:07 +000041 else: cache[name+':'] = list
42 return list
43
44def isdir(name):
45 st = _stat(name)
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000046 return type(st) == LISTTYPE
Guido van Rossum217a5fa1990-12-26 15:40:07 +000047
48def isfile(name):
49 st = _stat(name)
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000050 return st == FILE
Guido van Rossum217a5fa1990-12-26 15:40:07 +000051
52def exists(name):
53 st = _stat(name)
54 return st <> NONE
55
56def listdir(name):
57 st = _stat(name)
Guido van Rossumbdfcfcc1992-01-01 19:35:13 +000058 if type(st) == LISTTYPE:
Guido van Rossum217a5fa1990-12-26 15:40:07 +000059 return st
60 else:
61 raise RuntimeError, 'list non-directory'