gitutil.py 23 KB

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