Skip to content

Commit 46c31ce

Browse files
authored
format_code.py changed to print the diff when not formatting files inline (#462)
1 parent 0d36667 commit 46c31ce

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

scripts/format_code.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
because -noformat_file was set.
2929
2: The application wasn't configured properly and could not execute.
3030
"""
31+
import difflib
3132
import io
3233
import os
3334
import subprocess
@@ -58,6 +59,30 @@
5859
"""
5960

6061
# Functions:
62+
def get_formatting_diff_lines(filename):
63+
"""Calculates and returns a printable diff of the formatting changes that
64+
would be applied to the given file by clang-format.
65+
66+
Args:
67+
filename (string): path to the file whose formatting diff to calculate.
68+
69+
Returns:
70+
Iterable[str]: The diff of the formatted file against the original file;
71+
each string in the returned iterable is a "line" of the diff; they could
72+
be printed individually or joined into a single string using something
73+
like os.linesep.join(diff_lines), where `diff_lines` is the return value.
74+
"""
75+
args = ['clang-format', '-style=file', filename]
76+
result = subprocess.run(args, stdout=subprocess.PIPE, check=True)
77+
78+
formatted_lines = [line.rstrip('\r\n')
79+
for line in result.stdout.decode('utf8', errors='replace').splitlines()]
80+
with open(filename, 'rt', encoding='utf8', errors='replace') as f:
81+
original_lines = [line.rstrip('\r\n') for line in f]
82+
83+
return [line.rstrip()
84+
for line in difflib.unified_diff(original_lines, formatted_lines)]
85+
6186
def does_file_need_formatting(filename):
6287
"""Executes clang-format on the file to determine if it includes any
6388
formatting changes the user needs to fix.
@@ -246,6 +271,10 @@ def main(argv):
246271
count += 1
247272
if FLAGS.verbose:
248273
print(' - Requires reformatting: "{0}"'.format(filename))
274+
print('------ BEGIN FORMATTING DIFF OF {0}'.format(filename))
275+
for diff_line in get_formatting_diff_lines(filename):
276+
print(diff_line)
277+
print('------ END FORMATTING DIFF OF {0}'.format(filename))
249278
if FLAGS.verbose:
250279
print(' > Done. {0} file(s) need formatting.'.format(count))
251280
else:

0 commit comments

Comments
 (0)