gitutil.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2011 The Chromium OS Authors.
  3. #
  4. import command
  5. import re
  6. import os
  7. import series
  8. import subprocess
  9. import sys
  10. import terminal
  11. import checkpatch
  12. import settings
  13. # True to use --no-decorate - we check this in Setup()
  14. use_no_decorate = True
  15. def LogCmd(commit_range, git_dir=None, oneline=False, reverse=False,
  16. count=None):
  17. """Create a command to perform a 'git log'
  18. Args:
  19. commit_range: Range expression to use for log, None for none
  20. git_dir: Path to git repositiory (None to use default)
  21. oneline: True to use --oneline, else False
  22. reverse: True to reverse the log (--reverse)
  23. count: Number of commits to list, or None for no limit
  24. Return:
  25. List containing command and arguments to run
  26. """
  27. cmd = ['git']
  28. if git_dir:
  29. cmd += ['--git-dir', git_dir]
  30. cmd += ['--no-pager', 'log', '--no-color']
  31. if oneline:
  32. cmd.append('--oneline')
  33. if use_no_decorate:
  34. cmd.append('--no-decorate')
  35. if reverse:
  36. cmd.append('--reverse')
  37. if count is not None:
  38. cmd.append('-n%d' % count)
  39. if commit_range:
  40. cmd.append(commit_range)
  41. # Add this in case we have a branch with the same name as a directory.
  42. # This avoids messages like this, for example:
  43. # fatal: ambiguous argument 'test': both revision and filename
  44. cmd.append('--')
  45. return cmd
  46. def CountCommitsToBranch():
  47. """Returns number of commits between HEAD and the tracking branch.
  48. This looks back to the tracking branch and works out the number of commits
  49. since then.
  50. Return:
  51. Number of patches that exist on top of the branch
  52. """
  53. pipe = [LogCmd('@{upstream}..', oneline=True),
  54. ['wc', '-l']]
  55. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  56. patch_count = int(stdout)
  57. return patch_count
  58. def NameRevision(commit_hash):
  59. """Gets the revision name for a commit
  60. Args:
  61. commit_hash: Commit hash to look up
  62. Return:
  63. Name of revision, if any, else None
  64. """
  65. pipe = ['git', 'name-rev', commit_hash]
  66. stdout = command.RunPipe([pipe], capture=True, oneline=True).stdout
  67. # We expect a commit, a space, then a revision name
  68. name = stdout.split(' ')[1].strip()
  69. return name
  70. def GuessUpstream(git_dir, branch):
  71. """Tries to guess the upstream for a branch
  72. This lists out top commits on a branch and tries to find a suitable
  73. upstream. It does this by looking for the first commit where
  74. 'git name-rev' returns a plain branch name, with no ! or ^ modifiers.
  75. Args:
  76. git_dir: Git directory containing repo
  77. branch: Name of branch
  78. Returns:
  79. Tuple:
  80. Name of upstream branch (e.g. 'upstream/master') or None if none
  81. Warning/error message, or None if none
  82. """
  83. pipe = [LogCmd(branch, git_dir=git_dir, oneline=True, count=100)]
  84. result = command.RunPipe(pipe, capture=True, capture_stderr=True,
  85. raise_on_error=False)
  86. if result.return_code:
  87. return None, "Branch '%s' not found" % branch
  88. for line in result.stdout.splitlines()[1:]:
  89. commit_hash = line.split(' ')[0]
  90. name = NameRevision(commit_hash)
  91. if '~' not in name and '^' not in name:
  92. if name.startswith('remotes/'):
  93. name = name[8:]
  94. return name, "Guessing upstream as '%s'" % name
  95. return None, "Cannot find a suitable upstream for branch '%s'" % branch
  96. def GetUpstream(git_dir, branch):
  97. """Returns the name of the upstream for a branch
  98. Args:
  99. git_dir: Git directory containing repo
  100. branch: Name of branch
  101. Returns:
  102. Tuple:
  103. Name of upstream branch (e.g. 'upstream/master') or None if none
  104. Warning/error message, or None if none
  105. """
  106. try:
  107. remote = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  108. 'branch.%s.remote' % branch)
  109. merge = command.OutputOneLine('git', '--git-dir', git_dir, 'config',
  110. 'branch.%s.merge' % branch)
  111. except:
  112. upstream, msg = GuessUpstream(git_dir, branch)
  113. return upstream, msg
  114. if remote == '.':
  115. return merge, None
  116. elif remote and merge:
  117. leaf = merge.split('/')[-1]
  118. return '%s/%s' % (remote, leaf), None
  119. else:
  120. raise ValueError("Cannot determine upstream branch for branch "
  121. "'%s' remote='%s', merge='%s'" % (branch, remote, merge))
  122. def GetRangeInBranch(git_dir, branch, include_upstream=False):
  123. """Returns an expression for the commits in the given branch.
  124. Args:
  125. git_dir: Directory containing git repo
  126. branch: Name of branch
  127. Return:
  128. Expression in the form 'upstream..branch' which can be used to
  129. access the commits. If the branch does not exist, returns None.
  130. """
  131. upstream, msg = GetUpstream(git_dir, branch)
  132. if not upstream:
  133. return None, msg
  134. rstr = '%s%s..%s' % (upstream, '~' if include_upstream else '', branch)
  135. return rstr, msg
  136. def CountCommitsInRange(git_dir, range_expr):
  137. """Returns the number of commits in the given range.
  138. Args:
  139. git_dir: Directory containing git repo
  140. range_expr: Range to check
  141. Return:
  142. Number of patches that exist in the supplied rangem or None if none
  143. were found
  144. """
  145. pipe = [LogCmd(range_expr, git_dir=git_dir, oneline=True)]
  146. result = command.RunPipe(pipe, capture=True, capture_stderr=True,
  147. raise_on_error=False)
  148. if result.return_code:
  149. return None, "Range '%s' not found or is invalid" % range_expr
  150. patch_count = len(result.stdout.splitlines())
  151. return patch_count, None
  152. def CountCommitsInBranch(git_dir, branch, include_upstream=False):
  153. """Returns the number of commits in the given branch.
  154. Args:
  155. git_dir: Directory containing git repo
  156. branch: Name of branch
  157. Return:
  158. Number of patches that exist on top of the branch, or None if the
  159. branch does not exist.
  160. """
  161. range_expr, msg = GetRangeInBranch(git_dir, branch, include_upstream)
  162. if not range_expr:
  163. return None, msg
  164. return CountCommitsInRange(git_dir, range_expr)
  165. def CountCommits(commit_range):
  166. """Returns the number of commits in the given range.
  167. Args:
  168. commit_range: Range of commits to count (e.g. 'HEAD..base')
  169. Return:
  170. Number of patches that exist on top of the branch
  171. """
  172. pipe = [LogCmd(commit_range, oneline=True),
  173. ['wc', '-l']]
  174. stdout = command.RunPipe(pipe, capture=True, oneline=True).stdout
  175. patch_count = int(stdout)
  176. return patch_count
  177. def Checkout(commit_hash, git_dir=None, work_tree=None, force=False):
  178. """Checkout the selected commit for this build
  179. Args:
  180. commit_hash: Commit hash to check out
  181. """
  182. pipe = ['git']
  183. if git_dir:
  184. pipe.extend(['--git-dir', git_dir])
  185. if work_tree:
  186. pipe.extend(['--work-tree', work_tree])
  187. pipe.append('checkout')
  188. if force:
  189. pipe.append('-f')
  190. pipe.append(commit_hash)
  191. result = command.RunPipe([pipe], capture=True, raise_on_error=False,
  192. capture_stderr=True)
  193. if result.return_code != 0:
  194. raise OSError('git checkout (%s): %s' % (pipe, result.stderr))
  195. def Clone(git_dir, output_dir):
  196. """Checkout the selected commit for this build
  197. Args:
  198. commit_hash: Commit hash to check out
  199. """
  200. pipe = ['git', 'clone', git_dir, '.']
  201. result = command.RunPipe([pipe], capture=True, cwd=output_dir,
  202. capture_stderr=True)
  203. if result.return_code != 0:
  204. raise OSError('git clone: %s' % result.stderr)
  205. def Fetch(git_dir=None, work_tree=None):
  206. """Fetch from the origin repo
  207. Args:
  208. commit_hash: Commit hash to check out
  209. """
  210. pipe = ['git']
  211. if git_dir:
  212. pipe.extend(['--git-dir', git_dir])
  213. if work_tree:
  214. pipe.extend(['--work-tree', work_tree])
  215. pipe.append('fetch')
  216. result = command.RunPipe([pipe], capture=True, capture_stderr=True)
  217. if result.return_code != 0:
  218. raise OSError('git fetch: %s' % result.stderr)
  219. def CreatePatches(start, count, series):
  220. """Create a series of patches from the top of the current branch.
  221. The patch files are written to the current directory using
  222. git format-patch.
  223. Args:
  224. start: Commit to start from: 0=HEAD, 1=next one, etc.
  225. count: number of commits to include
  226. Return:
  227. Filename of cover letter
  228. List of filenames of patch files
  229. """
  230. if series.get('version'):
  231. version = '%s ' % series['version']
  232. cmd = ['git', 'format-patch', '-M', '--signoff']
  233. if series.get('cover'):
  234. cmd.append('--cover-letter')
  235. prefix = series.GetPatchPrefix()
  236. if prefix:
  237. cmd += ['--subject-prefix=%s' % prefix]
  238. cmd += ['HEAD~%d..HEAD~%d' % (start + count, start)]
  239. stdout = command.RunList(cmd)
  240. files = stdout.splitlines()
  241. # We have an extra file if there is a cover letter
  242. if series.get('cover'):
  243. return files[0], files[1:]
  244. else:
  245. return None, files
  246. def BuildEmailList(in_list, tag=None, alias=None, raise_on_error=True):
  247. """Build a list of email addresses based on an input list.
  248. Takes a list of email addresses and aliases, and turns this into a list
  249. of only email address, by resolving any aliases that are present.
  250. If the tag is given, then each email address is prepended with this
  251. tag and a space. If the tag starts with a minus sign (indicating a
  252. command line parameter) then the email address is quoted.
  253. Args:
  254. in_list: List of aliases/email addresses
  255. tag: Text to put before each address
  256. alias: Alias dictionary
  257. raise_on_error: True to raise an error when an alias fails to match,
  258. False to just print a message.
  259. Returns:
  260. List of email addresses
  261. >>> alias = {}
  262. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  263. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  264. >>> alias['mary'] = ['Mary Poppins <m.poppins@cloud.net>']
  265. >>> alias['boys'] = ['fred', ' john']
  266. >>> alias['all'] = ['fred ', 'john', ' mary ']
  267. >>> BuildEmailList(['john', 'mary'], None, alias)
  268. ['j.bloggs@napier.co.nz', 'Mary Poppins <m.poppins@cloud.net>']
  269. >>> BuildEmailList(['john', 'mary'], '--to', alias)
  270. ['--to "j.bloggs@napier.co.nz"', \
  271. '--to "Mary Poppins <m.poppins@cloud.net>"']
  272. >>> BuildEmailList(['john', 'mary'], 'Cc', alias)
  273. ['Cc j.bloggs@napier.co.nz', 'Cc Mary Poppins <m.poppins@cloud.net>']
  274. """
  275. quote = '"' if tag and tag[0] == '-' else ''
  276. raw = []
  277. for item in in_list:
  278. raw += LookupEmail(item, alias, raise_on_error=raise_on_error)
  279. result = []
  280. for item in raw:
  281. if not item in result:
  282. result.append(item)
  283. if tag:
  284. return ['%s %s%s%s' % (tag, quote, email, quote) for email in result]
  285. return result
  286. def EmailPatches(series, cover_fname, args, dry_run, raise_on_error, cc_fname,
  287. self_only=False, alias=None, in_reply_to=None, thread=False,
  288. smtp_server=None):
  289. """Email a patch series.
  290. Args:
  291. series: Series object containing destination info
  292. cover_fname: filename of cover letter
  293. args: list of filenames of patch files
  294. dry_run: Just return the command that would be run
  295. raise_on_error: True to raise an error when an alias fails to match,
  296. False to just print a message.
  297. cc_fname: Filename of Cc file for per-commit Cc
  298. self_only: True to just email to yourself as a test
  299. in_reply_to: If set we'll pass this to git as --in-reply-to.
  300. Should be a message ID that this is in reply to.
  301. thread: True to add --thread to git send-email (make
  302. all patches reply to cover-letter or first patch in series)
  303. smtp_server: SMTP server to use to send patches
  304. Returns:
  305. Git command that was/would be run
  306. # For the duration of this doctest pretend that we ran patman with ./patman
  307. >>> _old_argv0 = sys.argv[0]
  308. >>> sys.argv[0] = './patman'
  309. >>> alias = {}
  310. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  311. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  312. >>> alias['mary'] = ['m.poppins@cloud.net']
  313. >>> alias['boys'] = ['fred', ' john']
  314. >>> alias['all'] = ['fred ', 'john', ' mary ']
  315. >>> alias[os.getenv('USER')] = ['this-is-me@me.com']
  316. >>> series = series.Series()
  317. >>> series.to = ['fred']
  318. >>> series.cc = ['mary']
  319. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  320. False, alias)
  321. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  322. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  323. >>> EmailPatches(series, None, ['p1'], True, True, 'cc-fname', False, \
  324. alias)
  325. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  326. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" p1'
  327. >>> series.cc = ['all']
  328. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  329. True, alias)
  330. 'git send-email --annotate --to "this-is-me@me.com" --cc-cmd "./patman \
  331. --cc-cmd cc-fname" cover p1 p2'
  332. >>> EmailPatches(series, 'cover', ['p1', 'p2'], True, True, 'cc-fname', \
  333. False, alias)
  334. 'git send-email --annotate --to "f.bloggs@napier.co.nz" --cc \
  335. "f.bloggs@napier.co.nz" --cc "j.bloggs@napier.co.nz" --cc \
  336. "m.poppins@cloud.net" --cc-cmd "./patman --cc-cmd cc-fname" cover p1 p2'
  337. # Restore argv[0] since we clobbered it.
  338. >>> sys.argv[0] = _old_argv0
  339. """
  340. to = BuildEmailList(series.get('to'), '--to', alias, raise_on_error)
  341. if not to:
  342. git_config_to = command.Output('git', 'config', 'sendemail.to',
  343. raise_on_error=False)
  344. if not git_config_to:
  345. print ("No recipient.\n"
  346. "Please add something like this to a commit\n"
  347. "Series-to: Fred Bloggs <f.blogs@napier.co.nz>\n"
  348. "Or do something like this\n"
  349. "git config sendemail.to u-boot@lists.denx.de")
  350. return
  351. cc = BuildEmailList(list(set(series.get('cc')) - set(series.get('to'))),
  352. '--cc', alias, raise_on_error)
  353. if self_only:
  354. to = BuildEmailList([os.getenv('USER')], '--to', alias, raise_on_error)
  355. cc = []
  356. cmd = ['git', 'send-email', '--annotate']
  357. if smtp_server:
  358. cmd.append('--smtp-server=%s' % smtp_server)
  359. if in_reply_to:
  360. if type(in_reply_to) != str:
  361. in_reply_to = in_reply_to.encode('utf-8')
  362. cmd.append('--in-reply-to="%s"' % in_reply_to)
  363. if thread:
  364. cmd.append('--thread')
  365. cmd += to
  366. cmd += cc
  367. cmd += ['--cc-cmd', '"%s --cc-cmd %s"' % (sys.argv[0], cc_fname)]
  368. if cover_fname:
  369. cmd.append(cover_fname)
  370. cmd += args
  371. cmdstr = ' '.join(cmd)
  372. if not dry_run:
  373. os.system(cmdstr)
  374. return cmdstr
  375. def LookupEmail(lookup_name, alias=None, raise_on_error=True, level=0):
  376. """If an email address is an alias, look it up and return the full name
  377. TODO: Why not just use git's own alias feature?
  378. Args:
  379. lookup_name: Alias or email address to look up
  380. alias: Dictionary containing aliases (None to use settings default)
  381. raise_on_error: True to raise an error when an alias fails to match,
  382. False to just print a message.
  383. Returns:
  384. tuple:
  385. list containing a list of email addresses
  386. Raises:
  387. OSError if a recursive alias reference was found
  388. ValueError if an alias was not found
  389. >>> alias = {}
  390. >>> alias['fred'] = ['f.bloggs@napier.co.nz']
  391. >>> alias['john'] = ['j.bloggs@napier.co.nz']
  392. >>> alias['mary'] = ['m.poppins@cloud.net']
  393. >>> alias['boys'] = ['fred', ' john', 'f.bloggs@napier.co.nz']
  394. >>> alias['all'] = ['fred ', 'john', ' mary ']
  395. >>> alias['loop'] = ['other', 'john', ' mary ']
  396. >>> alias['other'] = ['loop', 'john', ' mary ']
  397. >>> LookupEmail('mary', alias)
  398. ['m.poppins@cloud.net']
  399. >>> LookupEmail('arthur.wellesley@howe.ro.uk', alias)
  400. ['arthur.wellesley@howe.ro.uk']
  401. >>> LookupEmail('boys', alias)
  402. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz']
  403. >>> LookupEmail('all', alias)
  404. ['f.bloggs@napier.co.nz', 'j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  405. >>> LookupEmail('odd', alias)
  406. Traceback (most recent call last):
  407. ...
  408. ValueError: Alias 'odd' not found
  409. >>> LookupEmail('loop', alias)
  410. Traceback (most recent call last):
  411. ...
  412. OSError: Recursive email alias at 'other'
  413. >>> LookupEmail('odd', alias, raise_on_error=False)
  414. Alias 'odd' not found
  415. []
  416. >>> # In this case the loop part will effectively be ignored.
  417. >>> LookupEmail('loop', alias, raise_on_error=False)
  418. Recursive email alias at 'other'
  419. Recursive email alias at 'john'
  420. Recursive email alias at 'mary'
  421. ['j.bloggs@napier.co.nz', 'm.poppins@cloud.net']
  422. """
  423. if not alias:
  424. alias = settings.alias
  425. lookup_name = lookup_name.strip()
  426. if '@' in lookup_name: # Perhaps a real email address
  427. return [lookup_name]
  428. lookup_name = lookup_name.lower()
  429. col = terminal.Color()
  430. out_list = []
  431. if level > 10:
  432. msg = "Recursive email alias at '%s'" % lookup_name
  433. if raise_on_error:
  434. raise OSError(msg)
  435. else:
  436. print(col.Color(col.RED, msg))
  437. return out_list
  438. if lookup_name:
  439. if not lookup_name in alias:
  440. msg = "Alias '%s' not found" % lookup_name
  441. if raise_on_error:
  442. raise ValueError(msg)
  443. else:
  444. print(col.Color(col.RED, msg))
  445. return out_list
  446. for item in alias[lookup_name]:
  447. todo = LookupEmail(item, alias, raise_on_error, level + 1)
  448. for new_item in todo:
  449. if not new_item in out_list:
  450. out_list.append(new_item)
  451. #print("No match for alias '%s'" % lookup_name)
  452. return out_list
  453. def GetTopLevel():
  454. """Return name of top-level directory for this git repo.
  455. Returns:
  456. Full path to git top-level directory
  457. This test makes sure that we are running tests in the right subdir
  458. >>> os.path.realpath(os.path.dirname(__file__)) == \
  459. os.path.join(GetTopLevel(), 'tools', 'patman')
  460. True
  461. """
  462. return command.OutputOneLine('git', 'rev-parse', '--show-toplevel')
  463. def GetAliasFile():
  464. """Gets the name of the git alias file.
  465. Returns:
  466. Filename of git alias file, or None if none
  467. """
  468. fname = command.OutputOneLine('git', 'config', 'sendemail.aliasesfile',
  469. raise_on_error=False)
  470. if fname:
  471. fname = os.path.join(GetTopLevel(), fname.strip())
  472. return fname
  473. def GetDefaultUserName():
  474. """Gets the user.name from .gitconfig file.
  475. Returns:
  476. User name found in .gitconfig file, or None if none
  477. """
  478. uname = command.OutputOneLine('git', 'config', '--global', 'user.name')
  479. return uname
  480. def GetDefaultUserEmail():
  481. """Gets the user.email from the global .gitconfig file.
  482. Returns:
  483. User's email found in .gitconfig file, or None if none
  484. """
  485. uemail = command.OutputOneLine('git', 'config', '--global', 'user.email')
  486. return uemail
  487. def GetDefaultSubjectPrefix():
  488. """Gets the format.subjectprefix from local .git/config file.
  489. Returns:
  490. Subject prefix found in local .git/config file, or None if none
  491. """
  492. sub_prefix = command.OutputOneLine('git', 'config', 'format.subjectprefix',
  493. raise_on_error=False)
  494. return sub_prefix
  495. def Setup():
  496. """Set up git utils, by reading the alias files."""
  497. # Check for a git alias file also
  498. global use_no_decorate
  499. alias_fname = GetAliasFile()
  500. if alias_fname:
  501. settings.ReadGitAliases(alias_fname)
  502. cmd = LogCmd(None, count=0)
  503. use_no_decorate = (command.RunPipe([cmd], raise_on_error=False)
  504. .return_code == 0)
  505. def GetHead():
  506. """Get the hash of the current HEAD
  507. Returns:
  508. Hash of HEAD
  509. """
  510. return command.OutputOneLine('git', 'show', '-s', '--pretty=format:%H')
  511. if __name__ == "__main__":
  512. import doctest
  513. doctest.testmod()