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

126 рядки
5.6 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 GitMetadata(codearchiver.core.Metadata):
  12. fields = (
  13. codearchiver.core.MetadataField(key = 'Git version', required = True, repeatable = False),
  14. codearchiver.core.MetadataField(key = 'Based on bundle', required = False, repeatable = True),
  15. codearchiver.core.MetadataField(key = 'Ref', required = True, repeatable = True),
  16. codearchiver.core.MetadataField(key = 'Root commit', required = True, repeatable = True),
  17. codearchiver.core.MetadataField(key = 'Commit', required = False, repeatable = True),
  18. )
  19. class Git(codearchiver.core.Module):
  20. name = 'git'
  21. MetadataClass = GitMetadata
  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. bundle = f'{self._id}.bundle'
  34. if os.path.exists(bundle):
  35. _logger.fatal(f'{bundle!r} already exists')
  36. raise FileExistsError(f'{bundle!r} already exists')
  37. _, gitVersion, _ = codearchiver.subprocess.run_with_log(['git', '--version'])
  38. if not gitVersion.startswith('git version ') or not gitVersion.endswith('\n') or gitVersion[12:-1].strip('0123456789.') != '':
  39. raise RuntimeError(f'Unexpected output from `git --version`: {gitVersion!r}')
  40. gitVersion = gitVersion[12:-1]
  41. _logger.info(f'Cloning {self._url} into {directory}')
  42. startTime = datetime.datetime.utcnow()
  43. codearchiver.subprocess.run_with_log(['git', 'clone', '--verbose', '--progress', '--mirror', self._url, directory], env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0'})
  44. if self._extraBranches:
  45. for branch, commit in self._extraBranches.items():
  46. _logger.info(f'Fetching commit {commit} as {branch}')
  47. r, _, _ = codearchiver.subprocess.run_with_log(['git', 'fetch', '--verbose', '--progress', 'origin', commit], cwd = directory, check = False)
  48. if r == 0:
  49. r2, _, _ = codearchiver.subprocess.run_with_log(['git', 'update-ref', f'refs/codearchiver/{branch}', commit, ''], cwd = directory, check = False)
  50. if r2 != 0:
  51. _logger.error(f'Failed to update-ref refs/codearchiver/{branch} to {commit}')
  52. else:
  53. _logger.error(f'Failed to fetch {commit}')
  54. # This leaves over a FETCH_HEAD file, but git-bundle does not care about that, so it can safely be ignored.
  55. endTime = datetime.datetime.utcnow()
  56. _logger.info('Collecting repository metadata')
  57. _, refs, _ = codearchiver.subprocess.run_with_log(['git', 'show-ref'], cwd = directory)
  58. _, commits, _ = codearchiver.subprocess.run_with_log(['git', 'log', '--reflog', '--all', '--format=format:%H% P'], cwd = directory)
  59. commits = list(map(functools.partial(str.split, sep = ' '), commits.splitlines()))
  60. rootCommits = [c[0] for c in commits if len(c) == 1]
  61. # Check whether there are relevant prior bundles to create an incremental one
  62. # Collect their commits shared with this clone (else `git bundle` complains about 'bad object')
  63. commitSet = set(c[0] for c in commits) # For fast lookup
  64. oldCommits = {} # dict to keep the order reasonable
  65. basedOnBundles = {} # ditto
  66. if self._storage:
  67. for oldBundle in self._storage.search_metadata([('Module', type(self).name)] + [('Root commit', c) for c in rootCommits]):
  68. _logger.info(f'Previous bundle: {oldBundle!r}')
  69. with self._storage.open_metadata(oldBundle) as fp:
  70. idx = GitMetadata.deserialise(fp)
  71. for key, value in idx:
  72. if key == 'Commit' and value in commitSet:
  73. oldCommits[value] = True
  74. basedOnBundles[oldBundle] = True
  75. _logger.info(f'Bundling into {bundle}')
  76. 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)
  77. if status == 128 and stderr == 'fatal: Refusing to create empty bundle.\n':
  78. # Manually write an empty bundle instead
  79. # Cf. Documentation/technical/bundle-format.txt and Documentation/technical/pack-format.txt in git's repository for details on the formats
  80. _logger.info('Writing empty bundle directly instead')
  81. with open(bundle, 'wb') as fp:
  82. fp.write(b'# v2 git bundle\n') # bundle signature
  83. fp.write(b'\n') # bundle end of prerequisites and refs
  84. packdata = b'PACK' # pack signature
  85. packdata += b'\0\0\0\x02' # pack version
  86. packdata += b'\0\0\0\0' # pack number of objects
  87. fp.write(packdata)
  88. fp.write(hashlib.sha1(packdata).digest()) # pack checksum trailer
  89. elif status != 0:
  90. raise RuntimeError(f'git bundle creation returned with non-zero exit status {status}.')
  91. _logger.info(f'Removing clone')
  92. shutil.rmtree(directory)
  93. metadata = self.create_metadata(bundle, startTime, endTime)
  94. metadata.append('Git version', gitVersion)
  95. for oldBundle in basedOnBundles:
  96. metadata.append('Based on bundle', oldBundle)
  97. for line in refs.splitlines():
  98. metadata.append('Ref', line)
  99. for commitHash, *parents in commits:
  100. if commitHash not in oldCommits:
  101. metadata.append('Commit', commitHash)
  102. if not parents:
  103. metadata.append('Root commit', commitHash)
  104. return codearchiver.core.Result(id = self._id, files = [(bundle, metadata)])
  105. def __repr__(self):
  106. return f'{type(self).__module__}.{type(self).__name__}({self._inputUrl!r}, extraBranches = {self._extraBranches!r})'