|
| 1 | +# Cache lines from files. |
| 2 | + |
| 3 | +import os |
| 4 | +from stat import * |
| 5 | + |
| 6 | +def 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 | + |
| 16 | +cache = {} # The cache |
| 17 | + |
| 18 | + |
| 19 | +# Clear the cache entirely |
| 20 | + |
| 21 | +def 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 | + |
| 29 | +def 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 | + |
| 39 | +def 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 | + |
| 54 | +def 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 |
0 commit comments