gitutil.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # SPDX-License-Identifier: GPL-2.0+
  4. #
  5. import command
  6. import re
  7. import os
  8. import series
  9. import subprocess
  10. import sys
  11. import terminal
  12. import checkpatch
  13. import settings
  14. # True to use --no-decorate - we check this in Setup()
  15. use_no_decorate = True
  16. def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
  17. count=None):
  18. """Create a command to perform a 'git log'
  19. Args:
  20. commit_range: Range expression to use for log, None for none
  21. git_dir: Path to git repositiory (None to use default)
  22. oneline: True to use --oneline, else False
  23. reverse: True to reverse the log (--reverse)
  24. count: Number of commits to list, or None for no limit
  25. Return:
  26. List containing command and arguments to run
  27. """
  28. cmd = ['git']
  29. if git_dir:
  30. cmd += ['--git-dir', git_dir]
  31. cmd += ['--no-pager', 'log', '--no-color']
  32. if oneline:
  33. cmd.append('--oneline')
  34. if use_no_decorate:
  35. cmd.append('--no-decorate')
  36. if reverse:
  37. cmd.append('--reverse')
  38. if count is not None:
  39. cmd.append('-n%d' % count)
  40. if commit_range:
  41. cmd.append(commit_range)
  42. return cmd
  43. def CountCommitsToBranch():
  44. """Returns number of commits between HEAD and the tracking branch.
  45. This looks back to the tracking branch and works out the number of commits
  46. since then.
  47. Return:
  48. Number of patches that exist on top of the branch
  49. """
  50. pipe = [LogCmd('@{upstream}..', oneline=True),
  51. ['wc', '-l']]
  52. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  53. patch_count = int(stdout)
  54. return patch_count
  55. def NameRevision(commit_hash):
  56. """Gets the revision name for a commit
  57. Args:
  58. commit_hash: Commit hash to look up
  59. Return:
  60. Name of revision, if any, else None
  61. """
  62. pipe = ['git', 'name-rev', commit_hash]
  63. stdout = command.RunPipe([pipe], capture=True, oneline=True).stdout
  64. # We expect a commit, a space, then a revision name
  65. name = stdout.split(' ')[1].strip()
  66. return name
  67. def GuessUpstream(git_dir, branch):
  68. """Tries to guess the upstream for a branch
  69. This lists out top commits on a branch and tries to find a suitable
  70. upstream. It does this by looking for the first commit where
  71. 'git name-rev' returns a plain branch name, with no ! or ^ modifiers.
  72. Args:
  73. git_dir: Git directory containing repo
  74. branch: Name of branch
  75. Returns:
  76. Tuple:
  77. Name of upstream branch (e.g. 'upstream/master') or None if none
  78. Warning/error message, or None if none
  79. """
  80. pipe = [LogCmd(branch, git_dir=git_dir, oneline=True, count=100)]
  81. result = command.RunPipe(pipe, capture=True, capture_stderr=True,
  82. raise_on_error=False)
  83. if result.return_code:
  84. return None, "Branch '%s' not found" % branch
  85. for line in result.stdout.splitlines()[1:]:
  86. commit_hash = line.split(' ')[0]
  87. name = NameRevision(commit_hash)
  88. if '~' not in name and '^' not in name:
  89. if name.startswith('remotes/'):
  90. name = name[8:]
  91. return name, "Guessing upstream as '%s'" % name
  92. return None, "Cannot find a suitable upstream for branch '%s'" % branch
  93. def GetUpstream(git_dir, branch):
  94. """Returns the name of the upstream for a branch
  95. Args:
  96. git_dir: Git directory containing repo
  97. branch: Name of branch
  98. Returns:
  99. Tuple:
  100. Name of upstream branch (e.g. 'upstream/master') or None if none
  101. Warning/error message, or None if none
  102. """
  103. try:
  104. remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  105. 'branch.%s.remote' % branch)
  106. merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  107. 'branch.%s.merge' % branch)
  108. except:
  109. upstream, msg = GuessUpstream(git_dir, branch)
  110. return upstream, msg
  111. if remote == '.':
  112. return merge
  113. elif remote and merge:
  114. leaf = merge.split('/')[-1]
  115. return '%s/%s' % (remote, leaf), None
  116. else:
  117. raise ValueError, ("Cannot determine upstream branch for branch "
  118. "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
  119. def GetRangeInBranch(git_dir, branch, include_upstream=False):
  120. """Returns an expression for the commits in the given branch.
  121. Args:
  122. git_dir: Directory containing git repo
  123. branch: Name of branch
  124. Return:
  125. Expression in the form 'upstream..branch' which can be used to
  126. access the commits. If the branch does not exist, returns None.
  127. """
  128. upstream, msg = GetUpstream(git_dir, branch)
  129. if not upstream:
  130. return None, msg
  131. rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
  132. return rstr, msg
  133. def CountCommitsInRange(git_dir, range_expr):
  134. """Returns the number of commits in the given range.
  135. Args:
  136. git_dir: Directory containing git repo
  137. range_expr: Range to check
  138. Return:
  139. Number of patches that exist in the supplied rangem or None if none
  140. were found
  141. """
  142. pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True)]
  143. result = command.RunPipe(pipe, capture=True, capture_stderr=True,
  144. raise_on_error=False)
  145. if result.return_code:
  146. return None, "Range '%s' not found or is invalid" % range_expr
  147. patch_count = len(result.stdout.splitlines())
  148. return patch_count, None
  149. def CountCommitsInBranch(git_dir, branch, include_upstream=False):
  150. """Returns the number of commits in the given branch.
  151. Args:
  152. git_dir: Directory containing git repo
  153. branch: Name of branch
  154. Return:
  155. Number of patches that exist on top of the branch, or None if the
  156. branch does not exist.
  157. """
  158. range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream)
  159. if not range_expr:
  160. return None, msg
  161. return CountCommitsInRange(git_dir, range_expr)
  162. def CountCommits(commit_range):
  163. """Returns the number of commits in the given range.
  164. Args:
  165. commit_range: Range of commits to count (e.g. 'HEAD..base')
  166. Return:
  167. Number of patches that exist on top of the branch
  168. """
  169. pipe = [LogCmd(commit_range, oneline=True),
  170. ['wc', '-l']]
  171. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  172. patch_count = int(stdout)
  173. return patch_count
  174. def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
  175. """Checkout the selected commit for this build
  176. Args:
  177. commit_hash: Commit hash to check out
  178. """
  179. pipe = ['git']
  180. if git_dir:
  181. pipe.extend(['--git-dir', git_dir])
  182. if work_tree:
  183. pipe.extend(['--work-tree', work_tree])
  184. pipe.append('checkout')
  185. if force:
  186. pipe.append('-f')
  187. pipe.append(commit_hash)
  188. result = command.RunPipe([pipe], capture=True, raise_on_error=False,
  189. capture_stderr=True)
  190. if result.return_code != 0:
  191. raise OSError, 'git checkout (%s): %s' % (pipe, result.stderr)
  192. def Clone(git_dir, output_dir):
  193. """Checkout the selected commit for this build
  194. Args:
  195. commit_hash: Commit hash to check out
  196. """
  197. pipe = ['git', 'clone', git_dir, '.']
  198. result = command.RunPipe([pipe], capture=True, cwd=output_dir,
  199. capture_stderr=True)
  200. if result.return_code != 0:
  201. raise OSError, 'git clone: %s' % result.stderr
  202. def Fetch(git_dir=None, work_tree=None):
  203. """Fetch from the origin repo
  204. Args:
  205. commit_hash: Commit hash to check out
  206. """
  207. pipe = ['git']
  208. if git_dir:
  209. pipe.extend(['--git-dir', git_dir])
  210. if work_tree:
  211. pipe.extend(['--work-tree', work_tree])
  212. pipe.append('fetch')
  213. result = command.RunPipe([pipe], capture=True, capture_stderr=True)
  214. if result.return_code != 0:
  215. raise OSError, 'git fetch: %s' % result.stderr
  216. def CreatePatches(start, count, series):
  217. """Create a series of patches from the top of the current branch.
  218. The patch files are written to the current directory using
  219. git format-patch.
  220. Args:
  221. start: Commit to start from: 0=HEAD, 1=next one, etc.
  222. count: number of commits to include
  223. Return:
  224. Filename of cover letter
  225. List of filenames of patch files
  226. """
  227. if series.get('version'):
  228. version = '%s ' % series['version']
  229. cmd = ['git', 'format-patch', '-M', '--signoff']
  230. if series.get('cover'):
  231. cmd.append('--cover-letter')
  232. prefix = series.GetPatchPrefix()
  233. if prefix:
  234. cmd += ['--subject-prefix=%s' % prefix]
  235. cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
  236. stdout = command.RunList(cmd)
  237. files = stdout.splitlines()
  238. # We have an extra file if there is a cover letter
  239. if series.get('cover'):
  240. return files[0], files[1:]
  241. else:
  242. return None, files
  243. def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
  244. """Build a list of email addresses based on an input list.
  245. Takes a list of email addresses and aliases, and turns this into a list
  246. of only email address, by resolving any aliases that are present.
  247. If the tag is given, then each email address is prepended with this
  248. tag and a space. If the tag starts with a minus sign (indicating a
  249. command line parameter) then the email address is quoted.
  250. Args:
  251. in_list: List of aliases/email addresses
  252. tag: Text to put before each address
  253. alias: Alias dictionary
  254. raise_on_error: True to raise an error when an alias fails to match,
  255. False to just print a message.
  256. Returns:
  257. List of email addresses
  258. >>> alias = {}
  259. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  260. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  261. >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
  262. >>> alias['boys'] = ['fred', ' john']
  263. >>> alias['all'] = ['fred ', 'john', ' mary ']
  264. >>> BuildEmailList(['john', 'mary'], None, alias)
  265. ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
  266. >>> BuildEmailList(['john', 'mary'], '--to', alias)
  267. ['--to "j.bloggs@napier.co.nz"', \
  268. '--to "Mary Poppins <m.poppins@cloud.net>"']
  269. >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
  270. ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
  271. """
  272. quote = '"' if tag and tag[0] == '-' else ''
  273. raw = []
  274. for item in in_list:
  275. raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
  276. result = []
  277. for item in raw:
  278. if not item in result:
  279. result.append(item)
  280. if tag:
  281. return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
  282. return result
  283. def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
  284. self_only=False, alias=None, in_reply_to=None):
  285. """Email a patch series.
  286. Args:
  287. series: Series object containing destination info
  288. cover_fname: filename of cover letter
  289. args: list of filenames of patch files
  290. dry_run: Just return the command that would be run
  291. raise_on_error: True to raise an error when an alias fails to match,
  292. False to just print a message.
  293. cc_fname: Filename of Cc file for per-commit Cc
  294. self_only: True to just email to yourself as a test
  295. in_reply_to: If set we'll pass this to git as --in-reply-to.
  296. Should be a message ID that this is in reply to.
  297. Returns:
  298. Git command that was/would be run
  299. # For the duration of this doctest pretend that we ran patman with ./patman
  300. >>> _old_argv0 = sys.argv[0]
  301. >>> sys.argv[0] = './patman'
  302. >>> alias = {}
  303. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  304. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  305. >>> alias['mary'] = ['m.poppins@cloud.net']
  306. >>> alias['boys'] = ['fred', ' john']
  307. >>> alias['all'] = ['fred ', 'john', ' mary ']
  308. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  309. >>> series = series.Series()
  310. >>> series.to = ['fred']
  311. >>> series.cc = ['mary']
  312. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  313. False, 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" cover p1 p2'
  316. >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
  317. alias)
  318. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  319. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
  320. >>> series.cc = ['all']
  321. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  322. True, alias)
  323. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  324. --cc-cmd cc-fname" cover p1 p2'
  325. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  326. False, alias)
  327. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  328. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  329. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  330. # Restore argv[0] since we clobbered it.
  331. >>> sys.argv[0] = _old_argv0
  332. """
  333. to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
  334. if not to:
  335. git_config_to = command.Output('git', 'config', 'sendemail.to')
  336. if not git_config_to:
  337. print ("No recipient.\n"
  338. "Please add something like this to a commit\n"
  339. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
  340. "Or do something like this\n"
  341. "git config sendemail.to u-boot@lists.denx.de")
  342. return
  343. cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))),
  344. '--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. Alias 'odd' not found
  401. []
  402. >>> # In this case the loop part will effectively be ignored.
  403. >>> LookupEmail('loop', alias, raise_on_error=False)
  404. Recursive email alias at 'other'
  405. Recursive email alias at 'john'
  406. Recursive email alias at 'mary'
  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. global use_no_decorate
  477. alias_fname = GetAliasFile()
  478. if alias_fname:
  479. settings.ReadGitAliases(alias_fname)
  480. cmd = LogCmd(None, count=0)
  481. use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
  482. .return_code == 0)
  483. def GetHead():
  484. """Get the hash of the current HEAD
  485. Returns:
  486. Hash of HEAD
  487. """
  488. return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
  489. if __name__ == "__main__":
  490. import doctest
  491. doctest.testmod()