A VCS repository archival tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

  1. import codearchiver.core
  2. import datetime
  3. import logging
  4. import os.path
  5. import shutil
  6. import subprocess
  7. logger = logging.getLogger(__name__)
  8. class Git(codearchiver.core.Module):
  9. @staticmethod
  10. def matches(inputUrl):
  11. return inputUrl.url.endswith('.git')
  12. def __init__(self, inputUrl, extraBranches = {}):
  13. self._inputUrl = inputUrl
  14. self._url = inputUrl.url
  15. self._extraBranches = extraBranches
  16. def process(self):
  17. directory = self._url.rsplit('/', 1)[1]
  18. if os.path.exists(directory):
  19. logger.fatal(f'{directory!r} already exists')
  20. return
  21. startTime = datetime.datetime.utcnow()
  22. bundle = f'{self._url.replace("/", "_")}.{startTime:%Y%m%dT%H%M%SZ}.bundle'
  23. if os.path.exists(bundle):
  24. logger.fatal(f'{bundle!r} already exists')
  25. return
  26. logger.info(f'Cloning {self._url} into {directory}')
  27. subprocess.run(['git', 'clone', '--verbose', '--mirror', self._url, directory], check = True)
  28. if self._extraBranches:
  29. for branch, commit in self._extraBranches.items():
  30. logger.info(f'Fetching commit {commit} as {branch}')
  31. r = subprocess.run(['git', 'fetch', '--verbose', 'origin', commit], cwd = directory)
  32. if r.returncode == 0:
  33. r2 = subprocess.run(['git', 'update-ref', f'refs/codearchiver/{branch}', commit, ''], cwd = directory)
  34. if r2.returncode != 0:
  35. logger.error(f'Failed to update-ref refs/codearchiver/{branch} to {commit}')
  36. else:
  37. logger.error(f'Failed to fetch {commit}')
  38. logger.info(f'Bundling into {bundle}')
  39. subprocess.run(['git', 'bundle', 'create', f'../{bundle}', '--all'], cwd = directory, check = True)
  40. logger.info(f'Removing clone')
  41. shutil.rmtree(directory)
  42. return codearchiver.core.Result(id = f'git-{bundle[:-7]}', files = [bundle])