A VCS repository archival tool
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

129 рядки
5.7 KiB

  1. import codearchiver.core
  2. import codearchiver.subprocess
  3. import datetime
  4. import functools
  5. import hashlib
  6. import logging
  7. import os.path
  8. import shutil
  9. import subprocess
  10. _logger = logging.getLogger(__name__)
  11. class GitIndex(codearchiver.core.Index):
  12. fields = (
  13. codearchiver.core.IndexField(key = 'Git version', required = True, repeatable = False),
  14. codearchiver.core.IndexField(key = 'Based on bundle', required = False, repeatable = True),
  15. codearchiver.core.IndexField(key = 'Ref', required = True, repeatable = True),
  16. codearchiver.core.IndexField(key = 'Root commit', required = True, repeatable = True),
  17. codearchiver.core.IndexField(key = 'Commit', required = False, repeatable = True),
  18. )
  19. class Git(codearchiver.core.Module):
  20. name = 'git'
  21. IndexClass = GitIndex
  22. @staticmethod
  23. def matches(inputUrl):
  24. return inputUrl.url.endswith('.git')
  25. def __init__(self, *args, extraBranches = {}, **kwargs):
  26. super().__init__(*args, **kwargs)
  27. self._extraBranches = extraBranches
  28. def process(self):
  29. directory = self._url.rsplit('/', 1)[1]
  30. if os.path.exists(directory):
  31. _logger.fatal(f'{directory!r} already exists')
  32. raise FileExistsError(f'{directory!r} already exists')
  33. startTime = datetime.datetime.utcnow()
  34. if self._id is None:
  35. self._id = f'git_{self._url.replace("/", "_")}_{startTime:%Y%m%dT%H%M%SZ}'
  36. bundle = f'{self._id}.bundle'
  37. if os.path.exists(bundle):
  38. _logger.fatal(f'{bundle!r} already exists')
  39. raise FileExistsError(f'{bundle!r} already exists')
  40. _, gitVersion, _ = codearchiver.subprocess.run_with_log(['git', '--version'])
  41. if not gitVersion.startswith('git version ') or not gitVersion.endswith('\n') or gitVersion[12:-1].strip('0123456789.') != '':
  42. raise RuntimeError(f'Unexpected output from `git --version`: {gitVersion!r}')
  43. gitVersion = gitVersion[12:-1]
  44. _logger.info(f'Cloning {self._url} into {directory}')
  45. codearchiver.subprocess.run_with_log(['git', 'clone', '--verbose', '--progress', '--mirror', self._url, directory], env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0'})
  46. if self._extraBranches:
  47. for branch, commit in self._extraBranches.items():
  48. _logger.info(f'Fetching commit {commit} as {branch}')
  49. r, _, _ = codearchiver.subprocess.run_with_log(['git', 'fetch', '--verbose', '--progress', 'origin', commit], cwd = directory, check = False)
  50. if r == 0:
  51. r2, _, _ = codearchiver.subprocess.run_with_log(['git', 'update-ref', f'refs/codearchiver/{branch}', commit, ''], cwd = directory, check = False)
  52. if r2 != 0:
  53. _logger.error(f'Failed to update-ref refs/codearchiver/{branch} to {commit}')
  54. else:
  55. _logger.error(f'Failed to fetch {commit}')
  56. # This leaves over a FETCH_HEAD file, but git-bundle does not care about that, so it can safely be ignored.
  57. _logger.info(f'Collecting repository metadata for index')
  58. _, refs, _ = codearchiver.subprocess.run_with_log(['git', 'show-ref'], cwd = directory)
  59. _, commits, _ = codearchiver.subprocess.run_with_log(['git', 'log', '--reflog', '--all', '--format=format:%H% P'], cwd = directory)
  60. commits = list(map(functools.partial(str.split, sep = ' '), commits.splitlines()))
  61. rootCommits = [c[0] for c in commits if len(c) == 1]
  62. # Check whether there are relevant prior bundles to create an incremental one
  63. # Collect their commits shared with this clone (else `git bundle` complains about 'bad object')
  64. commitSet = set(c[0] for c in commits) # For fast lookup
  65. oldCommits = {} # dict to keep the order reasonable
  66. basedOnBundles = {} # ditto
  67. if self._storage:
  68. for oldBundle in self._storage.search_indices([('Root commit', c) for c in rootCommits]):
  69. if not oldBundle.startswith('git_'): #TODO Is there a more generic and elegant approach?
  70. continue
  71. _logger.info(f'Previous bundle: {oldBundle!r}')
  72. with self._storage.open_index(oldBundle) as fp:
  73. idx = GitIndex.deserialise(fp)
  74. for key, value in idx:
  75. if key == 'Commit' and value in commitSet:
  76. oldCommits[value] = True
  77. basedOnBundles[oldBundle] = True
  78. _logger.info(f'Bundling into {bundle}')
  79. status , _, stderr = codearchiver.subprocess.run_with_log(['git', 'bundle', 'create', '--progress', f'../{bundle}', '--stdin', '--reflog', '--all'], cwd = directory, input = ''.join(f'^{commit}\n' for commit in oldCommits).encode('ascii'), check = False)
  80. if status == 128 and stderr == 'fatal: Refusing to create empty bundle.\n':
  81. # Manually write an empty bundle instead
  82. # Cf. Documentation/technical/bundle-format.txt and Documentation/technical/pack-format.txt in git's repository for details on the formats
  83. _logger.info('Writing empty bundle directly instead')
  84. with open(bundle, 'wb') as fp:
  85. fp.write(b'# v2 git bundle\n') # bundle signature
  86. fp.write(b'\n') # bundle end of prerequisites and refs
  87. packdata = b'PACK' # pack signature
  88. packdata += b'\0\0\0\x02' # pack version
  89. packdata += b'\0\0\0\0' # pack number of objects
  90. fp.write(packdata)
  91. fp.write(hashlib.sha1(packdata).digest()) # pack checksum trailer
  92. elif status != 0:
  93. raise RuntimeError(f'git bundle creation returned with non-zero exit status {status}.')
  94. _logger.info(f'Removing clone')
  95. shutil.rmtree(directory)
  96. index = self.create_index(bundle)
  97. index.append('Git version', gitVersion)
  98. for oldBundle in basedOnBundles:
  99. index.append('Based on bundle', oldBundle)
  100. for line in refs.splitlines():
  101. index.append('Ref', line)
  102. for commitHash, *parents in commits:
  103. if commitHash not in oldCommits:
  104. index.append('Commit', commitHash)
  105. if not parents:
  106. index.append('Root commit', commitHash)
  107. return codearchiver.core.Result(id = self._id, files = [(bundle, index)])
  108. def __repr__(self):
  109. return f'{type(self).__module__}.{type(self).__name__}({self._inputUrl!r}, extraBranches = {self._extraBranches!r})'