gitutil.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. if old_head == 'undefined':
  202. str = "Invalid HEAD '%s'" % stdout.strip()
  203. print col.Color(col.RED, str)
  204. return False
  205. # Checkout the required start point
  206. cmd = ['git', 'checkout', 'HEAD~%d' % start_point]
  207. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  208. stderr=subprocess.PIPE)
  209. stdout, stderr = pipe.communicate()
  210. if pipe.returncode:
  211. str = 'Could not move to commit before patch series'
  212. print col.Color(col.RED, str)
  213. print stdout, stderr
  214. return False
  215. # Apply all the patches
  216. for fname in args:
  217. ok, stdout = ApplyPatch(verbose, fname)
  218. if not ok:
  219. print col.Color(col.RED, 'git am returned errors for %s: will '
  220. 'skip this patch' % fname)
  221. if verbose:
  222. print stdout
  223. error_count += 1
  224. cmd = ['git', 'am', '--skip']
  225. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  226. stdout, stderr = pipe.communicate()
  227. if pipe.returncode != 0:
  228. print col.Color(col.RED, 'Unable to skip patch! Aborting...')
  229. print stdout
  230. break
  231. # Return to our previous position
  232. cmd = ['git', 'checkout', old_head]
  233. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  234. stdout, stderr = pipe.communicate()
  235. if pipe.returncode:
  236. print col.Color(col.RED, 'Could not move back to head commit')
  237. print stdout, stderr
  238. return error_count == 0
  239. def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
  240. """Build a list of email addresses based on an input list.
  241. Takes a list of email addresses and aliases, and turns this into a list
  242. of only email address, by resolving any aliases that are present.
  243. If the tag is given, then each email address is prepended with this
  244. tag and a space. If the tag starts with a minus sign (indicating a
  245. command line parameter) then the email address is quoted.
  246. Args:
  247. in_list: List of aliases/email addresses
  248. tag: Text to put before each address
  249. alias: Alias dictionary
  250. raise_on_error: True to raise an error when an alias fails to match,
  251. False to just print a message.
  252. Returns:
  253. List of email addresses
  254. >>> alias = {}
  255. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  256. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  257. >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
  258. >>> alias['boys'] = ['fred', ' john']
  259. >>> alias['all'] = ['fred ', 'john', ' mary ']
  260. >>> BuildEmailList(['john', 'mary'], None, alias)
  261. ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
  262. >>> BuildEmailList(['john', 'mary'], '--to', alias)
  263. ['--to "j.bloggs@napier.co.nz"', \
  264. '--to "Mary Poppins <m.poppins@cloud.net>"']
  265. >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
  266. ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
  267. """
  268. quote = '"' if tag and tag[0] == '-' else ''
  269. raw = []
  270. for item in in_list:
  271. raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
  272. result = []
  273. for item in raw:
  274. if not item in result:
  275. result.append(item)
  276. if tag:
  277. return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
  278. return result
  279. def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
  280. self_only=False, alias=None, in_reply_to=None):
  281. """Email a patch series.
  282. Args:
  283. series: Series object containing destination info
  284. cover_fname: filename of cover letter
  285. args: list of filenames of patch files
  286. dry_run: Just return the command that would be run
  287. raise_on_error: True to raise an error when an alias fails to match,
  288. False to just print a message.
  289. cc_fname: Filename of Cc file for per-commit Cc
  290. self_only: True to just email to yourself as a test
  291. in_reply_to: If set we'll pass this to git as --in-reply-to.
  292. Should be a message ID that this is in reply to.
  293. Returns:
  294. Git command that was/would be run
  295. # For the duration of this doctest pretend that we ran patman with ./patman
  296. >>> _old_argv0 = sys.argv[0]
  297. >>> sys.argv[0] = './patman'
  298. >>> alias = {}
  299. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  300. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  301. >>> alias['mary'] = ['m.poppins@cloud.net']
  302. >>> alias['boys'] = ['fred', ' john']
  303. >>> alias['all'] = ['fred ', 'john', ' mary ']
  304. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  305. >>> series = series.Series()
  306. >>> series.to = ['fred']
  307. >>> series.cc = ['mary']
  308. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  309. False, 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" cover p1 p2'
  312. >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
  313. alias)
  314. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  315. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
  316. >>> series.cc = ['all']
  317. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  318. True, alias)
  319. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  320. --cc-cmd cc-fname" cover p1 p2'
  321. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  322. False, alias)
  323. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  324. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  325. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  326. # Restore argv[0] since we clobbered it.
  327. >>> sys.argv[0] = _old_argv0
  328. """
  329. to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
  330. if not to:
  331. git_config_to = command.Output('git', 'config', 'sendemail.to')
  332. if not git_config_to:
  333. print ("No recipient.\n"
  334. "Please add something like this to a commit\n"
  335. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
  336. "Or do something like this\n"
  337. "git config sendemail.to u-boot@lists.denx.de")
  338. return
  339. cc = BuildEmailList(series.get('cc'), '--cc', alias, raise_on_error)
  340. if self_only:
  341. to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
  342. cc = []
  343. cmd = ['git', 'send-email', '--annotate']
  344. if in_reply_to:
  345. cmd.append('--in-reply-to="%s"' % in_reply_to)
  346. cmd += to
  347. cmd += cc
  348. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  349. if cover_fname:
  350. cmd.append(cover_fname)
  351. cmd += args
  352. str = ' '.join(cmd)
  353. if not dry_run:
  354. os.system(str)
  355. return str
  356. def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
  357. """If an email address is an alias, look it up and return the full name
  358. TODO: Why not just use git's own alias feature?
  359. Args:
  360. lookup_name: Alias or email address to look up
  361. alias: Dictionary containing aliases (None to use settings default)
  362. raise_on_error: True to raise an error when an alias fails to match,
  363. False to just print a message.
  364. Returns:
  365. tuple:
  366. list containing a list of email addresses
  367. Raises:
  368. OSError if a recursive alias reference was found
  369. ValueError if an alias was not found
  370. >>> alias = {}
  371. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  372. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  373. >>> alias['mary'] = ['m.poppins@cloud.net']
  374. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  375. >>> alias['all'] = ['fred ', 'john', ' mary ']
  376. >>> alias['loop'] = ['other', 'john', ' mary ']
  377. >>> alias['other'] = ['loop', 'john', ' mary ']
  378. >>> LookupEmail('mary', alias)
  379. ['m.poppins@cloud.net']
  380. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  381. ['arthur.wellesley@howe.ro.uk']
  382. >>> LookupEmail('boys', alias)
  383. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  384. >>> LookupEmail('all', alias)
  385. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  386. >>> LookupEmail('odd', alias)
  387. Traceback (most recent call last):
  388. ...
  389. ValueError: Alias 'odd' not found
  390. >>> LookupEmail('loop', alias)
  391. Traceback (most recent call last):
  392. ...
  393. OSError: Recursive email alias at 'other'
  394. >>> LookupEmail('odd', alias, raise_on_error=False)
  395. \033[1;31mAlias 'odd' not found\033[0m
  396. []
  397. >>> # In this case the loop part will effectively be ignored.
  398. >>> LookupEmail('loop', alias, raise_on_error=False)
  399. \033[1;31mRecursive email alias at 'other'\033[0m
  400. \033[1;31mRecursive email alias at 'john'\033[0m
  401. \033[1;31mRecursive email alias at 'mary'\033[0m
  402. ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  403. """
  404. if not alias:
  405. alias = settings.alias
  406. lookup_name = lookup_name.strip()
  407. if '@' in lookup_name: # Perhaps a real email address
  408. return [lookup_name]
  409. lookup_name = lookup_name.lower()
  410. col = terminal.Color()
  411. out_list = []
  412. if level > 10:
  413. msg = "Recursive email alias at '%s'" % lookup_name
  414. if raise_on_error:
  415. raise OSError, msg
  416. else:
  417. print col.Color(col.RED, msg)
  418. return out_list
  419. if lookup_name:
  420. if not lookup_name in alias:
  421. msg = "Alias '%s' not found" % lookup_name
  422. if raise_on_error:
  423. raise ValueError, msg
  424. else:
  425. print col.Color(col.RED, msg)
  426. return out_list
  427. for item in alias[lookup_name]:
  428. todo = LookupEmail(item, alias, raise_on_error, level + 1)
  429. for new_item in todo:
  430. if not new_item in out_list:
  431. out_list.append(new_item)
  432. #print "No match for alias '%s'" % lookup_name
  433. return out_list
  434. def GetTopLevel():
  435. """Return name of top-level directory for this git repo.
  436. Returns:
  437. Full path to git top-level directory
  438. This test makes sure that we are running tests in the right subdir
  439. >>> os.path.realpath(os.path.dirname(__file__)) == \
  440. os.path.join(GetTopLevel(), 'tools', 'patman')
  441. True
  442. """
  443. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  444. def GetAliasFile():
  445. """Gets the name of the git alias file.
  446. Returns:
  447. Filename of git alias file, or None if none
  448. """
  449. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
  450. raise_on_error=False)
  451. if fname:
  452. fname = os.path.join(GetTopLevel(), fname.strip())
  453. return fname
  454. def GetDefaultUserName():
  455. """Gets the user.name from .gitconfig file.
  456. Returns:
  457. User name found in .gitconfig file, or None if none
  458. """
  459. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  460. return uname
  461. def GetDefaultUserEmail():
  462. """Gets the user.email from the global .gitconfig file.
  463. Returns:
  464. User's email found in .gitconfig file, or None if none
  465. """
  466. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  467. return uemail
  468. def Setup():
  469. """Set up git utils, by reading the alias files."""
  470. # Check for a git alias file also
  471. alias_fname = GetAliasFile()
  472. if alias_fname:
  473. settings.ReadGitAliases(alias_fname)
  474. def GetHead():
  475. """Get the hash of the current HEAD
  476. Returns:
  477. Hash of HEAD
  478. """
  479. return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
  480. if __name__ == "__main__":
  481. import doctest
  482. doctest.testmod()