|
28 | 28 | because -noformat_file was set.
|
29 | 29 | 2: The application wasn't configured properly and could not execute.
|
30 | 30 | """
|
| 31 | +import difflib |
31 | 32 | import io
|
32 | 33 | import os
|
33 | 34 | import subprocess
|
|
58 | 59 | """
|
59 | 60 |
|
60 | 61 | # 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 | + |
61 | 86 | def does_file_need_formatting(filename):
|
62 | 87 | """Executes clang-format on the file to determine if it includes any
|
63 | 88 | formatting changes the user needs to fix.
|
@@ -246,6 +271,10 @@ def main(argv):
|
246 | 271 | count += 1
|
247 | 272 | if FLAGS.verbose:
|
248 | 273 | 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)) |
249 | 278 | if FLAGS.verbose:
|
250 | 279 | print(' > Done. {0} file(s) need formatting.'.format(count))
|
251 | 280 | else:
|
|
0 commit comments