1 """Cache lines from files.
3 This is intended to read lines from modules imported -- hence if a filename
4 is not found, it will look down the module search path for a file by
12 def getline(filename
, lineno
):
13 lines
= getlines(filename
)
14 if 1 <= lineno
<= len(lines
):
15 return lines
[lineno
-1]
22 cache
= {} # The cache
26 """Clear the cache entirely."""
32 def getlines(filename
):
33 """Get the lines for a file from the cache.
34 Update the cache if it doesn't contain an entry for this file already."""
36 if cache
.has_key(filename
):
37 return cache
[filename
][2]
39 return updatecache(filename
)
43 """Discard cache entries that are out of date.
44 (This is not checked upon each call!)"""
46 for filename
in cache
.keys():
47 size
, mtime
, lines
, fullname
= cache
[filename
]
49 stat
= os
.stat(fullname
)
53 if size
!= stat
[ST_SIZE
] or mtime
!= stat
[ST_MTIME
]:
57 def updatecache(filename
):
58 """Update a cache entry and return its list of lines.
59 If something's wrong, print a message, discard the cache entry,
60 and return an empty list."""
62 if cache
.has_key(filename
):
64 if not filename
or filename
[0] + filename
[-1] == '<>':
68 stat
= os
.stat(fullname
)
70 # Try looking through the module search path
71 basename
= os
.path
.split(filename
)[1]
72 for dirname
in sys
.path
:
73 fullname
= os
.path
.join(dirname
, basename
)
75 stat
= os
.stat(fullname
)
81 ## print '*** Cannot stat', filename, ':', msg
84 fp
= open(fullname
, 'r')
85 lines
= fp
.readlines()
88 ## print '*** Cannot open', fullname, ':', msg
90 size
, mtime
= stat
[ST_SIZE
], stat
[ST_MTIME
]
91 cache
[filename
] = size
, mtime
, lines
, fullname