PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/u-boot-2012.07-rc1/tools/patman/gitutil.py

#
Python | 390 lines | 331 code | 8 blank | 51 comment | 12 complexity | e8857306af2bf0d9836e16f8e151ac52 MD5 | raw file
Possible License(s): AGPL-1.0
  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', '--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. >>> alias = {}
  192. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  193. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  194. >>> alias['mary'] = ['m.poppins@cloud.net']
  195. >>> alias['boys'] = ['fred', ' john']
  196. >>> alias['all'] = ['fred ', 'john', ' mary ']
  197. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  198. >>> series = series.Series()
  199. >>> series.to = ['fred']
  200. >>> series.cc = ['mary']
  201. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', False, \
  202. alias)
  203. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  204. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  205. >>> EmailPatches(series, None, ['p1'], True, 'cc-fname', False, 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" p1'
  208. >>> series.cc = ['all']
  209. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', True, \
  210. alias)
  211. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  212. --cc-cmd cc-fname" cover p1 p2'
  213. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, 'cc-fname', False, \
  214. alias)
  215. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  216. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  217. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  218. """
  219. to = BuildEmailList(series.get('to'), '--to', alias)
  220. if not to:
  221. print ("No recipient, please add something like this to a commit\n"
  222. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>")
  223. return
  224. cc = BuildEmailList(series.get('cc'), '--cc', alias)
  225. if self_only:
  226. to = BuildEmailList([os.getenv('USER')], '--to', alias)
  227. cc = []
  228. cmd = ['git', 'send-email', '--annotate']
  229. cmd += to
  230. cmd += cc
  231. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  232. if cover_fname:
  233. cmd.append(cover_fname)
  234. cmd += args
  235. str = ' '.join(cmd)
  236. if not dry_run:
  237. os.system(str)
  238. return str
  239. def LookupEmail(lookup_name, alias=None, level=0):
  240. """If an email address is an alias, look it up and return the full name
  241. TODO: Why not just use git's own alias feature?
  242. Args:
  243. lookup_name: Alias or email address to look up
  244. Returns:
  245. tuple:
  246. list containing a list of email addresses
  247. Raises:
  248. OSError if a recursive alias reference was found
  249. ValueError if an alias was not found
  250. >>> alias = {}
  251. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  252. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  253. >>> alias['mary'] = ['m.poppins@cloud.net']
  254. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  255. >>> alias['all'] = ['fred ', 'john', ' mary ']
  256. >>> alias['loop'] = ['other', 'john', ' mary ']
  257. >>> alias['other'] = ['loop', 'john', ' mary ']
  258. >>> LookupEmail('mary', alias)
  259. ['m.poppins@cloud.net']
  260. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  261. ['arthur.wellesley@howe.ro.uk']
  262. >>> LookupEmail('boys', alias)
  263. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  264. >>> LookupEmail('all', alias)
  265. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  266. >>> LookupEmail('odd', alias)
  267. Traceback (most recent call last):
  268. ...
  269. ValueError: Alias 'odd' not found
  270. >>> LookupEmail('loop', alias)
  271. Traceback (most recent call last):
  272. ...
  273. OSError: Recursive email alias at 'other'
  274. """
  275. if not alias:
  276. alias = settings.alias
  277. lookup_name = lookup_name.strip()
  278. if '@' in lookup_name: # Perhaps a real email address
  279. return [lookup_name]
  280. lookup_name = lookup_name.lower()
  281. if level > 10:
  282. raise OSError, "Recursive email alias at '%s'" % lookup_name
  283. out_list = []
  284. if lookup_name:
  285. if not lookup_name in alias:
  286. raise ValueError, "Alias '%s' not found" % lookup_name
  287. for item in alias[lookup_name]:
  288. todo = LookupEmail(item, alias, level + 1)
  289. for new_item in todo:
  290. if not new_item in out_list:
  291. out_list.append(new_item)
  292. #print "No match for alias '%s'" % lookup_name
  293. return out_list
  294. def GetTopLevel():
  295. """Return name of top-level directory for this git repo.
  296. Returns:
  297. Full path to git top-level directory
  298. This test makes sure that we are running tests in the right subdir
  299. >>> os.path.realpath(os.getcwd()) == \
  300. os.path.join(GetTopLevel(), 'tools', 'scripts', 'patman')
  301. True
  302. """
  303. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  304. def GetAliasFile():
  305. """Gets the name of the git alias file.
  306. Returns:
  307. Filename of git alias file, or None if none
  308. """
  309. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile')
  310. if fname:
  311. fname = os.path.join(GetTopLevel(), fname.strip())
  312. return fname
  313. def GetDefaultUserName():
  314. """Gets the user.name from .gitconfig file.
  315. Returns:
  316. User name found in .gitconfig file, or None if none
  317. """
  318. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  319. return uname
  320. def GetDefaultUserEmail():
  321. """Gets the user.email from the global .gitconfig file.
  322. Returns:
  323. User's email found in .gitconfig file, or None if none
  324. """
  325. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  326. return uemail
  327. def Setup():
  328. """Set up git utils, by reading the alias files."""
  329. settings.Setup('')
  330. # Check for a git alias file also
  331. alias_fname = GetAliasFile()
  332. if alias_fname:
  333. settings.ReadGitAliases(alias_fname)
  334. if __name__ == "__main__":
  335. import doctest
  336. doctest.testmod()