blob: 4355f197582ada7a2eb04a140f98b551d52897b9 [file] [log] [blame]
Guido van Rossum921c8241992-01-10 14:54:42 +00001# Cache lines from files.
2
3import os
4from stat import *
5
6def getline(filename, lineno):
7 lines = getlines(filename)
8 if 1 <= lineno <= len(lines):
9 return lines[lineno-1]
10 else:
11 return ''
12
13
14# The cache
15
16cache = {} # The cache
17
18
19# Clear the cache entirely
20
21def clearcache():
22 global cache
23 cache = {}
24
25
26# Get the lines for a file from the cache.
27# Update the cache if it doesn't contain an entry for this file already.
28
29def getlines(filename):
30 if cache.has_key(filename):
31 return cache[filename][2]
32 else:
33 return updatecache(filename)
34
35
36# Discard cache entries that are out of date.
37# (This is not checked upon each call
38
39def checkcache():
40 for filename in cache.keys():
41 size, mtime, lines = cache[filename]
42 try: stat = os.stat(filename)
43 except os.error:
44 del cache[filename]
45 continue
46 if size <> stat[ST_SIZE] or mtime <> stat[ST_MTIME]:
47 del cache[filename]
48
49
50# Update a cache entry and return its list of lines.
51# If something's wrong, print a message, discard the cache entry,
52# and return an empty list.
53
54def updatecache(filename):
55 try: del cache[filename]
56 except KeyError: pass
57 try: stat = os.stat(filename)
58 except os.error, msg:
59 if filename[0] + filename[-1] <> '<>':
60 print '*** Cannot stat', filename, ':', msg
61 return []
62 try:
63 fp = open(filename, 'r')
64 lines = fp.readlines()
65 fp.close()
66 except IOError, msg:
67 print '*** Cannot open', filename, ':', msg
68 return []
69 size, mtime = stat[ST_SIZE], stat[ST_MTIME]
70 cache[filename] = size, mtime, lines
71 return lines