gitutil.py 19 KB

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