gitutil.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 settings
  26. import subprocess
  27. import sys
  28. import terminal
  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)
  39. patch_count = int(stdout)
  40. return patch_count
  41. def CreatePatches(start, count, series):
  42. """Create a series of patches from the top of the current branch.
  43. The patch files are written to the current directory using
  44. git format-patch.
  45. Args:
  46. start: Commit to start from: 0=HEAD, 1=next one, etc.
  47. count: number of commits to include
  48. Return:
  49. Filename of cover letter
  50. List of filenames of patch files
  51. """
  52. if series.get('version'):
  53. version = '%s ' % series['version']
  54. cmd = ['git', 'format-patch', '-M', '--signoff']
  55. if series.get('cover'):
  56. cmd.append('--cover-letter')
  57. prefix = series.GetPatchPrefix()
  58. if prefix:
  59. cmd += ['--subject-prefix=%s' % prefix]
  60. cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
  61. stdout = command.RunList(cmd)
  62. files = stdout.splitlines()
  63. # We have an extra file if there is a cover letter
  64. if series.get('cover'):
  65. return files[0], files[1:]
  66. else:
  67. return None, files
  68. def ApplyPatch(verbose, fname):
  69. """Apply a patch with git am to test it
  70. TODO: Convert these to use command, with stderr option
  71. Args:
  72. fname: filename of patch file to apply
  73. """
  74. cmd = ['git', 'am', fname]
  75. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  76. stderr=subprocess.PIPE)
  77. stdout, stderr = pipe.communicate()
  78. re_error = re.compile('^error: patch failed: (.+):(\d+)')
  79. for line in stderr.splitlines():
  80. if verbose:
  81. print line
  82. match = re_error.match(line)
  83. if match:
  84. print GetWarningMsg('warning', match.group(1), int(match.group(2)),
  85. 'Patch failed')
  86. return pipe.returncode == 0, stdout
  87. def ApplyPatches(verbose, args, start_point):
  88. """Apply the patches with git am to make sure all is well
  89. Args:
  90. verbose: Print out 'git am' output verbatim
  91. args: List of patch files to apply
  92. start_point: Number of commits back from HEAD to start applying.
  93. Normally this is len(args), but it can be larger if a start
  94. offset was given.
  95. """
  96. error_count = 0
  97. col = terminal.Color()
  98. # Figure out our current position
  99. cmd = ['git', 'name-rev', 'HEAD', '--name-only']
  100. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  101. stdout, stderr = pipe.communicate()
  102. if pipe.returncode:
  103. str = 'Could not find current commit name'
  104. print col.Color(col.RED, str)
  105. print stdout
  106. return False
  107. old_head = stdout.splitlines()[0]
  108. # Checkout the required start point
  109. cmd = ['git', 'checkout', 'HEAD~%d' % start_point]
  110. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,
  111. stderr=subprocess.PIPE)
  112. stdout, stderr = pipe.communicate()
  113. if pipe.returncode:
  114. str = 'Could not move to commit before patch series'
  115. print col.Color(col.RED, str)
  116. print stdout, stderr
  117. return False
  118. # Apply all the patches
  119. for fname in args:
  120. ok, stdout = ApplyPatch(verbose, fname)
  121. if not ok:
  122. print col.Color(col.RED, 'git am returned errors for %s: will '
  123. 'skip this patch' % fname)
  124. if verbose:
  125. print stdout
  126. error_count += 1
  127. cmd = ['git', 'am', '--skip']
  128. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  129. stdout, stderr = pipe.communicate()
  130. if pipe.returncode != 0:
  131. print col.Color(col.RED, 'Unable to skip patch! Aborting...')
  132. print stdout
  133. break
  134. # Return to our previous position
  135. cmd = ['git', 'checkout', old_head]
  136. pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  137. stdout, stderr = pipe.communicate()
  138. if pipe.returncode:
  139. print col.Color(col.RED, 'Could not move back to head commit')
  140. print stdout, stderr
  141. return error_count == 0
  142. def BuildEmailList(in_list, tag=None, alias=None):
  143. """Build a list of email addresses based on an input list.
  144. Takes a list of email addresses and aliases, and turns this into a list
  145. of only email address, by resolving any aliases that are present.
  146. If the tag is given, then each email address is prepended with this
  147. tag and a space. If the tag starts with a minus sign (indicating a
  148. command line parameter) then the email address is quoted.
  149. Args:
  150. in_list: List of aliases/email addresses
  151. tag: Text to put before each address
  152. Returns:
  153. List of email addresses
  154. >>> alias = {}
  155. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  156. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  157. >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
  158. >>> alias['boys'] = ['fred', ' john']
  159. >>> alias['all'] = ['fred ', 'john', ' mary ']
  160. >>> BuildEmailList(['john', 'mary'], None, alias)
  161. ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
  162. >>> BuildEmailList(['john', 'mary'], '--to', alias)
  163. ['--to "j.bloggs@napier.co.nz"', \
  164. '--to "Mary Poppins <m.poppins@cloud.net>"']
  165. >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
  166. ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
  167. """
  168. quote = '"' if tag and tag[0] == '-' else ''
  169. raw = []
  170. for item in in_list:
  171. raw += LookupEmail(item, alias)
  172. result = []
  173. for item in raw:
  174. if not item in result:
  175. result.append(item)
  176. if tag:
  177. return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
  178. return result
  179. def EmailPatches(series, cover_fname, args, dry_run, cc_fname,
  180. self_only=False, alias=None):
  181. """Email a patch series.
  182. Args:
  183. series: Series object containing destination info
  184. cover_fname: filename of cover letter
  185. args: list of filenames of patch files
  186. dry_run: Just return the command that would be run
  187. cc_fname: Filename of Cc file for per-commit Cc
  188. self_only: True to just email to yourself as a test
  189. Returns:
  190. Git command that was/would be run
  191. # For the duration of this doctest pretend that we ran patman with ./patman
  192. >>> _old_argv0 = sys.argv[0]
  193. >>> sys.argv[0] = './patman'
  194. >>> alias = {}
  195. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  196. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  197. >>> alias['mary'] = ['m.poppins@cloud.net']
  198. >>> alias['boys'] = ['fred', ' john']
  199. >>> alias['all'] = ['fred ', 'john', ' mary ']
  200. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  201. >>> series = series.Series()
  202. >>> series.to = ['fred']
  203. >>> series.cc = ['mary']
  204. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', False, \
  205. alias)
  206. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  207. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  208. >>> EmailPatches(series, None, ['p1'], True, 'cc-fname', False, alias)
  209. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  210. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
  211. >>> series.cc = ['all']
  212. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', True, \
  213. alias)
  214. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  215. --cc-cmd cc-fname" cover p1 p2'
  216. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', False, \
  217. alias)
  218. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  219. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  220. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  221. # Restore argv[0] since we clobbered it.
  222. >>> sys.argv[0] = _old_argv0
  223. """
  224. to = BuildEmailList(series.get('to'), '--to', alias)
  225. if not to:
  226. print ("No recipient, please add something like this to a commit\n"
  227. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>")
  228. return
  229. cc = BuildEmailList(series.get('cc'), '--cc', alias)
  230. if self_only:
  231. to = BuildEmailList([os.getenv('USER')], '--to', alias)
  232. cc = []
  233. cmd = ['git', 'send-email', '--annotate']
  234. cmd += to
  235. cmd += cc
  236. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  237. if cover_fname:
  238. cmd.append(cover_fname)
  239. cmd += args
  240. str = ' '.join(cmd)
  241. if not dry_run:
  242. os.system(str)
  243. return str
  244. def LookupEmail(lookup_name, alias=None, level=0):
  245. """If an email address is an alias, look it up and return the full name
  246. TODO: Why not just use git's own alias feature?
  247. Args:
  248. lookup_name: Alias or email address to look up
  249. Returns:
  250. tuple:
  251. list containing a list of email addresses
  252. Raises:
  253. OSError if a recursive alias reference was found
  254. ValueError if an alias was not found
  255. >>> alias = {}
  256. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  257. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  258. >>> alias['mary'] = ['m.poppins@cloud.net']
  259. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  260. >>> alias['all'] = ['fred ', 'john', ' mary ']
  261. >>> alias['loop'] = ['other', 'john', ' mary ']
  262. >>> alias['other'] = ['loop', 'john', ' mary ']
  263. >>> LookupEmail('mary', alias)
  264. ['m.poppins@cloud.net']
  265. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  266. ['arthur.wellesley@howe.ro.uk']
  267. >>> LookupEmail('boys', alias)
  268. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  269. >>> LookupEmail('all', alias)
  270. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  271. >>> LookupEmail('odd', alias)
  272. Traceback (most recent call last):
  273. ...
  274. ValueError: Alias 'odd' not found
  275. >>> LookupEmail('loop', alias)
  276. Traceback (most recent call last):
  277. ...
  278. OSError: Recursive email alias at 'other'
  279. """
  280. if not alias:
  281. alias = settings.alias
  282. lookup_name = lookup_name.strip()
  283. if '@' in lookup_name: # Perhaps a real email address
  284. return [lookup_name]
  285. lookup_name = lookup_name.lower()
  286. if level > 10:
  287. raise OSError, "Recursive email alias at '%s'" % lookup_name
  288. out_list = []
  289. if lookup_name:
  290. if not lookup_name in alias:
  291. raise ValueError, "Alias '%s' not found" % lookup_name
  292. for item in alias[lookup_name]:
  293. todo = LookupEmail(item, alias, level + 1)
  294. for new_item in todo:
  295. if not new_item in out_list:
  296. out_list.append(new_item)
  297. #print "No match for alias '%s'" % lookup_name
  298. return out_list
  299. def GetTopLevel():
  300. """Return name of top-level directory for this git repo.
  301. Returns:
  302. Full path to git top-level directory
  303. This test makes sure that we are running tests in the right subdir
  304. >>> os.path.realpath(os.path.dirname(__file__)) == \
  305. os.path.join(GetTopLevel(), 'tools', 'patman')
  306. True
  307. """
  308. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  309. def GetAliasFile():
  310. """Gets the name of the git alias file.
  311. Returns:
  312. Filename of git alias file, or None if none
  313. """
  314. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile')
  315. if fname:
  316. fname = os.path.join(GetTopLevel(), fname.strip())
  317. return fname
  318. def GetDefaultUserName():
  319. """Gets the user.name from .gitconfig file.
  320. Returns:
  321. User name found in .gitconfig file, or None if none
  322. """
  323. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  324. return uname
  325. def GetDefaultUserEmail():
  326. """Gets the user.email from the global .gitconfig file.
  327. Returns:
  328. User's email found in .gitconfig file, or None if none
  329. """
  330. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  331. return uemail
  332. def Setup():
  333. """Set up git utils, by reading the alias files."""
  334. settings.Setup('')
  335. # Check for a git alias file also
  336. alias_fname = GetAliasFile()
  337. if alias_fname:
  338. settings.ReadGitAliases(alias_fname)
  339. if __name__ == "__main__":
  340. import doctest
  341. doctest.testmod()