gitutil.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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):
  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. Returns:
  250. List of email addresses
  251. >>> alias = {}
  252. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  253. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  254. >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
  255. >>> alias['boys'] = ['fred', ' john']
  256. >>> alias['all'] = ['fred ', 'john', ' mary ']
  257. >>> BuildEmailList(['john', 'mary'], None, alias)
  258. ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
  259. >>> BuildEmailList(['john', 'mary'], '--to', alias)
  260. ['--to "j.bloggs@napier.co.nz"', \
  261. '--to "Mary Poppins <m.poppins@cloud.net>"']
  262. >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
  263. ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
  264. """
  265. quote = '"' if tag and tag[0] == '-' else ''
  266. raw = []
  267. for item in in_list:
  268. raw += LookupEmail(item, alias)
  269. result = []
  270. for item in raw:
  271. if not item in result:
  272. result.append(item)
  273. if tag:
  274. return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
  275. return result
  276. def EmailPatches(series, cover_fname, args, dry_run, cc_fname,
  277. self_only=False, alias=None):
  278. """Email a patch series.
  279. Args:
  280. series: Series object containing destination info
  281. cover_fname: filename of cover letter
  282. args: list of filenames of patch files
  283. dry_run: Just return the command that would be run
  284. cc_fname: Filename of Cc file for per-commit Cc
  285. self_only: True to just email to yourself as a test
  286. Returns:
  287. Git command that was/would be run
  288. # For the duration of this doctest pretend that we ran patman with ./patman
  289. >>> _old_argv0 = sys.argv[0]
  290. >>> sys.argv[0] = './patman'
  291. >>> alias = {}
  292. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  293. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  294. >>> alias['mary'] = ['m.poppins@cloud.net']
  295. >>> alias['boys'] = ['fred', ' john']
  296. >>> alias['all'] = ['fred ', 'john', ' mary ']
  297. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  298. >>> series = series.Series()
  299. >>> series.to = ['fred']
  300. >>> series.cc = ['mary']
  301. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', False, \
  302. alias)
  303. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  304. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  305. >>> EmailPatches(series, None, ['p1'], True, 'cc-fname', 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" p1'
  308. >>> series.cc = ['all']
  309. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', True, \
  310. alias)
  311. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  312. --cc-cmd cc-fname" cover p1 p2'
  313. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', False, \
  314. alias)
  315. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  316. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  317. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  318. # Restore argv[0] since we clobbered it.
  319. >>> sys.argv[0] = _old_argv0
  320. """
  321. to = BuildEmailList(series.get('to'), '--to', alias)
  322. if not to:
  323. print ("No recipient, please add something like this to a commit\n"
  324. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>")
  325. return
  326. cc = BuildEmailList(series.get('cc'), '--cc', alias)
  327. if self_only:
  328. to = BuildEmailList([os.getenv('USER')], '--to', alias)
  329. cc = []
  330. cmd = ['git', 'send-email', '--annotate']
  331. cmd += to
  332. cmd += cc
  333. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  334. if cover_fname:
  335. cmd.append(cover_fname)
  336. cmd += args
  337. str = ' '.join(cmd)
  338. if not dry_run:
  339. os.system(str)
  340. return str
  341. def LookupEmail(lookup_name, alias=None, level=0):
  342. """If an email address is an alias, look it up and return the full name
  343. TODO: Why not just use git's own alias feature?
  344. Args:
  345. lookup_name: Alias or email address to look up
  346. Returns:
  347. tuple:
  348. list containing a list of email addresses
  349. Raises:
  350. OSError if a recursive alias reference was found
  351. ValueError if an alias was not found
  352. >>> alias = {}
  353. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  354. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  355. >>> alias['mary'] = ['m.poppins@cloud.net']
  356. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  357. >>> alias['all'] = ['fred ', 'john', ' mary ']
  358. >>> alias['loop'] = ['other', 'john', ' mary ']
  359. >>> alias['other'] = ['loop', 'john', ' mary ']
  360. >>> LookupEmail('mary', alias)
  361. ['m.poppins@cloud.net']
  362. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  363. ['arthur.wellesley@howe.ro.uk']
  364. >>> LookupEmail('boys', alias)
  365. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  366. >>> LookupEmail('all', alias)
  367. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  368. >>> LookupEmail('odd', alias)
  369. Traceback (most recent call last):
  370. ...
  371. ValueError: Alias 'odd' not found
  372. >>> LookupEmail('loop', alias)
  373. Traceback (most recent call last):
  374. ...
  375. OSError: Recursive email alias at 'other'
  376. """
  377. if not alias:
  378. alias = settings.alias
  379. lookup_name = lookup_name.strip()
  380. if '@' in lookup_name: # Perhaps a real email address
  381. return [lookup_name]
  382. lookup_name = lookup_name.lower()
  383. if level > 10:
  384. raise OSError, "Recursive email alias at '%s'" % lookup_name
  385. out_list = []
  386. if lookup_name:
  387. if not lookup_name in alias:
  388. raise ValueError, "Alias '%s' not found" % lookup_name
  389. for item in alias[lookup_name]:
  390. todo = LookupEmail(item, alias, level + 1)
  391. for new_item in todo:
  392. if not new_item in out_list:
  393. out_list.append(new_item)
  394. #print "No match for alias '%s'" % lookup_name
  395. return out_list
  396. def GetTopLevel():
  397. """Return name of top-level directory for this git repo.
  398. Returns:
  399. Full path to git top-level directory
  400. This test makes sure that we are running tests in the right subdir
  401. >>> os.path.realpath(os.path.dirname(__file__)) == \
  402. os.path.join(GetTopLevel(), 'tools', 'patman')
  403. True
  404. """
  405. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  406. def GetAliasFile():
  407. """Gets the name of the git alias file.
  408. Returns:
  409. Filename of git alias file, or None if none
  410. """
  411. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
  412. raise_on_error=False)
  413. if fname:
  414. fname = os.path.join(GetTopLevel(), fname.strip())
  415. return fname
  416. def GetDefaultUserName():
  417. """Gets the user.name from .gitconfig file.
  418. Returns:
  419. User name found in .gitconfig file, or None if none
  420. """
  421. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  422. return uname
  423. def GetDefaultUserEmail():
  424. """Gets the user.email from the global .gitconfig file.
  425. Returns:
  426. User's email found in .gitconfig file, or None if none
  427. """
  428. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  429. return uemail
  430. def Setup():
  431. """Set up git utils, by reading the alias files."""
  432. # Check for a git alias file also
  433. alias_fname = GetAliasFile()
  434. if alias_fname:
  435. settings.ReadGitAliases(alias_fname)
  436. def GetHead():
  437. """Get the hash of the current HEAD
  438. Returns:
  439. Hash of HEAD
  440. """
  441. return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
  442. if __name__ == "__main__":
  443. import doctest
  444. doctest.testmod()