extensions.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. from __future__ import annotations
  2. import configparser
  3. import os
  4. import threading
  5. import re
  6. from modules import shared, errors, cache, scripts
  7. from modules.gitpython_hack import Repo
  8. from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
  9. os.makedirs(extensions_dir, exist_ok=True)
  10. def active():
  11. if shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
  12. return []
  13. elif shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions == "extra":
  14. return [x for x in extensions if x.enabled and x.is_builtin]
  15. else:
  16. return [x for x in extensions if x.enabled]
  17. class ExtensionMetadata:
  18. filename = "metadata.ini"
  19. config: configparser.ConfigParser
  20. canonical_name: str
  21. requires: list
  22. def __init__(self, path, canonical_name):
  23. self.config = configparser.ConfigParser()
  24. filepath = os.path.join(path, self.filename)
  25. # `self.config.read()` will quietly swallow OSErrors (which FileNotFoundError is),
  26. # so no need to check whether the file exists beforehand.
  27. try:
  28. self.config.read(filepath)
  29. except Exception:
  30. errors.report(f"Error reading {self.filename} for extension {canonical_name}.", exc_info=True)
  31. self.canonical_name = self.config.get("Extension", "Name", fallback=canonical_name)
  32. self.canonical_name = canonical_name.lower().strip()
  33. self.requires = self.get_script_requirements("Requires", "Extension")
  34. def get_script_requirements(self, field, section, extra_section=None):
  35. """reads a list of requirements from the config; field is the name of the field in the ini file,
  36. like Requires or Before, and section is the name of the [section] in the ini file; additionally,
  37. reads more requirements from [extra_section] if specified."""
  38. x = self.config.get(section, field, fallback='')
  39. if extra_section:
  40. x = x + ', ' + self.config.get(extra_section, field, fallback='')
  41. return self.parse_list(x.lower())
  42. def parse_list(self, text):
  43. """converts a line from config ("ext1 ext2, ext3 ") into a python list (["ext1", "ext2", "ext3"])"""
  44. if not text:
  45. return []
  46. # both "," and " " are accepted as separator
  47. return [x for x in re.split(r"[,\s]+", text.strip()) if x]
  48. class Extension:
  49. lock = threading.Lock()
  50. cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
  51. metadata: ExtensionMetadata
  52. def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
  53. self.name = name
  54. self.path = path
  55. self.enabled = enabled
  56. self.status = ''
  57. self.can_update = False
  58. self.is_builtin = is_builtin
  59. self.commit_hash = ''
  60. self.commit_date = None
  61. self.version = ''
  62. self.branch = None
  63. self.remote = None
  64. self.have_info_from_repo = False
  65. self.metadata = metadata if metadata else ExtensionMetadata(self.path, name.lower())
  66. self.canonical_name = metadata.canonical_name
  67. def to_dict(self):
  68. return {x: getattr(self, x) for x in self.cached_fields}
  69. def from_dict(self, d):
  70. for field in self.cached_fields:
  71. setattr(self, field, d[field])
  72. def read_info_from_repo(self):
  73. if self.is_builtin or self.have_info_from_repo:
  74. return
  75. def read_from_repo():
  76. with self.lock:
  77. if self.have_info_from_repo:
  78. return
  79. self.do_read_info_from_repo()
  80. return self.to_dict()
  81. try:
  82. d = cache.cached_data_for_file('extensions-git', self.name, os.path.join(self.path, ".git"), read_from_repo)
  83. self.from_dict(d)
  84. except FileNotFoundError:
  85. pass
  86. self.status = 'unknown' if self.status == '' else self.status
  87. def do_read_info_from_repo(self):
  88. repo = None
  89. try:
  90. if os.path.exists(os.path.join(self.path, ".git")):
  91. repo = Repo(self.path)
  92. except Exception:
  93. errors.report(f"Error reading github repository info from {self.path}", exc_info=True)
  94. if repo is None or repo.bare:
  95. self.remote = None
  96. else:
  97. try:
  98. self.remote = next(repo.remote().urls, None)
  99. commit = repo.head.commit
  100. self.commit_date = commit.committed_date
  101. if repo.active_branch:
  102. self.branch = repo.active_branch.name
  103. self.commit_hash = commit.hexsha
  104. self.version = self.commit_hash[:8]
  105. except Exception:
  106. errors.report(f"Failed reading extension data from Git repository ({self.name})", exc_info=True)
  107. self.remote = None
  108. self.have_info_from_repo = True
  109. def list_files(self, subdir, extension):
  110. dirpath = os.path.join(self.path, subdir)
  111. if not os.path.isdir(dirpath):
  112. return []
  113. res = []
  114. for filename in sorted(os.listdir(dirpath)):
  115. res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
  116. res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]
  117. return res
  118. def check_updates(self):
  119. repo = Repo(self.path)
  120. for fetch in repo.remote().fetch(dry_run=True):
  121. if fetch.flags != fetch.HEAD_UPTODATE:
  122. self.can_update = True
  123. self.status = "new commits"
  124. return
  125. try:
  126. origin = repo.rev_parse('origin')
  127. if repo.head.commit != origin:
  128. self.can_update = True
  129. self.status = "behind HEAD"
  130. return
  131. except Exception:
  132. self.can_update = False
  133. self.status = "unknown (remote error)"
  134. return
  135. self.can_update = False
  136. self.status = "latest"
  137. def fetch_and_reset_hard(self, commit='origin'):
  138. repo = Repo(self.path)
  139. # Fix: `error: Your local changes to the following files would be overwritten by merge`,
  140. # because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
  141. repo.git.fetch(all=True)
  142. repo.git.reset(commit, hard=True)
  143. self.have_info_from_repo = False
  144. def list_extensions():
  145. extensions.clear()
  146. if shared.cmd_opts.disable_all_extensions:
  147. print("*** \"--disable-all-extensions\" arg was used, will not load any extensions ***")
  148. elif shared.opts.disable_all_extensions == "all":
  149. print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
  150. elif shared.cmd_opts.disable_extra_extensions:
  151. print("*** \"--disable-extra-extensions\" arg was used, will only load built-in extensions ***")
  152. elif shared.opts.disable_all_extensions == "extra":
  153. print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
  154. loaded_extensions = {}
  155. # scan through extensions directory and load metadata
  156. for dirname in [extensions_builtin_dir, extensions_dir]:
  157. if not os.path.isdir(dirname):
  158. continue
  159. for extension_dirname in sorted(os.listdir(dirname)):
  160. path = os.path.join(dirname, extension_dirname)
  161. if not os.path.isdir(path):
  162. continue
  163. canonical_name = extension_dirname
  164. metadata = ExtensionMetadata(path, canonical_name)
  165. # check for duplicated canonical names
  166. already_loaded_extension = loaded_extensions.get(metadata.canonical_name)
  167. if already_loaded_extension is not None:
  168. errors.report(f'Duplicate canonical name "{canonical_name}" found in extensions "{extension_dirname}" and "{already_loaded_extension.name}". Former will be discarded.', exc_info=False)
  169. continue
  170. is_builtin = dirname == extensions_builtin_dir
  171. extension = Extension(name=extension_dirname, path=path, enabled=extension_dirname not in shared.opts.disabled_extensions, is_builtin=is_builtin, metadata=metadata)
  172. extensions.append(extension)
  173. loaded_extensions[canonical_name] = extension
  174. # check for requirements
  175. for extension in extensions:
  176. if not extension.enabled:
  177. continue
  178. for req in extension.metadata.requires:
  179. required_extension = loaded_extensions.get(req)
  180. if required_extension is None:
  181. errors.report(f'Extension "{extension.name}" requires "{req}" which is not installed.', exc_info=False)
  182. continue
  183. if not required_extension.enabled:
  184. errors.report(f'Extension "{extension.name}" requires "{required_extension.name}" which is disabled.', exc_info=False)
  185. continue
  186. extensions: list[Extension] = []