git.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/env python3
  2. """Git helper functions.
  3. Everything here should be project agnostic: it shouldn't rely on project's
  4. structure, or make assumptions about the passed arguments or calls' outcomes.
  5. """
  6. import io
  7. import os
  8. import posixpath
  9. import re
  10. import subprocess
  11. import sys
  12. SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
  13. sys.path.append(SCRIPT_DIR)
  14. from patches import PATCH_FILENAME_PREFIX, is_patch_location_line
  15. UPSTREAM_HEAD='refs/patches/upstream-head'
  16. def is_repo_root(path):
  17. path_exists = os.path.exists(path)
  18. if not path_exists:
  19. return False
  20. git_folder_path = os.path.join(path, '.git')
  21. git_folder_exists = os.path.exists(git_folder_path)
  22. return git_folder_exists
  23. def get_repo_root(path):
  24. """Finds a closest ancestor folder which is a repo root."""
  25. norm_path = os.path.normpath(path)
  26. norm_path_exists = os.path.exists(norm_path)
  27. if not norm_path_exists:
  28. return None
  29. if is_repo_root(norm_path):
  30. return norm_path
  31. parent_path = os.path.dirname(norm_path)
  32. # Check if we're in the root folder already.
  33. if parent_path == norm_path:
  34. return None
  35. return get_repo_root(parent_path)
  36. def am(repo, patch_data, threeway=False, directory=None, exclude=None,
  37. committer_name=None, committer_email=None, keep_cr=True):
  38. args = []
  39. if threeway:
  40. args += ['--3way']
  41. if directory is not None:
  42. args += ['--directory', directory]
  43. if exclude is not None:
  44. for path_pattern in exclude:
  45. args += ['--exclude', path_pattern]
  46. if keep_cr is True:
  47. # Keep the CR of CRLF in case any patches target files with Windows line
  48. # endings.
  49. args += ['--keep-cr']
  50. root_args = ['-C', repo]
  51. if committer_name is not None:
  52. root_args += ['-c', 'user.name=' + committer_name]
  53. if committer_email is not None:
  54. root_args += ['-c', 'user.email=' + committer_email]
  55. root_args += ['-c', 'commit.gpgsign=false']
  56. command = ['git'] + root_args + ['am'] + args
  57. with subprocess.Popen(command, stdin=subprocess.PIPE) as proc:
  58. proc.communicate(patch_data.encode('utf-8'))
  59. if proc.returncode != 0:
  60. raise RuntimeError(f"Command {command} returned {proc.returncode}")
  61. def import_patches(repo, ref=UPSTREAM_HEAD, **kwargs):
  62. """same as am(), but we save the upstream HEAD so we can refer to it when we
  63. later export patches"""
  64. update_ref(repo=repo, ref=ref, newvalue='HEAD')
  65. am(repo=repo, **kwargs)
  66. def update_ref(repo, ref, newvalue):
  67. args = ['git', '-C', repo, 'update-ref', ref, newvalue]
  68. return subprocess.check_call(args)
  69. def get_commit_for_ref(repo, ref):
  70. args = ['git', '-C', repo, 'rev-parse', '--verify', ref]
  71. return subprocess.check_output(args).decode('utf-8').strip()
  72. def get_commit_count(repo, commit_range):
  73. args = ['git', '-C', repo, 'rev-list', '--count', commit_range]
  74. return int(subprocess.check_output(args).decode('utf-8').strip())
  75. def guess_base_commit(repo, ref):
  76. """Guess which commit the patches might be based on"""
  77. try:
  78. upstream_head = get_commit_for_ref(repo, ref)
  79. num_commits = get_commit_count(repo, upstream_head + '..')
  80. return [upstream_head, num_commits]
  81. except subprocess.CalledProcessError:
  82. args = [
  83. 'git',
  84. '-C',
  85. repo,
  86. 'describe',
  87. '--tags',
  88. ]
  89. return subprocess.check_output(args).decode('utf-8').rsplit('-', 2)[0:2]
  90. def format_patch(repo, since):
  91. args = [
  92. 'git',
  93. '-C',
  94. repo,
  95. '-c',
  96. 'core.attributesfile='
  97. + os.path.join(
  98. os.path.dirname(os.path.realpath(__file__)),
  99. 'electron.gitattributes',
  100. ),
  101. # Ensure it is not possible to match anything
  102. # Disabled for now as we have consistent chunk headers
  103. # '-c',
  104. # 'diff.electron.xfuncname=$^',
  105. 'format-patch',
  106. '--keep-subject',
  107. '--no-stat',
  108. '--stdout',
  109. # Per RFC 3676 the signature is separated from the body by a line with
  110. # '-- ' on it. If the signature option is omitted the signature defaults
  111. # to the Git version number.
  112. '--no-signature',
  113. # The name of the parent commit object isn't useful information in this
  114. # context, so zero it out to avoid needless patch-file churn.
  115. '--zero-commit',
  116. # Some versions of git print out different numbers of characters in the
  117. # 'index' line of patches, so pass --full-index to get consistent
  118. # behaviour.
  119. '--full-index',
  120. since
  121. ]
  122. return subprocess.check_output(args).decode('utf-8')
  123. def split_patches(patch_data):
  124. """Split a concatenated series of patches into N separate patches"""
  125. patches = []
  126. patch_start = re.compile('^From [0-9a-f]+ ')
  127. # Keep line endings in case any patches target files with CRLF.
  128. keep_line_endings = True
  129. for line in patch_data.splitlines(keep_line_endings):
  130. if patch_start.match(line):
  131. patches.append([])
  132. patches[-1].append(line)
  133. return patches
  134. def filter_patches(patches, key):
  135. """Return patches that include the specified key"""
  136. if key is None:
  137. return patches
  138. matches = []
  139. for patch in patches:
  140. if any(key in line for line in patch):
  141. matches.append(patch)
  142. continue
  143. return matches
  144. def munge_subject_to_filename(subject):
  145. """Derive a suitable filename from a commit's subject"""
  146. if subject.endswith('.patch'):
  147. subject = subject[:-6]
  148. return re.sub(r'[^A-Za-z0-9-]+', '_', subject).strip('_').lower() + '.patch'
  149. def get_file_name(patch):
  150. """Return the name of the file to which the patch should be written"""
  151. file_name = None
  152. for line in patch:
  153. if line.startswith(PATCH_FILENAME_PREFIX):
  154. file_name = line[len(PATCH_FILENAME_PREFIX):]
  155. break
  156. # If no patch-filename header, munge the subject.
  157. if not file_name:
  158. for line in patch:
  159. if line.startswith('Subject: '):
  160. file_name = munge_subject_to_filename(line[len('Subject: '):])
  161. break
  162. return file_name.rstrip('\n')
  163. def join_patch(patch):
  164. """Joins and formats patch contents"""
  165. return ''.join(remove_patch_location(patch)).rstrip('\n') + '\n'
  166. def remove_patch_location(patch):
  167. """Strip out the patch location lines from a patch's message body"""
  168. force_keep_next_line = False
  169. n = len(patch)
  170. for i, l in enumerate(patch):
  171. skip_line = is_patch_location_line(l)
  172. skip_next = i < n - 1 and is_patch_location_line(patch[i + 1])
  173. if not force_keep_next_line and (
  174. skip_line or (skip_next and len(l.rstrip()) == 0)
  175. ):
  176. pass # drop this line
  177. else:
  178. yield l
  179. force_keep_next_line = l.startswith('Subject: ')
  180. def export_patches(repo, out_dir,
  181. patch_range=None, ref=UPSTREAM_HEAD,
  182. dry_run=False, grep=None):
  183. if not os.path.exists(repo):
  184. sys.stderr.write(
  185. f"Skipping patches in {repo} because it does not exist.\n"
  186. )
  187. return
  188. if patch_range is None:
  189. patch_range, n_patches = guess_base_commit(repo, ref)
  190. msg = f"Exporting {n_patches} patches in {repo} since {patch_range[0:7]}\n"
  191. sys.stderr.write(msg)
  192. patch_data = format_patch(repo, patch_range)
  193. patches = split_patches(patch_data)
  194. if grep:
  195. olen = len(patches)
  196. patches = filter_patches(patches, grep)
  197. sys.stderr.write(f"Exporting {len(patches)} of {olen} patches\n")
  198. try:
  199. os.mkdir(out_dir)
  200. except OSError:
  201. pass
  202. if dry_run:
  203. # If we're doing a dry run, iterate through each patch and see if the newly
  204. # exported patch differs from what exists. Report number of mismatched
  205. # patches and fail if there's more than one.
  206. bad_patches = []
  207. for patch in patches:
  208. filename = get_file_name(patch)
  209. filepath = posixpath.join(out_dir, filename)
  210. with io.open(filepath, 'rb') as inp:
  211. existing_patch = str(inp.read(), 'utf-8')
  212. formatted_patch = join_patch(patch)
  213. if formatted_patch != existing_patch:
  214. bad_patches.append(filename)
  215. if len(bad_patches) > 0:
  216. sys.stderr.write(
  217. "Patches in {} not up to date: {} patches need update\n-- {}\n".format(
  218. out_dir, len(bad_patches), "\n-- ".join(bad_patches)
  219. )
  220. )
  221. sys.exit(1)
  222. else:
  223. # Remove old patches so that deleted commits are correctly reflected in the
  224. # patch files (as a removed file)
  225. for p in os.listdir(out_dir):
  226. if p.endswith('.patch'):
  227. os.remove(posixpath.join(out_dir, p))
  228. with io.open(
  229. posixpath.join(out_dir, '.patches'),
  230. 'w',
  231. newline='\n',
  232. encoding='utf-8',
  233. ) as pl:
  234. for patch in patches:
  235. filename = get_file_name(patch)
  236. file_path = posixpath.join(out_dir, filename)
  237. formatted_patch = join_patch(patch)
  238. # Write in binary mode to retain mixed line endings on write.
  239. with io.open(
  240. file_path, 'wb'
  241. ) as f:
  242. f.write(formatted_patch.encode('utf-8'))
  243. pl.write(filename + '\n')