Skip to content

Commit 37c478b

Browse files
committed
[google-java-format-diff] Add mode that verifies a diff is formated
This change adds a flag to google-java-format-diff.py to verify that a diff is formatted instread of reformating the files. Useful to enforce a styleguide as part of presubmit checks.
1 parent 1614b6a commit 37c478b

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

scripts/google-java-format-diff.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,15 @@ def main():
6262
parser.add_argument('-b', '--binary', help='path to google-java-format binary')
6363
parser.add_argument('--google-java-format-jar', metavar='ABSOLUTE_PATH', default=None,
6464
help='use a custom google-java-format jar')
65+
parser.add_argument('--verify', action='store_true',
66+
help="Only verify that the diff is formated and skip reformatting")
6567

6668
args = parser.parse_args()
6769

70+
if args.i and args.verify:
71+
sys.stderr.write("Cannot use -i and --verify simultaneously")
72+
sys.exit(-1)
73+
6874
# Extract changed lines for each file.
6975
filename = None
7076
lines_by_file = {}
@@ -116,15 +122,23 @@ def main():
116122
command.append('--skip-sorting-imports')
117123
if args.skip_removing_unused_imports:
118124
command.append('--skip-removing-unused-imports')
125+
if args.verify:
126+
command.append("--dry-run")
127+
command.append("--set-exit-if-changed")
119128
command.extend(lines)
120129
command.append(filename)
121130
p = subprocess.Popen(command, stdout=subprocess.PIPE,
122131
stderr=None, stdin=subprocess.PIPE)
123132
stdout, stderr = p.communicate()
124133
if p.returncode != 0:
125-
sys.exit(p.returncode);
134+
if args.verify:
135+
sys.stderr.write(
136+
"The following file is not formated: " + filename + "\n")
137+
continue
138+
else:
139+
sys.exit(p.returncode)
126140

127-
if not args.i:
141+
if not args.i and not args.verify:
128142
with open(filename) as f:
129143
code = f.readlines()
130144
formatted_code = StringIO.StringIO(stdout).readlines()

0 commit comments

Comments
 (0)