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
11 __all__
= ["getline","clearcache","checkcache"]
13 def getline(filename
, lineno
):
14 lines
= getlines(filename
)
15 if 1 <= lineno
<= len(lines
):
16 return lines
[lineno
-1]
23 cache
= {} # The cache
27 """Clear the cache entirely."""
33 def getlines(filename
):
34 """Get the lines for a file from the cache.
35 Update the cache if it doesn't contain an entry for this file already."""
38 return cache
[filename
][2]
40 return updatecache(filename
)
44 """Discard cache entries that are out of date.
45 (This is not checked upon each call!)"""
47 for filename
in cache
.keys():
48 size
, mtime
, lines
, fullname
= cache
[filename
]
50 stat
= os
.stat(fullname
)
54 if size
!= stat
.st_size
or mtime
!= stat
.st_mtime
:
58 def updatecache(filename
):
59 """Update a cache entry and return its list of lines.
60 If something's wrong, print a message, discard the cache entry,
61 and return an empty list."""
65 if not filename
or filename
[0] + filename
[-1] == '<>':
69 stat
= os
.stat(fullname
)
71 # Try looking through the module search path.
72 basename
= os
.path
.split(filename
)[1]
73 for dirname
in sys
.path
:
74 # When using imputil, sys.path may contain things other than
75 # strings; ignore them when it happens.
77 fullname
= os
.path
.join(dirname
, basename
)
78 except (TypeError, AttributeError):
79 # Not sufficiently string-like to do anything useful with.
83 stat
= os
.stat(fullname
)
89 ## print '*** Cannot stat', filename, ':', msg
92 fp
= open(fullname
, 'rU')
93 lines
= fp
.readlines()
96 ## print '*** Cannot open', fullname, ':', msg
98 size
, mtime
= stat
.st_size
, stat
.st_mtime
99 cache
[filename
] = size
, mtime
, lines
, fullname