Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / src / nas,5.n2.os.2 / lib / python / lib / python2.4 / linecache.py
CommitLineData
86530b38
AT
1"""Cache lines from files.
2
3This is intended to read lines from modules imported -- hence if a filename
4is not found, it will look down the module search path for a file by
5that name.
6"""
7
8import sys
9import os
10
11__all__ = ["getline", "clearcache", "checkcache"]
12
13def getline(filename, lineno):
14 lines = getlines(filename)
15 if 1 <= lineno <= len(lines):
16 return lines[lineno-1]
17 else:
18 return ''
19
20
21# The cache
22
23cache = {} # The cache
24
25
26def clearcache():
27 """Clear the cache entirely."""
28
29 global cache
30 cache = {}
31
32
33def 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."""
36
37 if filename in cache:
38 return cache[filename][2]
39 else:
40 return updatecache(filename)
41
42
43def checkcache(filename=None):
44 """Discard cache entries that are out of date.
45 (This is not checked upon each call!)"""
46
47 if filename is None:
48 filenames = cache.keys()
49 else:
50 if filename in cache:
51 filenames = [filename]
52 else:
53 return
54
55 for filename in filenames:
56 size, mtime, lines, fullname = cache[filename]
57 try:
58 stat = os.stat(fullname)
59 except os.error:
60 del cache[filename]
61 continue
62 if size != stat.st_size or mtime != stat.st_mtime:
63 del cache[filename]
64
65
66def updatecache(filename):
67 """Update a cache entry and return its list of lines.
68 If something's wrong, print a message, discard the cache entry,
69 and return an empty list."""
70
71 if filename in cache:
72 del cache[filename]
73 if not filename or filename[0] + filename[-1] == '<>':
74 return []
75 fullname = filename
76 try:
77 stat = os.stat(fullname)
78 except os.error, msg:
79 # Try looking through the module search path.
80 basename = os.path.split(filename)[1]
81 for dirname in sys.path:
82 # When using imputil, sys.path may contain things other than
83 # strings; ignore them when it happens.
84 try:
85 fullname = os.path.join(dirname, basename)
86 except (TypeError, AttributeError):
87 # Not sufficiently string-like to do anything useful with.
88 pass
89 else:
90 try:
91 stat = os.stat(fullname)
92 break
93 except os.error:
94 pass
95 else:
96 # No luck
97## print '*** Cannot stat', filename, ':', msg
98 return []
99 try:
100 fp = open(fullname, 'rU')
101 lines = fp.readlines()
102 fp.close()
103 except IOError, msg:
104## print '*** Cannot open', fullname, ':', msg
105 return []
106 size, mtime = stat.st_size, stat.st_mtime
107 cache[filename] = size, mtime, lines, fullname
108 return lines