linecache.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """Cache lines from Python source files.
  2. This is intended to read lines from modules imported -- hence if a filename
  3. is not found, it will look down the module search path for a file by
  4. that name.
  5. """
  6. import functools
  7. import sys
  8. import os
  9. import tokenize
  10. __all__ = ["getline", "clearcache", "checkcache"]
  11. def getline(filename, lineno, module_globals=None):
  12. lines = getlines(filename, module_globals)
  13. if 1 <= lineno <= len(lines):
  14. return lines[lineno-1]
  15. else:
  16. return ''
  17. # The cache
  18. # The cache. Maps filenames to either a thunk which will provide source code,
  19. # or a tuple (size, mtime, lines, fullname) once loaded.
  20. cache = {}
  21. def clearcache():
  22. """Clear the cache entirely."""
  23. global cache
  24. cache = {}
  25. def getlines(filename, module_globals=None):
  26. """Get the lines for a Python source file from the cache.
  27. Update the cache if it doesn't contain an entry for this file already."""
  28. if filename in cache:
  29. entry = cache[filename]
  30. if len(entry) != 1:
  31. return cache[filename][2]
  32. try:
  33. return updatecache(filename, module_globals)
  34. except MemoryError:
  35. clearcache()
  36. return []
  37. def checkcache(filename=None):
  38. """Discard cache entries that are out of date.
  39. (This is not checked upon each call!)"""
  40. if filename is None:
  41. filenames = list(cache.keys())
  42. else:
  43. if filename in cache:
  44. filenames = [filename]
  45. else:
  46. return
  47. for filename in filenames:
  48. entry = cache[filename]
  49. if len(entry) == 1:
  50. # lazy cache entry, leave it lazy.
  51. continue
  52. size, mtime, lines, fullname = entry
  53. if mtime is None:
  54. continue # no-op for files loaded via a __loader__
  55. try:
  56. stat = os.stat(fullname)
  57. except OSError:
  58. del cache[filename]
  59. continue
  60. if size != stat.st_size or mtime != stat.st_mtime:
  61. del cache[filename]
  62. def updatecache(filename, module_globals=None):
  63. """Update a cache entry and return its list of lines.
  64. If something's wrong, print a message, discard the cache entry,
  65. and return an empty list."""
  66. if filename in cache:
  67. if len(cache[filename]) != 1:
  68. del cache[filename]
  69. if not filename or (filename.startswith('<') and filename.endswith('>')):
  70. return []
  71. fullname = filename
  72. try:
  73. stat = os.stat(fullname)
  74. except OSError:
  75. basename = filename
  76. # Realise a lazy loader based lookup if there is one
  77. # otherwise try to lookup right now.
  78. if lazycache(filename, module_globals):
  79. try:
  80. data = cache[filename][0]()
  81. except (ImportError, OSError):
  82. pass
  83. else:
  84. if data is None:
  85. # No luck, the PEP302 loader cannot find the source
  86. # for this module.
  87. return []
  88. cache[filename] = (
  89. len(data), None,
  90. [line+'\n' for line in data.splitlines()], fullname
  91. )
  92. return cache[filename][2]
  93. # Try looking through the module search path, which is only useful
  94. # when handling a relative filename.
  95. if os.path.isabs(filename):
  96. return []
  97. for dirname in sys.path:
  98. try:
  99. fullname = os.path.join(dirname, basename)
  100. except (TypeError, AttributeError):
  101. # Not sufficiently string-like to do anything useful with.
  102. continue
  103. try:
  104. stat = os.stat(fullname)
  105. break
  106. except OSError:
  107. pass
  108. else:
  109. return []
  110. try:
  111. with tokenize.open(fullname) as fp:
  112. lines = fp.readlines()
  113. except OSError:
  114. return []
  115. if lines and not lines[-1].endswith('\n'):
  116. lines[-1] += '\n'
  117. size, mtime = stat.st_size, stat.st_mtime
  118. cache[filename] = size, mtime, lines, fullname
  119. return lines
  120. def lazycache(filename, module_globals):
  121. """Seed the cache for filename with module_globals.
  122. The module loader will be asked for the source only when getlines is
  123. called, not immediately.
  124. If there is an entry in the cache already, it is not altered.
  125. :return: True if a lazy load is registered in the cache,
  126. otherwise False. To register such a load a module loader with a
  127. get_source method must be found, the filename must be a cachable
  128. filename, and the filename must not be already cached.
  129. """
  130. if filename in cache:
  131. if len(cache[filename]) == 1:
  132. return True
  133. else:
  134. return False
  135. if not filename or (filename.startswith('<') and filename.endswith('>')):
  136. return False
  137. # Try for a __loader__, if available
  138. if module_globals and '__loader__' in module_globals:
  139. name = module_globals.get('__name__')
  140. loader = module_globals['__loader__']
  141. get_source = getattr(loader, 'get_source', None)
  142. if name and get_source:
  143. get_lines = functools.partial(get_source, name)
  144. cache[filename] = (get_lines,)
  145. return True
  146. return False