git-clang-format 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. #!/usr/bin/env python3
  2. #
  3. # ===- git-clang-format - ClangFormat Git Integration -------*- python -*--=== #
  4. #
  5. # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  6. # See https://llvm.org/LICENSE.txt for license information.
  7. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  8. #
  9. # ===----------------------------------------------------------------------=== #
  10. r"""
  11. clang-format git integration
  12. ============================
  13. This file provides a clang-format integration for git. Put it somewhere in your
  14. path and ensure that it is executable. Then, "git clang-format" will invoke
  15. clang-format on the changes in current files or a specific commit.
  16. For further details, run:
  17. git clang-format -h
  18. Requires Python version >=3.8
  19. """
  20. from __future__ import absolute_import, division, print_function
  21. import argparse
  22. import collections
  23. import contextlib
  24. import errno
  25. import os
  26. import re
  27. import subprocess
  28. import sys
  29. usage = "git clang-format [OPTIONS] [<commit>] [<commit>|--staged] [--] [<file>...]"
  30. desc = """
  31. If zero or one commits are given, run clang-format on all lines that differ
  32. between the working directory and <commit>, which defaults to HEAD. Changes are
  33. only applied to the working directory, or in the stage/index.
  34. Examples:
  35. To format staged changes, i.e everything that's been `git add`ed:
  36. git clang-format
  37. To also format everything touched in the most recent commit:
  38. git clang-format HEAD~1
  39. If you're on a branch off main, to format everything touched on your branch:
  40. git clang-format main
  41. If two commits are given (requires --diff), run clang-format on all lines in the
  42. second <commit> that differ from the first <commit>.
  43. The following git-config settings set the default of the corresponding option:
  44. clangFormat.binary
  45. clangFormat.commit
  46. clangFormat.extensions
  47. clangFormat.style
  48. """
  49. # Name of the temporary index file in which save the output of clang-format.
  50. # This file is created within the .git directory.
  51. temp_index_basename = "clang-format-index"
  52. Range = collections.namedtuple("Range", "start, count")
  53. def main():
  54. config = load_git_config()
  55. # In order to keep '--' yet allow options after positionals, we need to
  56. # check for '--' ourselves. (Setting nargs='*' throws away the '--', while
  57. # nargs=argparse.REMAINDER disallows options after positionals.)
  58. argv = sys.argv[1:]
  59. try:
  60. idx = argv.index("--")
  61. except ValueError:
  62. dash_dash = []
  63. else:
  64. dash_dash = argv[idx:]
  65. argv = argv[:idx]
  66. default_extensions = ",".join(
  67. [
  68. # From clang/lib/Frontend/FrontendOptions.cpp, all lower case
  69. "c",
  70. "h", # C
  71. "m", # ObjC
  72. "mm", # ObjC++
  73. "cc",
  74. "cp",
  75. "cpp",
  76. "c++",
  77. "cxx",
  78. "hh",
  79. "hpp",
  80. "hxx",
  81. "inc", # C++
  82. "ccm",
  83. "cppm",
  84. "cxxm",
  85. "c++m", # C++ Modules
  86. "cu",
  87. "cuh", # CUDA
  88. "cl", # OpenCL
  89. # Other languages that clang-format supports
  90. "proto",
  91. "protodevel", # Protocol Buffers
  92. "java", # Java
  93. "js",
  94. "mjs",
  95. "cjs", # JavaScript
  96. "ts", # TypeScript
  97. "cs", # C Sharp
  98. "json",
  99. "ipynb", # JSON
  100. "sv",
  101. "svh",
  102. "v",
  103. "vh", # Verilog
  104. "td", # TableGen
  105. "txtpb",
  106. "textpb",
  107. "pb.txt",
  108. "textproto",
  109. "asciipb", # TextProto
  110. ]
  111. )
  112. p = argparse.ArgumentParser(
  113. usage=usage,
  114. formatter_class=argparse.RawDescriptionHelpFormatter,
  115. description=desc,
  116. )
  117. p.add_argument(
  118. "--binary",
  119. default=config.get("clangformat.binary", "clang-format"),
  120. help="path to clang-format",
  121. ),
  122. p.add_argument(
  123. "--commit",
  124. default=config.get("clangformat.commit", "HEAD"),
  125. help="default commit to use if none is specified",
  126. ),
  127. p.add_argument(
  128. "--diff",
  129. action="store_true",
  130. help="print a diff instead of applying the changes",
  131. )
  132. p.add_argument(
  133. "--diffstat",
  134. action="store_true",
  135. help="print a diffstat instead of applying the changes",
  136. )
  137. p.add_argument(
  138. "--extensions",
  139. default=config.get("clangformat.extensions", default_extensions),
  140. help=(
  141. "comma-separated list of file extensions to format, "
  142. "excluding the period and case-insensitive"
  143. ),
  144. ),
  145. p.add_argument(
  146. "-f",
  147. "--force",
  148. action="store_true",
  149. help="allow changes to unstaged files",
  150. )
  151. p.add_argument(
  152. "-p", "--patch", action="store_true", help="select hunks interactively"
  153. )
  154. p.add_argument(
  155. "-q",
  156. "--quiet",
  157. action="count",
  158. default=0,
  159. help="print less information",
  160. )
  161. p.add_argument(
  162. "--staged",
  163. "--cached",
  164. action="store_true",
  165. help="format lines in the stage instead of the working dir",
  166. )
  167. p.add_argument(
  168. "--style",
  169. default=config.get("clangformat.style", None),
  170. help="passed to clang-format",
  171. ),
  172. p.add_argument(
  173. "-v",
  174. "--verbose",
  175. action="count",
  176. default=0,
  177. help="print extra information",
  178. )
  179. p.add_argument(
  180. "--diff_from_common_commit",
  181. action="store_true",
  182. help=(
  183. "diff from the last common commit for commits in "
  184. "separate branches rather than the exact point of the "
  185. "commits"
  186. ),
  187. )
  188. # We gather all the remaining positional arguments into 'args' since we need
  189. # to use some heuristics to determine whether or not <commit> was present.
  190. # However, to print pretty messages, we make use of metavar and help.
  191. p.add_argument(
  192. "args",
  193. nargs="*",
  194. metavar="<commit>",
  195. help="revision from which to compute the diff",
  196. )
  197. p.add_argument(
  198. "ignored",
  199. nargs="*",
  200. metavar="<file>...",
  201. help="if specified, only consider differences in these files",
  202. )
  203. opts = p.parse_args(argv)
  204. opts.verbose -= opts.quiet
  205. del opts.quiet
  206. commits, files = interpret_args(opts.args, dash_dash, opts.commit)
  207. if len(commits) > 2:
  208. die("at most two commits allowed; %d given" % len(commits))
  209. if len(commits) == 2:
  210. if opts.staged:
  211. die("--staged is not allowed when two commits are given")
  212. if not opts.diff:
  213. die("--diff is required when two commits are given")
  214. elif opts.diff_from_common_commit:
  215. die("--diff_from_common_commit is only allowed when two commits are given")
  216. if os.path.dirname(opts.binary):
  217. opts.binary = os.path.abspath(opts.binary)
  218. changed_lines = compute_diff_and_extract_lines(
  219. commits, files, opts.staged, opts.diff_from_common_commit
  220. )
  221. if opts.verbose >= 1:
  222. ignored_files = set(changed_lines)
  223. filter_by_extension(changed_lines, opts.extensions.lower().split(","))
  224. # The computed diff outputs absolute paths, so we must cd before accessing
  225. # those files.
  226. cd_to_toplevel()
  227. filter_symlinks(changed_lines)
  228. filter_ignored_files(changed_lines, binary=opts.binary)
  229. if opts.verbose >= 1:
  230. ignored_files.difference_update(changed_lines)
  231. if ignored_files:
  232. print(
  233. "Ignoring the following files (wrong extension, symlink, or "
  234. "ignored by clang-format):"
  235. )
  236. for filename in ignored_files:
  237. print(" %s" % filename)
  238. if changed_lines:
  239. print("Running clang-format on the following files:")
  240. for filename in changed_lines:
  241. print(" %s" % filename)
  242. if not changed_lines:
  243. if opts.verbose >= 0:
  244. print("no modified files to format")
  245. return 0
  246. if len(commits) > 1:
  247. old_tree = commits[1]
  248. revision = old_tree
  249. elif opts.staged:
  250. old_tree = create_tree_from_index(changed_lines)
  251. revision = ""
  252. else:
  253. old_tree = create_tree_from_workdir(changed_lines)
  254. revision = None
  255. new_tree = run_clang_format_and_save_to_tree(
  256. changed_lines, revision, binary=opts.binary, style=opts.style
  257. )
  258. if opts.verbose >= 1:
  259. print("old tree: %s" % old_tree)
  260. print("new tree: %s" % new_tree)
  261. if old_tree == new_tree:
  262. if opts.verbose >= 0:
  263. print("clang-format did not modify any files")
  264. return 0
  265. if opts.diff:
  266. return print_diff(old_tree, new_tree)
  267. if opts.diffstat:
  268. return print_diffstat(old_tree, new_tree)
  269. changed_files = apply_changes(
  270. old_tree, new_tree, force=opts.force, patch_mode=opts.patch
  271. )
  272. if (opts.verbose >= 0 and not opts.patch) or opts.verbose >= 1:
  273. print("changed files:")
  274. for filename in changed_files:
  275. print(" %s" % filename)
  276. return 1
  277. def load_git_config(non_string_options=None):
  278. """Return the git configuration as a dictionary.
  279. All options are assumed to be strings unless in `non_string_options`, in
  280. which is a dictionary mapping option name (in lower case) to either "--bool"
  281. or "--int"."""
  282. if non_string_options is None:
  283. non_string_options = {}
  284. out = {}
  285. for entry in run("git", "config", "--list", "--null").split("\0"):
  286. if entry:
  287. if "\n" in entry:
  288. name, value = entry.split("\n", 1)
  289. else:
  290. # A setting with no '=' ('\n' with --null) is implicitly 'true'
  291. name = entry
  292. value = "true"
  293. if name in non_string_options:
  294. value = run("git", "config", non_string_options[name], name)
  295. out[name] = value
  296. return out
  297. def interpret_args(args, dash_dash, default_commit):
  298. """Interpret `args` as "[commits] [--] [files]" and return (commits, files).
  299. It is assumed that "--" and everything that follows has been removed from
  300. args and placed in `dash_dash`.
  301. If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its
  302. left (if present) are taken as commits. Otherwise, the arguments are
  303. checked from left to right if they are commits or files. If commits are not
  304. given, a list with `default_commit` is used."""
  305. if dash_dash:
  306. if len(args) == 0:
  307. commits = [default_commit]
  308. else:
  309. commits = args
  310. for commit in commits:
  311. object_type = get_object_type(commit)
  312. if object_type not in ("commit", "tag"):
  313. if object_type is None:
  314. die("'%s' is not a commit" % commit)
  315. else:
  316. die(
  317. "'%s' is a %s, but a commit was expected"
  318. % (commit, object_type)
  319. )
  320. files = dash_dash[1:]
  321. elif args:
  322. commits = []
  323. while args:
  324. if not disambiguate_revision(args[0]):
  325. break
  326. commits.append(args.pop(0))
  327. if not commits:
  328. commits = [default_commit]
  329. files = args
  330. else:
  331. commits = [default_commit]
  332. files = []
  333. return commits, files
  334. def disambiguate_revision(value):
  335. """Returns True if `value` is a revision, False if it is a file, or dies."""
  336. # If `value` is ambiguous (neither a commit nor a file), the following
  337. # command will die with an appropriate error message.
  338. run("git", "rev-parse", value, verbose=False)
  339. object_type = get_object_type(value)
  340. if object_type is None:
  341. return False
  342. if object_type in ("commit", "tag"):
  343. return True
  344. die("`%s` is a %s, but a commit or filename was expected" % (value, object_type))
  345. def get_object_type(value):
  346. """Returns a string description of an object's type, or None if it is not
  347. a valid git object."""
  348. cmd = ["git", "cat-file", "-t", value]
  349. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  350. stdout, stderr = p.communicate()
  351. if p.returncode != 0:
  352. return None
  353. return convert_string(stdout.strip())
  354. def compute_diff_and_extract_lines(commits, files, staged, diff_common_commit):
  355. """Calls compute_diff() followed by extract_lines()."""
  356. diff_process = compute_diff(commits, files, staged, diff_common_commit)
  357. changed_lines = extract_lines(diff_process.stdout)
  358. diff_process.stdout.close()
  359. diff_process.wait()
  360. if diff_process.returncode != 0:
  361. # Assume error was already printed to stderr.
  362. sys.exit(2)
  363. return changed_lines
  364. def compute_diff(commits, files, staged, diff_common_commit):
  365. """Return a subprocess object producing the diff from `commits`.
  366. The return value's `stdin` file object will produce a patch with the
  367. differences between the working directory (or stage if --staged is used) and
  368. the first commit if a single one was specified, or the difference between
  369. both specified commits, filtered on `files` (if non-empty).
  370. Zero context lines are used in the patch."""
  371. git_tool = "diff-index"
  372. extra_args = []
  373. if len(commits) == 2:
  374. git_tool = "diff-tree"
  375. if diff_common_commit:
  376. extra_args += ["--merge-base"]
  377. elif staged:
  378. extra_args += ["--cached"]
  379. cmd = ["git", git_tool, "-p", "-U0"] + extra_args + commits + ["--"]
  380. cmd.extend(files)
  381. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  382. p.stdin.close()
  383. return p
  384. def extract_lines(patch_file):
  385. """Extract the changed lines in `patch_file`.
  386. The return value is a dictionary mapping filename to a list of (start_line,
  387. line_count) pairs.
  388. The input must have been produced with ``-U0``, meaning unidiff format with
  389. zero lines of context. The return value is a dict mapping filename to a
  390. list of line `Range`s."""
  391. matches = {}
  392. for line in patch_file:
  393. line = convert_string(line)
  394. match = re.search(r"^\+\+\+\ [^/]+/(.*)", line)
  395. if match:
  396. filename = match.group(1).rstrip("\r\n\t")
  397. match = re.search(r"^@@ -[0-9,]+ \+(\d+)(,(\d+))?", line)
  398. if match:
  399. start_line = int(match.group(1))
  400. line_count = 1
  401. if match.group(3):
  402. line_count = int(match.group(3))
  403. if line_count == 0:
  404. line_count = 1
  405. if start_line == 0:
  406. continue
  407. matches.setdefault(filename, []).append(Range(start_line, line_count))
  408. return matches
  409. def filter_by_extension(dictionary, allowed_extensions):
  410. """Delete every key in `dictionary` that doesn't have an allowed extension.
  411. `allowed_extensions` must be a collection of lowercase file extensions,
  412. excluding the period."""
  413. allowed_extensions = frozenset(allowed_extensions)
  414. for filename in list(dictionary.keys()):
  415. base_ext = filename.rsplit(".", 1)
  416. if len(base_ext) == 1 and "" in allowed_extensions:
  417. continue
  418. if len(base_ext) == 1 or base_ext[1].lower() not in allowed_extensions:
  419. del dictionary[filename]
  420. def filter_symlinks(dictionary):
  421. """Delete every key in `dictionary` that is a symlink."""
  422. for filename in list(dictionary.keys()):
  423. if os.path.islink(filename):
  424. del dictionary[filename]
  425. def filter_ignored_files(dictionary, binary):
  426. """Delete every key in `dictionary` that is ignored by clang-format."""
  427. ignored_files = run(binary, "-list-ignored", *dictionary.keys())
  428. if not ignored_files:
  429. return
  430. ignored_files = ignored_files.split("\n")
  431. for filename in ignored_files:
  432. del dictionary[filename]
  433. def cd_to_toplevel():
  434. """Change to the top level of the git repository."""
  435. toplevel = run("git", "rev-parse", "--show-toplevel")
  436. os.chdir(toplevel)
  437. def create_tree_from_workdir(filenames):
  438. """Create a new git tree with the given files from the working directory.
  439. Returns the object ID (SHA-1) of the created tree."""
  440. return create_tree(filenames, "--stdin")
  441. def create_tree_from_index(filenames):
  442. # Copy the environment, because the files have to be read from the original
  443. # index.
  444. env = os.environ.copy()
  445. def index_contents_generator():
  446. for filename in filenames:
  447. git_ls_files_cmd = [
  448. "git",
  449. "ls-files",
  450. "--stage",
  451. "-z",
  452. "--",
  453. filename,
  454. ]
  455. git_ls_files = subprocess.Popen(
  456. git_ls_files_cmd,
  457. env=env,
  458. stdin=subprocess.PIPE,
  459. stdout=subprocess.PIPE,
  460. )
  461. stdout = git_ls_files.communicate()[0]
  462. yield convert_string(stdout.split(b"\0")[0])
  463. return create_tree(index_contents_generator(), "--index-info")
  464. def run_clang_format_and_save_to_tree(
  465. changed_lines, revision=None, binary="clang-format", style=None
  466. ):
  467. """Run clang-format on each file and save the result to a git tree.
  468. Returns the object ID (SHA-1) of the created tree."""
  469. # Copy the environment when formatting the files in the index, because the
  470. # files have to be read from the original index.
  471. env = os.environ.copy() if revision == "" else None
  472. def iteritems(container):
  473. try:
  474. return container.iteritems() # Python 2
  475. except AttributeError:
  476. return container.items() # Python 3
  477. def index_info_generator():
  478. for filename, line_ranges in iteritems(changed_lines):
  479. if revision is not None:
  480. if len(revision) > 0:
  481. git_metadata_cmd = [
  482. "git",
  483. "ls-tree",
  484. "%s:%s" % (revision, os.path.dirname(filename)),
  485. os.path.basename(filename),
  486. ]
  487. else:
  488. git_metadata_cmd = [
  489. "git",
  490. "ls-files",
  491. "--stage",
  492. "--",
  493. filename,
  494. ]
  495. git_metadata = subprocess.Popen(
  496. git_metadata_cmd,
  497. env=env,
  498. stdin=subprocess.PIPE,
  499. stdout=subprocess.PIPE,
  500. )
  501. stdout = git_metadata.communicate()[0]
  502. mode = oct(int(stdout.split()[0], 8))
  503. else:
  504. mode = oct(os.stat(filename).st_mode)
  505. # Adjust python3 octal format so that it matches what git expects
  506. if mode.startswith("0o"):
  507. mode = "0" + mode[2:]
  508. blob_id = clang_format_to_blob(
  509. filename,
  510. line_ranges,
  511. revision=revision,
  512. binary=binary,
  513. style=style,
  514. env=env,
  515. )
  516. yield "%s %s\t%s" % (mode, blob_id, filename)
  517. return create_tree(index_info_generator(), "--index-info")
  518. def create_tree(input_lines, mode):
  519. """Create a tree object from the given input.
  520. If mode is '--stdin', it must be a list of filenames. If mode is
  521. '--index-info' is must be a list of values suitable for "git update-index
  522. --index-info", such as "<mode> <SP> <sha1> <TAB> <filename>". Any other
  523. mode is invalid."""
  524. assert mode in ("--stdin", "--index-info")
  525. cmd = ["git", "update-index", "--add", "-z", mode]
  526. with temporary_index_file():
  527. p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  528. for line in input_lines:
  529. p.stdin.write(to_bytes("%s\0" % line))
  530. p.stdin.close()
  531. if p.wait() != 0:
  532. die("`%s` failed" % " ".join(cmd))
  533. tree_id = run("git", "write-tree")
  534. return tree_id
  535. def clang_format_to_blob(
  536. filename,
  537. line_ranges,
  538. revision=None,
  539. binary="clang-format",
  540. style=None,
  541. env=None,
  542. ):
  543. """Run clang-format on the given file and save the result to a git blob.
  544. Runs on the file in `revision` if not None, or on the file in the working
  545. directory if `revision` is None. Revision can be set to an empty string to
  546. run clang-format on the file in the index.
  547. Returns the object ID (SHA-1) of the created blob."""
  548. clang_format_cmd = [binary]
  549. if style:
  550. clang_format_cmd.extend(["--style=" + style])
  551. clang_format_cmd.extend(
  552. [
  553. "--lines=%s:%s" % (start_line, start_line + line_count - 1)
  554. for start_line, line_count in line_ranges
  555. ]
  556. )
  557. if revision is not None:
  558. clang_format_cmd.extend(["--assume-filename=" + filename])
  559. git_show_cmd = [
  560. "git",
  561. "cat-file",
  562. "blob",
  563. "%s:%s" % (revision, filename),
  564. ]
  565. git_show = subprocess.Popen(
  566. git_show_cmd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE
  567. )
  568. git_show.stdin.close()
  569. clang_format_stdin = git_show.stdout
  570. else:
  571. clang_format_cmd.extend([filename])
  572. git_show = None
  573. clang_format_stdin = subprocess.PIPE
  574. try:
  575. clang_format = subprocess.Popen(
  576. clang_format_cmd, stdin=clang_format_stdin, stdout=subprocess.PIPE
  577. )
  578. if clang_format_stdin == subprocess.PIPE:
  579. clang_format_stdin = clang_format.stdin
  580. except OSError as e:
  581. if e.errno == errno.ENOENT:
  582. die('cannot find executable "%s"' % binary)
  583. else:
  584. raise
  585. clang_format_stdin.close()
  586. hash_object_cmd = [
  587. "git",
  588. "hash-object",
  589. "-w",
  590. "--path=" + filename,
  591. "--stdin",
  592. ]
  593. hash_object = subprocess.Popen(
  594. hash_object_cmd, stdin=clang_format.stdout, stdout=subprocess.PIPE
  595. )
  596. clang_format.stdout.close()
  597. stdout = hash_object.communicate()[0]
  598. if hash_object.returncode != 0:
  599. die("`%s` failed" % " ".join(hash_object_cmd))
  600. if clang_format.wait() != 0:
  601. die("`%s` failed" % " ".join(clang_format_cmd))
  602. if git_show and git_show.wait() != 0:
  603. die("`%s` failed" % " ".join(git_show_cmd))
  604. return convert_string(stdout).rstrip("\r\n")
  605. @contextlib.contextmanager
  606. def temporary_index_file(tree=None):
  607. """Context manager for setting GIT_INDEX_FILE to a temporary file and
  608. deleting the file afterward."""
  609. index_path = create_temporary_index(tree)
  610. old_index_path = os.environ.get("GIT_INDEX_FILE")
  611. os.environ["GIT_INDEX_FILE"] = index_path
  612. try:
  613. yield
  614. finally:
  615. if old_index_path is None:
  616. del os.environ["GIT_INDEX_FILE"]
  617. else:
  618. os.environ["GIT_INDEX_FILE"] = old_index_path
  619. os.remove(index_path)
  620. def create_temporary_index(tree=None):
  621. """Create a temporary index file and return the created file's path.
  622. If `tree` is not None, use that as the tree to read in. Otherwise, an
  623. empty index is created."""
  624. gitdir = run("git", "rev-parse", "--git-dir")
  625. path = os.path.join(gitdir, temp_index_basename)
  626. if tree is None:
  627. tree = "--empty"
  628. run("git", "read-tree", "--index-output=" + path, tree)
  629. return path
  630. def print_diff(old_tree, new_tree):
  631. """Print the diff between the two trees to stdout."""
  632. # We use the porcelain 'diff' and not plumbing 'diff-tree' because the
  633. # output is expected to be viewed by the user, and only the former does nice
  634. # things like color and pagination.
  635. #
  636. # We also only print modified files since `new_tree` only contains the files
  637. # that were modified, so unmodified files would show as deleted without the
  638. # filter.
  639. return subprocess.run(
  640. ["git", "diff", "--diff-filter=M", "--exit-code", old_tree, new_tree]
  641. ).returncode
  642. def print_diffstat(old_tree, new_tree):
  643. """Print the diffstat between the two trees to stdout."""
  644. # We use the porcelain 'diff' and not plumbing 'diff-tree' because the
  645. # output is expected to be viewed by the user, and only the former does nice
  646. # things like color and pagination.
  647. #
  648. # We also only print modified files since `new_tree` only contains the files
  649. # that were modified, so unmodified files would show as deleted without the
  650. # filter.
  651. return subprocess.run(
  652. [
  653. "git",
  654. "diff",
  655. "--diff-filter=M",
  656. "--exit-code",
  657. "--stat",
  658. old_tree,
  659. new_tree,
  660. ]
  661. ).returncode
  662. def apply_changes(old_tree, new_tree, force=False, patch_mode=False):
  663. """Apply the changes in `new_tree` to the working directory.
  664. Bails if there are local changes in those files and not `force`. If
  665. `patch_mode`, runs `git checkout --patch` to select hunks interactively."""
  666. changed_files = (
  667. run(
  668. "git",
  669. "diff-tree",
  670. "--diff-filter=M",
  671. "-r",
  672. "-z",
  673. "--name-only",
  674. old_tree,
  675. new_tree,
  676. )
  677. .rstrip("\0")
  678. .split("\0")
  679. )
  680. if not force:
  681. unstaged_files = run("git", "diff-files", "--name-status", *changed_files)
  682. if unstaged_files:
  683. print(
  684. "The following files would be modified but have unstaged changes:",
  685. file=sys.stderr,
  686. )
  687. print(unstaged_files, file=sys.stderr)
  688. print("Please commit, stage, or stash them first.", file=sys.stderr)
  689. sys.exit(2)
  690. if patch_mode:
  691. # In patch mode, we could just as well create an index from the new tree
  692. # and checkout from that, but then the user will be presented with a
  693. # message saying "Discard ... from worktree". Instead, we use the old
  694. # tree as the index and checkout from new_tree, which gives the slightly
  695. # better message, "Apply ... to index and worktree". This is not quite
  696. # right, since it won't be applied to the user's index, but oh well.
  697. with temporary_index_file(old_tree):
  698. subprocess.run(["git", "checkout", "--patch", new_tree], check=True)
  699. index_tree = old_tree
  700. else:
  701. with temporary_index_file(new_tree):
  702. run("git", "checkout-index", "-f", "--", *changed_files)
  703. return changed_files
  704. def run(*args, **kwargs):
  705. stdin = kwargs.pop("stdin", "")
  706. verbose = kwargs.pop("verbose", True)
  707. strip = kwargs.pop("strip", True)
  708. for name in kwargs:
  709. raise TypeError("run() got an unexpected keyword argument '%s'" % name)
  710. p = subprocess.Popen(
  711. args,
  712. stdout=subprocess.PIPE,
  713. stderr=subprocess.PIPE,
  714. stdin=subprocess.PIPE,
  715. )
  716. stdout, stderr = p.communicate(input=stdin)
  717. stdout = convert_string(stdout)
  718. stderr = convert_string(stderr)
  719. if p.returncode == 0:
  720. if stderr:
  721. if verbose:
  722. print("`%s` printed to stderr:" % " ".join(args), file=sys.stderr)
  723. print(stderr.rstrip(), file=sys.stderr)
  724. if strip:
  725. stdout = stdout.rstrip("\r\n")
  726. return stdout
  727. if verbose:
  728. print("`%s` returned %s" % (" ".join(args), p.returncode), file=sys.stderr)
  729. if stderr:
  730. print(stderr.rstrip(), file=sys.stderr)
  731. sys.exit(2)
  732. def die(message):
  733. print("error:", message, file=sys.stderr)
  734. sys.exit(2)
  735. def to_bytes(str_input):
  736. # Encode to UTF-8 to get binary data.
  737. if isinstance(str_input, bytes):
  738. return str_input
  739. return str_input.encode("utf-8")
  740. def to_string(bytes_input):
  741. if isinstance(bytes_input, str):
  742. return bytes_input
  743. return bytes_input.encode("utf-8")
  744. def convert_string(bytes_input):
  745. try:
  746. return to_string(bytes_input.decode("utf-8"))
  747. except AttributeError: # 'str' object has no attribute 'decode'.
  748. return str(bytes_input)
  749. except UnicodeError:
  750. return str(bytes_input)
  751. if __name__ == "__main__":
  752. sys.exit(main())