gitutil.py 19 KB

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