linecache.py 6.1 KB

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