git.py 8.1 KB

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