Debian Codegraph @

scripts/developer/git/git-clang-format

raw symbols SCIP
1 #!/usr/bin/env python
2
3 # SPDX-FileCopyrightText: 2026 Oak Ridge National Laboratory and Contributors
4 #
5 # SPDX-License-Identifier: Apache-2.0
6
7 #
8 #===- git-clang-format - ClangFormat Git Integration ---------*- python -*--===#
9 #
10 # The LLVM Compiler Infrastructure
11 #
12 # This file is distributed under the University of Illinois Open Source
13 # License. See LICENSE.TXT for details.
14 #
15 #===------------------------------------------------------------------------===#
16
17 r"""
18 clang-format git integration
19 ============================
20
21 This file provides a clang-format integration for git. Put it somewhere in your
22 path and ensure that it is executable. Then, "git clang-format" will invoke
23 clang-format on the changes in current files or a specific commit.
24
25 For further details, run:
26 git clang-format -h
27
28 Requires Python 2.7
29 """
30
31 import argparse
32 import collections
33 import contextlib
34 import errno
35 import os
36 import re
37 import subprocess
38 import sys
39
40 usage = 'git clang-format [OPTIONS] [<commit>] [<commit>] [--] [<file>...]'
41
42 desc = '''
43 If zero or one commits are given, run clang-format on all lines that differ
44 between the working directory and <commit>, which defaults to HEAD. Changes are
45 only applied to the working directory.
46
47 If two commits are given (requires --diff), run clang-format on all lines in the
48 second <commit> that differ from the first <commit>.
49
50 The following git-config settings set the default of the corresponding option:
51 clangFormat.binary
52 clangFormat.commit
53 clangFormat.extension
54 clangFormat.style
55 '''
56
57 # Name of the temporary index file in which save the output of clang-format.
58 # This file is created within the .git directory.
59 temp_index_basename = 'clang-format-index'
60
61
62 Range = collections.namedtuple('Range', 'start, count')
63
64
65 def main():
66 config = load_git_config()
67
68 # In order to keep '--' yet allow options after positionals, we need to
69 # check for '--' ourselves. (Setting nargs='*' throws away the '--', while
70 # nargs=argparse.REMAINDER disallows options after positionals.)
71 argv = sys.argv[1:]
72 try:
73 idx = argv.index('--')
74 except ValueError:
75 dash_dash = []
76 else:
77 dash_dash = argv[idx:]
78 argv = argv[:idx]
79
80 default_extensions = ','.join([
81 # From clang/lib/Frontend/FrontendOptions.cpp, all lower case
82 'c', 'h', # C
83 'm', # ObjC
84 'mm', # ObjC++
85 'cc', 'cp', 'cpp', 'c++', 'cxx', 'hpp', 'tcc', 'inl' # C++
86 # Other languages that clang-format supports
87 'proto', 'protodevel', # Protocol Buffers
88 'java', # Java
89 'js', # JavaScript
90 'ts', # TypeScript
91 ])
92
93 p = argparse.ArgumentParser(
94 usage=usage, formatter_class=argparse.RawDescriptionHelpFormatter,
95 description=desc)
96 p.add_argument('--binary',
97 default=config.get('clangformat.binary', 'clang-format'),
98 help='path to clang-format'),
99 p.add_argument('--commit',
100 default=config.get('clangformat.commit', 'HEAD'),
101 help='default commit to use if none is specified'),
102 p.add_argument('--diff', action='store_true',
103 help='print a diff instead of applying the changes')
104 p.add_argument('--extensions',
105 default=config.get('clangformat.extensions',
106 default_extensions),
107 help=('comma-separated list of file extensions to format, '
108 'excluding the period and case-insensitive')),
109 p.add_argument('-f', '--force', action='store_true',
110 help='allow changes to unstaged files')
111 p.add_argument('-p', '--patch', action='store_true',
112 help='select hunks interactively')
113 p.add_argument('-q', '--quiet', action='count', default=0,
114 help='print less information')
115 p.add_argument('--style',
116 default=config.get('clangformat.style', None),
117 help='passed to clang-format'),
118 p.add_argument('-v', '--verbose', action='count', default=0,
119 help='print extra information')
120 p.add_argument('-x', '--exclude',
121 help='Regex to match for files to exclude from checking')
122 # We gather all the remaining positional arguments into 'args' since we need
123 # to use some heuristics to determine whether or not <commit> was present.
124 # However, to print pretty messages, we make use of metavar and help.
125 p.add_argument('args', nargs='*', metavar='<commit>',
126 help='revision from which to compute the diff')
127 p.add_argument('ignored', nargs='*', metavar='<file>...',
128 help='if specified, only consider differences in these files')
129 opts = p.parse_args(argv)
130
131 opts.verbose -= opts.quiet
132 del opts.quiet
133
134 commits, files = interpret_args(opts.args, dash_dash, opts.commit)
135 if len(commits) > 1:
136 if not opts.diff:
137 die('--diff is required when two commits are given')
138 else:
139 if len(commits) > 2:
140 die('at most two commits allowed; %d given' % len(commits))
141 changed_lines = compute_diff_and_extract_lines(commits, files)
142 if opts.verbose >= 1:
143 ignored_files = set(changed_lines)
144 filter_by_exclude(changed_lines, opts.exclude)
145 filter_by_extension(changed_lines, opts.extensions.lower().split(','))
146 if opts.verbose >= 1:
147 ignored_files.difference_update(changed_lines)
148 if ignored_files:
149 print 'Ignoring changes in the following files (wrong extension):'
150 for filename in ignored_files:
151 print ' ', filename
152 if changed_lines:
153 print 'Running clang-format on the following files:'
154 for filename in changed_lines:
155 print ' ', filename
156 if not changed_lines:
157 print 'no modified files to format'
158 return
159 # The computed diff outputs absolute paths, so we must cd before accessing
160 # those files.
161 cd_to_toplevel()
162 if len(commits) > 1:
163 old_tree = commits[1]
164 new_tree = run_clang_format_and_save_to_tree(changed_lines,
165 revision=commits[1],
166 binary=opts.binary,
167 style=opts.style)
168 else:
169 old_tree = create_tree_from_workdir(changed_lines)
170 new_tree = run_clang_format_and_save_to_tree(changed_lines,
171 binary=opts.binary,
172 style=opts.style)
173 if opts.verbose >= 1:
174 print 'old tree:', old_tree
175 print 'new tree:', new_tree
176 if old_tree == new_tree:
177 if opts.verbose >= 0:
178 print 'clang-format did not modify any files'
179 elif opts.diff:
180 print_diff(old_tree, new_tree)
181 else:
182 changed_files = apply_changes(old_tree, new_tree, force=opts.force,
183 patch_mode=opts.patch)
184 if (opts.verbose >= 0 and not opts.patch) or opts.verbose >= 1:
185 print 'changed files:'
186 for filename in changed_files:
187 print ' ', filename
188
189
190 def load_git_config(non_string_options=None):
191 """Return the git configuration as a dictionary.
192
193 All options are assumed to be strings unless in `non_string_options`, in which
194 is a dictionary mapping option name (in lower case) to either "--bool" or
195 "--int"."""
196 if non_string_options is None:
197 non_string_options = {}
198 out = {}
199 for entry in run('git', 'config', '--list', '--null').split('\0'):
200 if entry:
201 name, value = entry.split('\n', 1)
202 if name in non_string_options:
203 value = run('git', 'config', non_string_options[name], name)
204 out[name] = value
205 return out
206
207
208 def interpret_args(args, dash_dash, default_commit):
209 """Interpret `args` as "[commits] [--] [files]" and return (commits, files).
210
211 It is assumed that "--" and everything that follows has been removed from
212 args and placed in `dash_dash`.
213
214 If "--" is present (i.e., `dash_dash` is non-empty), the arguments to its
215 left (if present) are taken as commits. Otherwise, the arguments are checked
216 from left to right if they are commits or files. If commits are not given,
217 a list with `default_commit` is used."""
218 if dash_dash:
219 if len(args) == 0:
220 commits = [default_commit]
221 else:
222 commits = args
223 for commit in commits:
224 object_type = get_object_type(commit)
225 if object_type not in ('commit', 'tag'):
226 if object_type is None:
227 die("'%s' is not a commit" % commit)
228 else:
229 die("'%s' is a %s, but a commit was expected" % (commit, object_type))
230 files = dash_dash[1:]
231 elif args:
232 commits = []
233 while args:
234 if not disambiguate_revision(args[0]):
235 break
236 commits.append(args.pop(0))
237 if not commits:
238 commits = [default_commit]
239 files = args
240 else:
241 commits = [default_commit]
242 files = []
243 return commits, files
244
245
246 def disambiguate_revision(value):
247 """Returns True if `value` is a revision, False if it is a file, or dies."""
248 # If `value` is ambiguous (neither a commit nor a file), the following
249 # command will die with an appropriate error message.
250 run('git', 'rev-parse', value, verbose=False)
251 object_type = get_object_type(value)
252 if object_type is None:
253 return False
254 if object_type in ('commit', 'tag'):
255 return True
256 die('`%s` is a %s, but a commit or filename was expected' %
257 (value, object_type))
258
259
260 def get_object_type(value):
261 """Returns a string description of an object's type, or None if it is not
262 a valid git object."""
263 cmd = ['git', 'cat-file', '-t', value]
264 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
265 stdout, stderr = p.communicate()
266 if p.returncode != 0:
267 return None
268 return stdout.strip()
269
270
271 def compute_diff_and_extract_lines(commits, files):
272 """Calls compute_diff() followed by extract_lines()."""
273 diff_process = compute_diff(commits, files)
274 changed_lines = extract_lines(diff_process.stdout)
275 diff_process.stdout.close()
276 diff_process.wait()
277 if diff_process.returncode != 0:
278 # Assume error was already printed to stderr.
279 sys.exit(2)
280 return changed_lines
281
282
283 def compute_diff(commits, files):
284 """Return a subprocess object producing the diff from `commits`.
285
286 The return value's `stdin` file object will produce a patch with the
287 differences between the working directory and the first commit if a single
288 one was specified, or the difference between both specified commits, filtered
289 on `files` (if non-empty). Zero context lines are used in the patch."""
290 git_tool = 'diff-index'
291 if len(commits) > 1:
292 git_tool = 'diff-tree'
293 cmd = ['git', git_tool, '-p', '-U0'] + commits + ['--']
294 cmd.extend(files)
295 p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
296 p.stdin.close()
297 return p
298
299
300 def extract_lines(patch_file):
301 """Extract the changed lines in `patch_file`.
302
303 The return value is a dictionary mapping filename to a list of (start_line,
304 line_count) pairs.
305
306 The input must have been produced with ``-U0``, meaning unidiff format with
307 zero lines of context. The return value is a dict mapping filename to a
308 list of line `Range`s."""
309 matches = {}
310 for line in patch_file:
311 match = re.search(r'^\+\+\+\ [^/]+/(.*)', line)
312 if match:
313 filename = match.group(1).rstrip('\r\n')
314 match = re.search(r'^@@ -[0-9,]+ \+(\d+)(,(\d+))?', line)
315 if match:
316 start_line = int(match.group(1))
317 line_count = 1
318 if match.group(3):
319 line_count = int(match.group(3))
320 if line_count > 0:
321 matches.setdefault(filename, []).append(Range(start_line, line_count))
322 return matches
323
324
325 def filter_by_exclude(dictionary, exclude_re):
326 """Delete every key in `dictionary` that matches the exclusion regex.
327
328 `exclude_re` must be a valid regex."""
329 exre = re.compile(exclude_re)
330 for filename in dictionary.keys():
331 if exre.match(filename):
332 del dictionary[filename]
333
334
335 def filter_by_extension(dictionary, allowed_extensions):
336 """Delete every key in `dictionary` that doesn't have an allowed extension.
337
338 `allowed_extensions` must be a collection of lowercase file extensions,
339 excluding the period."""
340 allowed_extensions = frozenset(allowed_extensions)
341 for filename in dictionary.keys():
342 base_ext = filename.rsplit('.', 1)
343 if len(base_ext) == 1 or base_ext[1].lower() not in allowed_extensions:
344 del dictionary[filename]
345
346
347 def cd_to_toplevel():
348 """Change to the top level of the git repository."""
349 toplevel = run('git', 'rev-parse', '--show-toplevel')
350 os.chdir(toplevel)
351
352
353 def create_tree_from_workdir(filenames):
354 """Create a new git tree with the given files from the working directory.
355
356 Returns the object ID (SHA-1) of the created tree."""
357 return create_tree(filenames, '--stdin')
358
359
360 def run_clang_format_and_save_to_tree(changed_lines, revision=None,
361 binary='clang-format', style=None):
362 """Run clang-format on each file and save the result to a git tree.
363
364 Returns the object ID (SHA-1) of the created tree."""
365 def index_info_generator():
366 for filename, line_ranges in changed_lines.iteritems():
367 if revision:
368 git_metadata_cmd = ['git', 'ls-tree',
369 '%s:%s' % (revision, os.path.dirname(filename)),
370 os.path.basename(filename)]
371 git_metadata = subprocess.Popen(git_metadata_cmd, stdin=subprocess.PIPE,
372 stdout=subprocess.PIPE)
373 stdout = git_metadata.communicate()[0]
374 mode = oct(int(stdout.split()[0], 8))
375 else:
376 mode = oct(os.stat(filename).st_mode)
377 blob_id = clang_format_to_blob(filename, line_ranges,
378 revision=revision,
379 binary=binary,
380 style=style)
381 yield '%s %s\t%s' % (mode, blob_id, filename)
382 return create_tree(index_info_generator(), '--index-info')
383
384
385 def create_tree(input_lines, mode):
386 """Create a tree object from the given input.
387
388 If mode is '--stdin', it must be a list of filenames. If mode is
389 '--index-info' is must be a list of values suitable for "git update-index
390 --index-info", such as "<mode> <SP> <sha1> <TAB> <filename>". Any other mode
391 is invalid."""
392 assert mode in ('--stdin', '--index-info')
393 cmd = ['git', 'update-index', '--add', '-z', mode]
394 with temporary_index_file():
395 p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
396 for line in input_lines:
397 p.stdin.write('%s\0' % line)
398 p.stdin.close()
399 if p.wait() != 0:
400 die('`%s` failed' % ' '.join(cmd))
401 tree_id = run('git', 'write-tree')
402 return tree_id
403
404
405 def clang_format_to_blob(filename, line_ranges, revision=None,
406 binary='clang-format', style=None):
407 """Run clang-format on the given file and save the result to a git blob.
408
409 Runs on the file in `revision` if not None, or on the file in the working
410 directory if `revision` is None.
411
412 Returns the object ID (SHA-1) of the created blob."""
413 clang_format_cmd = [binary]
414 if style:
415 clang_format_cmd.extend(['-style='+style])
416 clang_format_cmd.extend([
417 '-lines=%s:%s' % (start_line, start_line+line_count-1)
418 for start_line, line_count in line_ranges])
419 if revision:
420 clang_format_cmd.extend(['-assume-filename='+filename])
421 git_show_cmd = ['git', 'cat-file', 'blob', '%s:%s' % (revision, filename)]
422 git_show = subprocess.Popen(git_show_cmd, stdin=subprocess.PIPE,
423 stdout=subprocess.PIPE)
424 git_show.stdin.close()
425 clang_format_stdin = git_show.stdout
426 else:
427 clang_format_cmd.extend([filename])
428 git_show = None
429 clang_format_stdin = subprocess.PIPE
430 try:
431 clang_format = subprocess.Popen(clang_format_cmd, stdin=clang_format_stdin,
432 stdout=subprocess.PIPE)
433 if clang_format_stdin == subprocess.PIPE:
434 clang_format_stdin = clang_format.stdin
435 except OSError as e:
436 if e.errno == errno.ENOENT:
437 die('cannot find executable "%s"' % binary)
438 else:
439 raise
440 clang_format_stdin.close()
441 hash_object_cmd = ['git', 'hash-object', '-w', '--path='+filename, '--stdin']
442 hash_object = subprocess.Popen(hash_object_cmd, stdin=clang_format.stdout,
443 stdout=subprocess.PIPE)
444 clang_format.stdout.close()
445 stdout = hash_object.communicate()[0]
446 if hash_object.returncode != 0:
447 die('`%s` failed' % ' '.join(hash_object_cmd))
448 if clang_format.wait() != 0:
449 die('`%s` failed' % ' '.join(clang_format_cmd))
450 if git_show and git_show.wait() != 0:
451 die('`%s` failed' % ' '.join(git_show_cmd))
452 return stdout.rstrip('\r\n')
453
454
455 @contextlib.contextmanager
456 def temporary_index_file(tree=None):
457 """Context manager for setting GIT_INDEX_FILE to a temporary file and deleting
458 the file afterward."""
459 index_path = create_temporary_index(tree)
460 old_index_path = os.environ.get('GIT_INDEX_FILE')
461 os.environ['GIT_INDEX_FILE'] = index_path
462 try:
463 yield
464 finally:
465 if old_index_path is None:
466 del os.environ['GIT_INDEX_FILE']
467 else:
468 os.environ['GIT_INDEX_FILE'] = old_index_path
469 os.remove(index_path)
470
471
472 def create_temporary_index(tree=None):
473 """Create a temporary index file and return the created file's path.
474
475 If `tree` is not None, use that as the tree to read in. Otherwise, an
476 empty index is created."""
477 gitdir = run('git', 'rev-parse', '--git-dir')
478 path = os.path.join(gitdir, temp_index_basename)
479 if tree is None:
480 tree = '--empty'
481 run('git', 'read-tree', '--index-output='+path, tree)
482 return path
483
484
485 def print_diff(old_tree, new_tree):
486 """Print the diff between the two trees to stdout."""
487 # We use the porcelain 'diff' and not plumbing 'diff-tree' because the output
488 # is expected to be viewed by the user, and only the former does nice things
489 # like color and pagination.
490 #
491 # We also only print modified files since `new_tree` only contains the files
492 # that were modified, so unmodified files would show as deleted without the
493 # filter.
494 subprocess.check_call(['git', 'diff', '--diff-filter=M', old_tree, new_tree,
495 '--'])
496
497
498 def apply_changes(old_tree, new_tree, force=False, patch_mode=False):
499 """Apply the changes in `new_tree` to the working directory.
500
501 Bails if there are local changes in those files and not `force`. If
502 `patch_mode`, runs `git checkout --patch` to select hunks interactively."""
503 changed_files = run('git', 'diff-tree', '--diff-filter=M', '-r', '-z',
504 '--name-only', old_tree,
505 new_tree).rstrip('\0').split('\0')
506 if not force:
507 unstaged_files = run('git', 'diff-files', '--name-status', *changed_files)
508 if unstaged_files:
509 print >>sys.stderr, ('The following files would be modified but '
510 'have unstaged changes:')
511 print >>sys.stderr, unstaged_files
512 print >>sys.stderr, 'Please commit, stage, or stash them first.'
513 sys.exit(2)
514 if patch_mode:
515 # In patch mode, we could just as well create an index from the new tree
516 # and checkout from that, but then the user will be presented with a
517 # message saying "Discard ... from worktree". Instead, we use the old
518 # tree as the index and checkout from new_tree, which gives the slightly
519 # better message, "Apply ... to index and worktree". This is not quite
520 # right, since it won't be applied to the user's index, but oh well.
521 with temporary_index_file(old_tree):
522 subprocess.check_call(['git', 'checkout', '--patch', new_tree])
523 index_tree = old_tree
524 else:
525 with temporary_index_file(new_tree):
526 run('git', 'checkout-index', '-a', '-f')
527 return changed_files
528
529
530 def run(*args, **kwargs):
531 stdin = kwargs.pop('stdin', '')
532 verbose = kwargs.pop('verbose', True)
533 strip = kwargs.pop('strip', True)
534 for name in kwargs:
535 raise TypeError("run() got an unexpected keyword argument '%s'" % name)
536 p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
537 stdin=subprocess.PIPE)
538 stdout, stderr = p.communicate(input=stdin)
539 if p.returncode == 0:
540 if stderr:
541 if verbose:
542 print >>sys.stderr, '`%s` printed to stderr:' % ' '.join(args)
543 print >>sys.stderr, stderr.rstrip()
544 if strip:
545 stdout = stdout.rstrip('\r\n')
546 return stdout
547 if verbose:
548 print >>sys.stderr, '`%s` returned %s' % (' '.join(args), p.returncode)
549 if stderr:
550 print >>sys.stderr, stderr.rstrip()
551 sys.exit(2)
552
553
554 def die(message):
555 print >>sys.stderr, 'error:', message
556 sys.exit(2)
557
558
559 if __name__ == '__main__':
560 main()