git.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. '--notes',
  126. '--stdout',
  127. # Per RFC 3676 the signature is separated from the body by a line with
  128. # '-- ' on it. If the signature option is omitted the signature defaults
  129. # to the Git version number.
  130. '--no-signature',
  131. # The name of the parent commit object isn't useful information in this
  132. # context, so zero it out to avoid needless patch-file churn.
  133. '--zero-commit',
  134. # Some versions of git print out different numbers of characters in the
  135. # 'index' line of patches, so pass --full-index to get consistent
  136. # behaviour.
  137. '--full-index',
  138. since
  139. ]
  140. return subprocess.check_output(args).decode('utf-8')
  141. def split_patches(patch_data):
  142. """Split a concatenated series of patches into N separate patches"""
  143. patches = []
  144. patch_start = re.compile('^From [0-9a-f]+ ')
  145. # Keep line endings in case any patches target files with CRLF.
  146. keep_line_endings = True
  147. for line in patch_data.splitlines(keep_line_endings):
  148. if patch_start.match(line):
  149. patches.append([])
  150. patches[-1].append(line)
  151. return patches
  152. def filter_patches(patches, key):
  153. """Return patches that include the specified key"""
  154. if key is None:
  155. return patches
  156. matches = []
  157. for patch in patches:
  158. if any(key in line for line in patch):
  159. matches.append(patch)
  160. continue
  161. return matches
  162. def munge_subject_to_filename(subject):
  163. """Derive a suitable filename from a commit's subject"""
  164. if subject.endswith('.patch'):
  165. subject = subject[:-6]
  166. return re.sub(r'[^A-Za-z0-9-]+', '_', subject).strip('_').lower() + '.patch'
  167. def get_file_name(patch):
  168. """Return the name of the file to which the patch should be written"""
  169. file_name = None
  170. for line in patch:
  171. if line.startswith('Patch-Filename: '):
  172. file_name = line[len('Patch-Filename: '):]
  173. break
  174. # If no patch-filename header, munge the subject.
  175. if not file_name:
  176. for line in patch:
  177. if line.startswith('Subject: '):
  178. file_name = munge_subject_to_filename(line[len('Subject: '):])
  179. break
  180. return file_name.rstrip('\n')
  181. def join_patch(patch):
  182. """Joins and formats patch contents"""
  183. return ''.join(remove_patch_filename(patch)).rstrip('\n') + '\n'
  184. def remove_patch_filename(patch):
  185. """Strip out the Patch-Filename trailer from a patch's message body"""
  186. force_keep_next_line = False
  187. for i, l in enumerate(patch):
  188. is_patchfilename = l.startswith('Patch-Filename: ')
  189. next_is_patchfilename = i < len(patch) - 1 and patch[i + 1].startswith(
  190. 'Patch-Filename: '
  191. )
  192. if not force_keep_next_line and (
  193. is_patchfilename or (next_is_patchfilename and len(l.rstrip()) == 0)
  194. ):
  195. pass # drop this line
  196. else:
  197. yield l
  198. force_keep_next_line = l.startswith('Subject: ')
  199. def export_patches(repo, out_dir, patch_range=None, dry_run=False, grep=None):
  200. if not os.path.exists(repo):
  201. sys.stderr.write(
  202. "Skipping patches in {} because it does not exist.\n".format(repo)
  203. )
  204. return
  205. if patch_range is None:
  206. patch_range, num_patches = guess_base_commit(repo)
  207. sys.stderr.write("Exporting {} patches in {} since {}\n".format(
  208. num_patches, repo, patch_range[0:7]))
  209. patch_data = format_patch(repo, patch_range)
  210. patches = split_patches(patch_data)
  211. if grep:
  212. patches = filter_patches(patches, grep)
  213. try:
  214. os.mkdir(out_dir)
  215. except OSError:
  216. pass
  217. if dry_run:
  218. # If we're doing a dry run, iterate through each patch and see if the newly
  219. # exported patch differs from what exists. Report number of mismatched
  220. # patches and fail if there's more than one.
  221. bad_patches = []
  222. for patch in patches:
  223. filename = get_file_name(patch)
  224. filepath = posixpath.join(out_dir, filename)
  225. existing_patch = str(io.open(filepath, 'rb').read(), 'utf-8')
  226. formatted_patch = join_patch(patch)
  227. if formatted_patch != existing_patch:
  228. bad_patches.append(filename)
  229. if len(bad_patches) > 0:
  230. sys.stderr.write(
  231. "Patches in {} not up to date: {} patches need update\n-- {}\n".format(
  232. out_dir, len(bad_patches), "\n-- ".join(bad_patches)
  233. )
  234. )
  235. sys.exit(1)
  236. else:
  237. # Remove old patches so that deleted commits are correctly reflected in the
  238. # patch files (as a removed file)
  239. for p in os.listdir(out_dir):
  240. if p.endswith('.patch'):
  241. os.remove(posixpath.join(out_dir, p))
  242. with io.open(
  243. posixpath.join(out_dir, '.patches'),
  244. 'w',
  245. newline='\n',
  246. encoding='utf-8',
  247. ) as pl:
  248. for patch in patches:
  249. filename = get_file_name(patch)
  250. file_path = posixpath.join(out_dir, filename)
  251. formatted_patch = join_patch(patch)
  252. # Write in binary mode to retain mixed line endings on write.
  253. with io.open(
  254. file_path, 'wb'
  255. ) as f:
  256. f.write(formatted_patch.encode('utf-8'))
  257. pl.write(filename + '\n')