gitutil.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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', '@{upstream}..'],
  37. ['wc', '-l']]
  38. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  39. patch_count = int(stdout)
  40. return patch_count
  41. def GetUpstream(git_dir, branch):
  42. """Returns the name of the upstream for a branch
  43. Args:
  44. git_dir: Git directory containing repo
  45. branch: Name of branch
  46. Returns:
  47. Name of upstream branch (e.g. 'upstream/master') or None if none
  48. """
  49. remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  50. 'branch.%s.remote' % branch)
  51. merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  52. 'branch.%s.merge' % branch)
  53. if remote == '.':
  54. return merge
  55. elif remote and merge:
  56. leaf = merge.split('/')[-1]
  57. return '%s/%s' % (remote, leaf)
  58. else:
  59. raise ValueError, ("Cannot determine upstream branch for branch "
  60. "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
  61. def GetRangeInBranch(git_dir, branch, include_upstream=False):
  62. """Returns an expression for the commits in the given branch.
  63. Args:
  64. git_dir: Directory containing git repo
  65. branch: Name of branch
  66. Return:
  67. Expression in the form 'upstream..branch' which can be used to
  68. access the commits.
  69. """
  70. upstream = GetUpstream(git_dir, branch)
  71. return '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
  72. def CountCommitsInBranch(git_dir, branch, include_upstream=False):
  73. """Returns the number of commits in the given branch.
  74. Args:
  75. git_dir: Directory containing git repo
  76. branch: Name of branch
  77. Return:
  78. Number of patches that exist on top of the branch
  79. """
  80. range_expr = GetRangeInBranch(git_dir, branch, include_upstream)
  81. pipe = [['git', '--git-dir', git_dir, 'log', '--oneline', range_expr],
  82. ['wc', '-l']]
  83. result = command.RunPipe(pipe, capture=True, oneline=True)
  84. patch_count = int(result.stdout)
  85. return patch_count
  86. def CountCommits(commit_range):
  87. """Returns the number of commits in the given range.
  88. Args:
  89. commit_range: Range of commits to count (e.g. 'HEAD..base')
  90. Return:
  91. Number of patches that exist on top of the branch
  92. """
  93. pipe = [['git', 'log', '--oneline', commit_range],
  94. ['wc', '-l']]
  95. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  96. patch_count = int(stdout)
  97. return patch_count
  98. def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
  99. """Checkout the selected commit for this build
  100. Args:
  101. commit_hash: Commit hash to check out
  102. """
  103. pipe = ['git']
  104. if git_dir:
  105. pipe.extend(['--git-dir', git_dir])
  106. if work_tree:
  107. pipe.extend(['--work-tree', work_tree])
  108. pipe.append('checkout')
  109. if force:
  110. pipe.append('-f')
  111. pipe.append(commit_hash)
  112. result = command.RunPipe([pipe], capture=True, raise_on_error=False)
  113. if result.return_code != 0:
  114. raise OSError, 'git checkout (%s): %s' % (pipe, result.stderr)
  115. def Clone(git_dir, output_dir):
  116. """Checkout the selected commit for this build
  117. Args:
  118. commit_hash: Commit hash to check out
  119. """
  120. pipe = ['git', 'clone', git_dir, '.']
  121. result = command.RunPipe([pipe], capture=True, cwd=output_dir)
  122. if result.return_code != 0:
  123. raise OSError, 'git clone: %s' % result.stderr
  124. def Fetch(git_dir=None, work_tree=None):
  125. """Fetch from the origin repo
  126. Args:
  127. commit_hash: Commit hash to check out
  128. """
  129. pipe = ['git']
  130. if git_dir:
  131. pipe.extend(['--git-dir', git_dir])
  132. if work_tree:
  133. pipe.extend(['--work-tree', work_tree])
  134. pipe.append('fetch')
  135. result = command.RunPipe([pipe], capture=True)
  136. if result.return_code != 0:
  137. raise OSError, 'git fetch: %s' % result.stderr
  138. def CreatePatches(start, count, series):
  139. """Create a series of patches from the top of the current branch.
  140. The patch files are written to the current directory using
  141. git format-patch.
  142. Args:
  143. start: Commit to start from: 0=HEAD, 1=next one, etc.
  144. count: number of commits to include
  145. Return:
  146. Filename of cover letter
  147. List of filenames of patch files
  148. """
  149. if series.get('version'):
  150. version = '%s ' % series['version']
  151. cmd = ['git', 'format-patch', '-M', '--signoff']
  152. if series.get('cover'):
  153. cmd.append('--cover-letter')
  154. prefix = series.GetPatchPrefix()
  155. if prefix:
  156. cmd += ['--subject-prefix=%s' % prefix]
  157. cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
  158. stdout = command.RunList(cmd)
  159. files = stdout.splitlines()
  160. # We have an extra file if there is a cover letter
  161. if series.get('cover'):
  162. return files[0], files[1:]
  163. else:
  164. return None, files
  165. def ApplyPatch(verbose, fname):
  166. """Apply a patch with git am to test it
  167. TODO: Convert these to use command, with stderr option
  168. Args:
  169. fname: filename of patch file to apply
  170. """
  171. cmd = ['git', 'am', fname]
  172. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  173. stderr=subprocess.PIPE)
  174. stdout, stderr = pipe.communicate()
  175. re_error = re.compile('^error: patch failed: (.+):(\d+)')
  176. for line in stderr.splitlines():
  177. if verbose:
  178. print line
  179. match = re_error.match(line)
  180. if match:
  181. print GetWarningMsg('warning', match.group(1), int(match.group(2)),
  182. 'Patch failed')
  183. return pipe.returncode == 0, stdout
  184. def ApplyPatches(verbose, args, start_point):
  185. """Apply the patches with git am to make sure all is well
  186. Args:
  187. verbose: Print out 'git am' output verbatim
  188. args: List of patch files to apply
  189. start_point: Number of commits back from HEAD to start applying.
  190. Normally this is len(args), but it can be larger if a start
  191. offset was given.
  192. """
  193. error_count = 0
  194. col = terminal.Color()
  195. # Figure out our current position
  196. cmd = ['git', 'name-rev', 'HEAD', '--name-only']
  197. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  198. stdout, stderr = pipe.communicate()
  199. if pipe.returncode:
  200. str = 'Could not find current commit name'
  201. print col.Color(col.RED, str)
  202. print stdout
  203. return False
  204. old_head = stdout.splitlines()[0]
  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. print ("No recipient, please add something like this to a commit\n"
  332. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>")
  333. return
  334. cc = BuildEmailList(series.get('cc'), '--cc', alias, raise_on_error)
  335. if self_only:
  336. to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
  337. cc = []
  338. cmd = ['git', 'send-email', '--annotate']
  339. if in_reply_to:
  340. cmd.append('--in-reply-to="%s"' % in_reply_to)
  341. cmd += to
  342. cmd += cc
  343. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  344. if cover_fname:
  345. cmd.append(cover_fname)
  346. cmd += args
  347. str = ' '.join(cmd)
  348. if not dry_run:
  349. os.system(str)
  350. return str
  351. def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
  352. """If an email address is an alias, look it up and return the full name
  353. TODO: Why not just use git's own alias feature?
  354. Args:
  355. lookup_name: Alias or email address to look up
  356. alias: Dictionary containing aliases (None to use settings default)
  357. raise_on_error: True to raise an error when an alias fails to match,
  358. False to just print a message.
  359. Returns:
  360. tuple:
  361. list containing a list of email addresses
  362. Raises:
  363. OSError if a recursive alias reference was found
  364. ValueError if an alias was not found
  365. >>> alias = {}
  366. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  367. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  368. >>> alias['mary'] = ['m.poppins@cloud.net']
  369. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  370. >>> alias['all'] = ['fred ', 'john', ' mary ']
  371. >>> alias['loop'] = ['other', 'john', ' mary ']
  372. >>> alias['other'] = ['loop', 'john', ' mary ']
  373. >>> LookupEmail('mary', alias)
  374. ['m.poppins@cloud.net']
  375. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  376. ['arthur.wellesley@howe.ro.uk']
  377. >>> LookupEmail('boys', alias)
  378. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  379. >>> LookupEmail('all', alias)
  380. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  381. >>> LookupEmail('odd', alias)
  382. Traceback (most recent call last):
  383. ...
  384. ValueError: Alias 'odd' not found
  385. >>> LookupEmail('loop', alias)
  386. Traceback (most recent call last):
  387. ...
  388. OSError: Recursive email alias at 'other'
  389. >>> LookupEmail('odd', alias, raise_on_error=False)
  390. \033[1;31mAlias 'odd' not found\033[0m
  391. []
  392. >>> # In this case the loop part will effectively be ignored.
  393. >>> LookupEmail('loop', alias, raise_on_error=False)
  394. \033[1;31mRecursive email alias at 'other'\033[0m
  395. \033[1;31mRecursive email alias at 'john'\033[0m
  396. \033[1;31mRecursive email alias at 'mary'\033[0m
  397. ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  398. """
  399. if not alias:
  400. alias = settings.alias
  401. lookup_name = lookup_name.strip()
  402. if '@' in lookup_name: # Perhaps a real email address
  403. return [lookup_name]
  404. lookup_name = lookup_name.lower()
  405. col = terminal.Color()
  406. out_list = []
  407. if level > 10:
  408. msg = "Recursive email alias at '%s'" % lookup_name
  409. if raise_on_error:
  410. raise OSError, msg
  411. else:
  412. print col.Color(col.RED, msg)
  413. return out_list
  414. if lookup_name:
  415. if not lookup_name in alias:
  416. msg = "Alias '%s' not found" % lookup_name
  417. if raise_on_error:
  418. raise ValueError, msg
  419. else:
  420. print col.Color(col.RED, msg)
  421. return out_list
  422. for item in alias[lookup_name]:
  423. todo = LookupEmail(item, alias, raise_on_error, level + 1)
  424. for new_item in todo:
  425. if not new_item in out_list:
  426. out_list.append(new_item)
  427. #print "No match for alias '%s'" % lookup_name
  428. return out_list
  429. def GetTopLevel():
  430. """Return name of top-level directory for this git repo.
  431. Returns:
  432. Full path to git top-level directory
  433. This test makes sure that we are running tests in the right subdir
  434. >>> os.path.realpath(os.path.dirname(__file__)) == \
  435. os.path.join(GetTopLevel(), 'tools', 'patman')
  436. True
  437. """
  438. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  439. def GetAliasFile():
  440. """Gets the name of the git alias file.
  441. Returns:
  442. Filename of git alias file, or None if none
  443. """
  444. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
  445. raise_on_error=False)
  446. if fname:
  447. fname = os.path.join(GetTopLevel(), fname.strip())
  448. return fname
  449. def GetDefaultUserName():
  450. """Gets the user.name from .gitconfig file.
  451. Returns:
  452. User name found in .gitconfig file, or None if none
  453. """
  454. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  455. return uname
  456. def GetDefaultUserEmail():
  457. """Gets the user.email from the global .gitconfig file.
  458. Returns:
  459. User's email found in .gitconfig file, or None if none
  460. """
  461. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  462. return uemail
  463. def Setup():
  464. """Set up git utils, by reading the alias files."""
  465. # Check for a git alias file also
  466. alias_fname = GetAliasFile()
  467. if alias_fname:
  468. settings.ReadGitAliases(alias_fname)
  469. def GetHead():
  470. """Get the hash of the current HEAD
  471. Returns:
  472. Hash of HEAD
  473. """
  474. return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
  475. if __name__ == "__main__":
  476. import doctest
  477. doctest.testmod()