git-make-shallow 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. #!/usr/bin/env python3
  2. """git-make-shallow: make the current git repository shallow
  3. Remove the history of the specified revisions, then optionally filter the
  4. available refs to those specified.
  5. """
  6. import argparse
  7. import collections
  8. import errno
  9. import itertools
  10. import os
  11. import subprocess
  12. import sys
  13. version = 1.0
  14. def main():
  15. if sys.version_info < (3, 4, 0):
  16. sys.exit('Python 3.4 or greater is required')
  17. git_dir = check_output(['git', 'rev-parse', '--git-dir']).rstrip()
  18. shallow_file = os.path.join(git_dir, 'shallow')
  19. if os.path.exists(shallow_file):
  20. try:
  21. check_output(['git', 'fetch', '--unshallow'])
  22. except subprocess.CalledProcessError:
  23. try:
  24. os.unlink(shallow_file)
  25. except OSError as exc:
  26. if exc.errno != errno.ENOENT:
  27. raise
  28. args = process_args()
  29. revs = check_output(['git', 'rev-list'] + args.revisions).splitlines()
  30. make_shallow(shallow_file, args.revisions, args.refs)
  31. ref_revs = check_output(['git', 'rev-list'] + args.refs).splitlines()
  32. remaining_history = set(revs) & set(ref_revs)
  33. for rev in remaining_history:
  34. if check_output(['git', 'rev-parse', '{}^@'.format(rev)]):
  35. sys.exit('Error: %s was not made shallow' % rev)
  36. filter_refs(args.refs)
  37. if args.shrink:
  38. shrink_repo(git_dir)
  39. subprocess.check_call(['git', 'fsck', '--unreachable'])
  40. def process_args():
  41. # TODO: add argument to automatically keep local-only refs, since they
  42. # can't be easily restored with a git fetch.
  43. parser = argparse.ArgumentParser(description='Remove the history of the specified revisions, then optionally filter the available refs to those specified.')
  44. parser.add_argument('--ref', '-r', metavar='REF', action='append', dest='refs', help='remove all but the specified refs (cumulative)')
  45. parser.add_argument('--shrink', '-s', action='store_true', help='shrink the git repository by repacking and pruning')
  46. parser.add_argument('revisions', metavar='REVISION', nargs='+', help='a git revision/commit')
  47. if len(sys.argv) < 2:
  48. parser.print_help()
  49. sys.exit(2)
  50. args = parser.parse_args()
  51. if args.refs:
  52. args.refs = check_output(['git', 'rev-parse', '--symbolic-full-name'] + args.refs).splitlines()
  53. else:
  54. args.refs = get_all_refs(lambda r, t, tt: t == 'commit' or tt == 'commit')
  55. args.refs = list(filter(lambda r: not r.endswith('/HEAD'), args.refs))
  56. args.revisions = check_output(['git', 'rev-parse'] + ['%s^{}' % i for i in args.revisions]).splitlines()
  57. return args
  58. def check_output(cmd, input=None):
  59. return subprocess.check_output(cmd, universal_newlines=True, input=input)
  60. def make_shallow(shallow_file, revisions, refs):
  61. """Remove the history of the specified revisions."""
  62. for rev in follow_history_intersections(revisions, refs):
  63. print("Processing %s" % rev)
  64. with open(shallow_file, 'a') as f:
  65. f.write(rev + '\n')
  66. def get_all_refs(ref_filter=None):
  67. """Return all the existing refs in this repository, optionally filtering the refs."""
  68. ref_output = check_output(['git', 'for-each-ref', '--format=%(refname)\t%(objecttype)\t%(*objecttype)'])
  69. ref_split = [tuple(iter_extend(l.rsplit('\t'), 3)) for l in ref_output.splitlines()]
  70. if ref_filter:
  71. ref_split = (e for e in ref_split if ref_filter(*e))
  72. refs = [r[0] for r in ref_split]
  73. return refs
  74. def iter_extend(iterable, length, obj=None):
  75. """Ensure that iterable is the specified length by extending with obj."""
  76. return itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length)
  77. def filter_refs(refs):
  78. """Remove all but the specified refs from the git repository."""
  79. all_refs = get_all_refs()
  80. to_remove = set(all_refs) - set(refs)
  81. if to_remove:
  82. check_output(['xargs', '-0', '-n', '1', 'git', 'update-ref', '-d', '--no-deref'],
  83. input=''.join(l + '\0' for l in to_remove))
  84. def follow_history_intersections(revisions, refs):
  85. """Determine all the points where the history of the specified revisions intersects the specified refs."""
  86. queue = collections.deque(revisions)
  87. seen = set()
  88. for rev in iter_except(queue.popleft, IndexError):
  89. if rev in seen:
  90. continue
  91. parents = check_output(['git', 'rev-parse', '%s^@' % rev]).splitlines()
  92. yield rev
  93. seen.add(rev)
  94. if not parents:
  95. continue
  96. check_refs = check_output(['git', 'merge-base', '--independent'] + sorted(refs)).splitlines()
  97. for parent in parents:
  98. for ref in check_refs:
  99. print("Checking %s vs %s" % (parent, ref))
  100. try:
  101. merge_base = check_output(['git', 'merge-base', parent, ref]).rstrip()
  102. except subprocess.CalledProcessError:
  103. continue
  104. else:
  105. queue.append(merge_base)
  106. def iter_except(func, exception, start=None):
  107. """Yield a function repeatedly until it raises an exception."""
  108. try:
  109. if start is not None:
  110. yield start()
  111. while True:
  112. yield func()
  113. except exception:
  114. pass
  115. def shrink_repo(git_dir):
  116. """Shrink the newly shallow repository, removing the unreachable objects."""
  117. subprocess.check_call(['git', 'reflog', 'expire', '--expire-unreachable=now', '--all'])
  118. subprocess.check_call(['git', 'repack', '-ad'])
  119. try:
  120. os.unlink(os.path.join(git_dir, 'objects', 'info', 'alternates'))
  121. except OSError as exc:
  122. if exc.errno != errno.ENOENT:
  123. raise
  124. subprocess.check_call(['git', 'prune', '--expire', 'now'])
  125. if __name__ == '__main__':
  126. main()