gitutil.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0+
  4. #
  5. import command
  6. import re
  7. import os
  8. import series
  9. import subprocess
  10. import sys
  11. import terminal
  12. import checkpatch
  13. import settings
  14. def CountCommitsToBranch():
  15. """Returns number of commits between HEAD and the tracking branch.
  16. This looks back to the tracking branch and works out the number of commits
  17. since then.
  18. Return:
  19. Number of patches that exist on top of the branch
  20. """
  21. pipe = [['git', 'log', '--no-color', '--oneline', '--no-decorate',
  22. '@{upstream}..'],
  23. ['wc', '-l']]
  24. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  25. patch_count = int(stdout)
  26. return patch_count
  27. def GetUpstream(git_dir, branch):
  28. """Returns the name of the upstream for a branch
  29. Args:
  30. git_dir: Git directory containing repo
  31. branch: Name of branch
  32. Returns:
  33. Name of upstream branch (e.g. 'upstream/master') or None if none
  34. """
  35. try:
  36. remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  37. 'branch.%s.remote' % branch)
  38. merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  39. 'branch.%s.merge' % branch)
  40. except:
  41. return None
  42. if remote == '.':
  43. return merge
  44. elif remote and merge:
  45. leaf = merge.split('/')[-1]
  46. return '%s/%s' % (remote, leaf)
  47. else:
  48. raise ValueError, ("Cannot determine upstream branch for branch "
  49. "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
  50. def GetRangeInBranch(git_dir, branch, include_upstream=False):
  51. """Returns an expression for the commits in the given branch.
  52. Args:
  53. git_dir: Directory containing git repo
  54. branch: Name of branch
  55. Return:
  56. Expression in the form 'upstream..branch' which can be used to
  57. access the commits. If the branch does not exist, returns None.
  58. """
  59. upstream = GetUpstream(git_dir, branch)
  60. if not upstream:
  61. return None
  62. return '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
  63. def CountCommitsInBranch(git_dir, branch, include_upstream=False):
  64. """Returns the number of commits in the given branch.
  65. Args:
  66. git_dir: Directory containing git repo
  67. branch: Name of branch
  68. Return:
  69. Number of patches that exist on top of the branch, or None if the
  70. branch does not exist.
  71. """
  72. range_expr = GetRangeInBranch(git_dir, branch, include_upstream)
  73. if not range_expr:
  74. return None
  75. pipe = [['git', '--git-dir', git_dir, 'log', '--oneline', '--no-decorate',
  76. range_expr],
  77. ['wc', '-l']]
  78. result = command.RunPipe(pipe, capture=True, oneline=True)
  79. patch_count = int(result.stdout)
  80. return patch_count
  81. def CountCommits(commit_range):
  82. """Returns the number of commits in the given range.
  83. Args:
  84. commit_range: Range of commits to count (e.g. 'HEAD..base')
  85. Return:
  86. Number of patches that exist on top of the branch
  87. """
  88. pipe = [['git', 'log', '--oneline', '--no-decorate', commit_range],
  89. ['wc', '-l']]
  90. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  91. patch_count = int(stdout)
  92. return patch_count
  93. def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
  94. """Checkout the selected commit for this build
  95. Args:
  96. commit_hash: Commit hash to check out
  97. """
  98. pipe = ['git']
  99. if git_dir:
  100. pipe.extend(['--git-dir', git_dir])
  101. if work_tree:
  102. pipe.extend(['--work-tree', work_tree])
  103. pipe.append('checkout')
  104. if force:
  105. pipe.append('-f')
  106. pipe.append(commit_hash)
  107. result = command.RunPipe([pipe], capture=True, raise_on_error=False)
  108. if result.return_code != 0:
  109. raise OSError, 'git checkout (%s): %s' % (pipe, result.stderr)
  110. def Clone(git_dir, output_dir):
  111. """Checkout the selected commit for this build
  112. Args:
  113. commit_hash: Commit hash to check out
  114. """
  115. pipe = ['git', 'clone', git_dir, '.']
  116. result = command.RunPipe([pipe], capture=True, cwd=output_dir)
  117. if result.return_code != 0:
  118. raise OSError, 'git clone: %s' % result.stderr
  119. def Fetch(git_dir=None, work_tree=None):
  120. """Fetch from the origin repo
  121. Args:
  122. commit_hash: Commit hash to check out
  123. """
  124. pipe = ['git']
  125. if git_dir:
  126. pipe.extend(['--git-dir', git_dir])
  127. if work_tree:
  128. pipe.extend(['--work-tree', work_tree])
  129. pipe.append('fetch')
  130. result = command.RunPipe([pipe], capture=True)
  131. if result.return_code != 0:
  132. raise OSError, 'git fetch: %s' % result.stderr
  133. def CreatePatches(start, count, series):
  134. """Create a series of patches from the top of the current branch.
  135. The patch files are written to the current directory using
  136. git format-patch.
  137. Args:
  138. start: Commit to start from: 0=HEAD, 1=next one, etc.
  139. count: number of commits to include
  140. Return:
  141. Filename of cover letter
  142. List of filenames of patch files
  143. """
  144. if series.get('version'):
  145. version = '%s ' % series['version']
  146. cmd = ['git', 'format-patch', '-M', '--signoff']
  147. if series.get('cover'):
  148. cmd.append('--cover-letter')
  149. prefix = series.GetPatchPrefix()
  150. if prefix:
  151. cmd += ['--subject-prefix=%s' % prefix]
  152. cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
  153. stdout = command.RunList(cmd)
  154. files = stdout.splitlines()
  155. # We have an extra file if there is a cover letter
  156. if series.get('cover'):
  157. return files[0], files[1:]
  158. else:
  159. return None, files
  160. def ApplyPatch(verbose, fname):
  161. """Apply a patch with git am to test it
  162. TODO: Convert these to use command, with stderr option
  163. Args:
  164. fname: filename of patch file to apply
  165. """
  166. col = terminal.Color()
  167. cmd = ['git', 'am', fname]
  168. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  169. stderr=subprocess.PIPE)
  170. stdout, stderr = pipe.communicate()
  171. re_error = re.compile('^error: patch failed: (.+):(\d+)')
  172. for line in stderr.splitlines():
  173. if verbose:
  174. print line
  175. match = re_error.match(line)
  176. if match:
  177. print checkpatch.GetWarningMsg(col, 'warning', match.group(1),
  178. int(match.group(2)), 'Patch failed')
  179. return pipe.returncode == 0, stdout
  180. def ApplyPatches(verbose, args, start_point):
  181. """Apply the patches with git am to make sure all is well
  182. Args:
  183. verbose: Print out 'git am' output verbatim
  184. args: List of patch files to apply
  185. start_point: Number of commits back from HEAD to start applying.
  186. Normally this is len(args), but it can be larger if a start
  187. offset was given.
  188. """
  189. error_count = 0
  190. col = terminal.Color()
  191. # Figure out our current position
  192. cmd = ['git', 'name-rev', 'HEAD', '--name-only']
  193. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  194. stdout, stderr = pipe.communicate()
  195. if pipe.returncode:
  196. str = 'Could not find current commit name'
  197. print col.Color(col.RED, str)
  198. print stdout
  199. return False
  200. old_head = stdout.splitlines()[0]
  201. # Checkout the required start point
  202. cmd = ['git', 'checkout', 'HEAD~%d' % start_point]
  203. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  204. stderr=subprocess.PIPE)
  205. stdout, stderr = pipe.communicate()
  206. if pipe.returncode:
  207. str = 'Could not move to commit before patch series'
  208. print col.Color(col.RED, str)
  209. print stdout, stderr
  210. return False
  211. # Apply all the patches
  212. for fname in args:
  213. ok, stdout = ApplyPatch(verbose, fname)
  214. if not ok:
  215. print col.Color(col.RED, 'git am returned errors for %s: will '
  216. 'skip this patch' % fname)
  217. if verbose:
  218. print stdout
  219. error_count += 1
  220. cmd = ['git', 'am', '--skip']
  221. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  222. stdout, stderr = pipe.communicate()
  223. if pipe.returncode != 0:
  224. print col.Color(col.RED, 'Unable to skip patch! Aborting...')
  225. print stdout
  226. break
  227. # Return to our previous position
  228. cmd = ['git', 'checkout', old_head]
  229. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  230. stdout, stderr = pipe.communicate()
  231. if pipe.returncode:
  232. print col.Color(col.RED, 'Could not move back to head commit')
  233. print stdout, stderr
  234. return error_count == 0
  235. def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
  236. """Build a list of email addresses based on an input list.
  237. Takes a list of email addresses and aliases, and turns this into a list
  238. of only email address, by resolving any aliases that are present.
  239. If the tag is given, then each email address is prepended with this
  240. tag and a space. If the tag starts with a minus sign (indicating a
  241. command line parameter) then the email address is quoted.
  242. Args:
  243. in_list: List of aliases/email addresses
  244. tag: Text to put before each address
  245. alias: Alias dictionary
  246. raise_on_error: True to raise an error when an alias fails to match,
  247. False to just print a message.
  248. Returns:
  249. List of email addresses
  250. >>> alias = {}
  251. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  252. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  253. >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
  254. >>> alias['boys'] = ['fred', ' john']
  255. >>> alias['all'] = ['fred ', 'john', ' mary ']
  256. >>> BuildEmailList(['john', 'mary'], None, alias)
  257. ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
  258. >>> BuildEmailList(['john', 'mary'], '--to', alias)
  259. ['--to "j.bloggs@napier.co.nz"', \
  260. '--to "Mary Poppins <m.poppins@cloud.net>"']
  261. >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
  262. ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
  263. """
  264. quote = '"' if tag and tag[0] == '-' else ''
  265. raw = []
  266. for item in in_list:
  267. raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
  268. result = []
  269. for item in raw:
  270. if not item in result:
  271. result.append(item)
  272. if tag:
  273. return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
  274. return result
  275. def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
  276. self_only=False, alias=None, in_reply_to=None):
  277. """Email a patch series.
  278. Args:
  279. series: Series object containing destination info
  280. cover_fname: filename of cover letter
  281. args: list of filenames of patch files
  282. dry_run: Just return the command that would be run
  283. raise_on_error: True to raise an error when an alias fails to match,
  284. False to just print a message.
  285. cc_fname: Filename of Cc file for per-commit Cc
  286. self_only: True to just email to yourself as a test
  287. in_reply_to: If set we'll pass this to git as --in-reply-to.
  288. Should be a message ID that this is in reply to.
  289. Returns:
  290. Git command that was/would be run
  291. # For the duration of this doctest pretend that we ran patman with ./patman
  292. >>> _old_argv0 = sys.argv[0]
  293. >>> sys.argv[0] = './patman'
  294. >>> alias = {}
  295. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  296. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  297. >>> alias['mary'] = ['m.poppins@cloud.net']
  298. >>> alias['boys'] = ['fred', ' john']
  299. >>> alias['all'] = ['fred ', 'john', ' mary ']
  300. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  301. >>> series = series.Series()
  302. >>> series.to = ['fred']
  303. >>> series.cc = ['mary']
  304. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  305. False, alias)
  306. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  307. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  308. >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
  309. alias)
  310. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  311. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
  312. >>> series.cc = ['all']
  313. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  314. True, alias)
  315. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  316. --cc-cmd cc-fname" cover p1 p2'
  317. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  318. False, alias)
  319. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  320. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  321. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  322. # Restore argv[0] since we clobbered it.
  323. >>> sys.argv[0] = _old_argv0
  324. """
  325. to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
  326. if not to:
  327. print ("No recipient, please add something like this to a commit\n"
  328. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>")
  329. return
  330. cc = BuildEmailList(series.get('cc'), '--cc', alias, raise_on_error)
  331. if self_only:
  332. to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
  333. cc = []
  334. cmd = ['git', 'send-email', '--annotate']
  335. if in_reply_to:
  336. cmd.append('--in-reply-to="%s"' % in_reply_to)
  337. cmd += to
  338. cmd += cc
  339. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  340. if cover_fname:
  341. cmd.append(cover_fname)
  342. cmd += args
  343. str = ' '.join(cmd)
  344. if not dry_run:
  345. os.system(str)
  346. return str
  347. def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
  348. """If an email address is an alias, look it up and return the full name
  349. TODO: Why not just use git's own alias feature?
  350. Args:
  351. lookup_name: Alias or email address to look up
  352. alias: Dictionary containing aliases (None to use settings default)
  353. raise_on_error: True to raise an error when an alias fails to match,
  354. False to just print a message.
  355. Returns:
  356. tuple:
  357. list containing a list of email addresses
  358. Raises:
  359. OSError if a recursive alias reference was found
  360. ValueError if an alias was not found
  361. >>> alias = {}
  362. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  363. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  364. >>> alias['mary'] = ['m.poppins@cloud.net']
  365. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  366. >>> alias['all'] = ['fred ', 'john', ' mary ']
  367. >>> alias['loop'] = ['other', 'john', ' mary ']
  368. >>> alias['other'] = ['loop', 'john', ' mary ']
  369. >>> LookupEmail('mary', alias)
  370. ['m.poppins@cloud.net']
  371. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  372. ['arthur.wellesley@howe.ro.uk']
  373. >>> LookupEmail('boys', alias)
  374. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  375. >>> LookupEmail('all', alias)
  376. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  377. >>> LookupEmail('odd', alias)
  378. Traceback (most recent call last):
  379. ...
  380. ValueError: Alias 'odd' not found
  381. >>> LookupEmail('loop', alias)
  382. Traceback (most recent call last):
  383. ...
  384. OSError: Recursive email alias at 'other'
  385. >>> LookupEmail('odd', alias, raise_on_error=False)
  386. \033[1;31mAlias 'odd' not found\033[0m
  387. []
  388. >>> # In this case the loop part will effectively be ignored.
  389. >>> LookupEmail('loop', alias, raise_on_error=False)
  390. \033[1;31mRecursive email alias at 'other'\033[0m
  391. \033[1;31mRecursive email alias at 'john'\033[0m
  392. \033[1;31mRecursive email alias at 'mary'\033[0m
  393. ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  394. """
  395. if not alias:
  396. alias = settings.alias
  397. lookup_name = lookup_name.strip()
  398. if '@' in lookup_name: # Perhaps a real email address
  399. return [lookup_name]
  400. lookup_name = lookup_name.lower()
  401. col = terminal.Color()
  402. out_list = []
  403. if level > 10:
  404. msg = "Recursive email alias at '%s'" % lookup_name
  405. if raise_on_error:
  406. raise OSError, msg
  407. else:
  408. print col.Color(col.RED, msg)
  409. return out_list
  410. if lookup_name:
  411. if not lookup_name in alias:
  412. msg = "Alias '%s' not found" % lookup_name
  413. if raise_on_error:
  414. raise ValueError, msg
  415. else:
  416. print col.Color(col.RED, msg)
  417. return out_list
  418. for item in alias[lookup_name]:
  419. todo = LookupEmail(item, alias, raise_on_error, level + 1)
  420. for new_item in todo:
  421. if not new_item in out_list:
  422. out_list.append(new_item)
  423. #print "No match for alias '%s'" % lookup_name
  424. return out_list
  425. def GetTopLevel():
  426. """Return name of top-level directory for this git repo.
  427. Returns:
  428. Full path to git top-level directory
  429. This test makes sure that we are running tests in the right subdir
  430. >>> os.path.realpath(os.path.dirname(__file__)) == \
  431. os.path.join(GetTopLevel(), 'tools', 'patman')
  432. True
  433. """
  434. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  435. def GetAliasFile():
  436. """Gets the name of the git alias file.
  437. Returns:
  438. Filename of git alias file, or None if none
  439. """
  440. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
  441. raise_on_error=False)
  442. if fname:
  443. fname = os.path.join(GetTopLevel(), fname.strip())
  444. return fname
  445. def GetDefaultUserName():
  446. """Gets the user.name from .gitconfig file.
  447. Returns:
  448. User name found in .gitconfig file, or None if none
  449. """
  450. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  451. return uname
  452. def GetDefaultUserEmail():
  453. """Gets the user.email from the global .gitconfig file.
  454. Returns:
  455. User's email found in .gitconfig file, or None if none
  456. """
  457. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  458. return uemail
  459. def Setup():
  460. """Set up git utils, by reading the alias files."""
  461. # Check for a git alias file also
  462. alias_fname = GetAliasFile()
  463. if alias_fname:
  464. settings.ReadGitAliases(alias_fname)
  465. def GetHead():
  466. """Get the hash of the current HEAD
  467. Returns:
  468. Hash of HEAD
  469. """
  470. return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
  471. if __name__ == "__main__":
  472. import doctest
  473. doctest.testmod()