From ee1804890a22cee42a90e24432f5a63efc3d7d8a Mon Sep 17 00:00:00 2001 From: Christian Stein Date: Wed, 14 Dec 2016 16:12:44 +0100 Subject: [PATCH 1/2] Add `--dry-run` and `--set-exit-if-changed` option to CLI `--dry-run` or `-n` Prints the paths of the files whose contents would change if the formatter were run normally. `--set-exit-if-changed` Return exit code 1 if there are any formatting changes. --- .../java/CommandLineOptions.java | 39 ++++++++++++- .../java/CommandLineOptionsParser.java | 7 +++ .../google/googlejavaformat/java/Main.java | 43 +++++++++++---- .../googlejavaformat/java/UsageException.java | 4 ++ .../java/CommandLineFlagsTest.java | 21 ++++++- .../googlejavaformat/java/MainTest.java | 55 +++++++++++++++++++ 6 files changed, 152 insertions(+), 17 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java index 47a6cfd21..f636bc7ad 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java @@ -38,6 +38,8 @@ final class CommandLineOptions { private final boolean removeJavadocOnlyImports; private final boolean sortImports; private final boolean removeUnusedImports; + private final boolean dryRun; + private final boolean setExitIfChanged; CommandLineOptions( ImmutableList files, @@ -52,7 +54,9 @@ final class CommandLineOptions { boolean fixImportsOnly, boolean removeJavadocOnlyImports, boolean sortImports, - boolean removeUnusedImports) { + boolean removeUnusedImports, + boolean dryRun, + boolean setExitIfChanged) { this.files = files; this.inPlace = inPlace; this.lines = lines; @@ -66,6 +70,8 @@ final class CommandLineOptions { this.removeJavadocOnlyImports = removeJavadocOnlyImports; this.sortImports = sortImports; this.removeUnusedImports = removeUnusedImports; + this.dryRun = dryRun; + this.setExitIfChanged = setExitIfChanged; } /** The files to format. */ @@ -141,6 +147,21 @@ boolean isSelection() { return !lines().isEmpty() || !offsets().isEmpty() || !lengths().isEmpty(); } + /** Returns true if dry-run mode was selected. */ + boolean isDryRun() { + return dryRun; + } + + /** Returns true if exit code 1 should be set if formatting was done or is required. */ + boolean isSetExitIfChanged() { + return setExitIfChanged; + } + + /** Returns true if no special run-mode (like in-place or dry-run) is selected. */ + boolean stdout() { + return !(inPlace || dryRun); // note: add new special run modes here + } + static Builder builder() { return new Builder(); } @@ -160,6 +181,8 @@ static class Builder { private Boolean removeJavadocOnlyImports = false; private Boolean sortImports = true; private Boolean removeUnusedImports = true; + private Boolean dryRun = false; + private Boolean setExitIfChanged = false; ImmutableList.Builder filesBuilder() { return files; @@ -224,6 +247,16 @@ Builder removeUnusedImports(boolean removeUnusedImports) { return this; } + Builder dryRun(boolean dryRun) { + this.dryRun = dryRun; + return this; + } + + Builder setExitIfChanged(boolean setExitIfChanged) { + this.setExitIfChanged = setExitIfChanged; + return this; + } + CommandLineOptions build() { return new CommandLineOptions( this.files.build(), @@ -238,7 +271,9 @@ CommandLineOptions build() { this.fixImportsOnly, this.removeJavadocOnlyImports, this.sortImports, - this.removeUnusedImports); + this.removeUnusedImports, + this.dryRun, + this.setExitIfChanged); } } } diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java index b12e2bfd2..593f9880b 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java @@ -54,6 +54,13 @@ static CommandLineOptions parse(Iterable options) { case "--replace": optionsBuilder.inPlace(true); break; + case "-n": + case "--dry-run": + optionsBuilder.dryRun(true); + break; + case "--set-exit-if-changed": + optionsBuilder.setExitIfChanged(true); + break; case "--lines": case "-lines": case "--line": diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index 7164d96bb..c31f52e54 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -133,6 +133,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti boolean allOk = true; for (Map.Entry> result : results.entrySet()) { String formatted; + Path path = result.getKey(); try { formatted = result.getValue().get(); } catch (InterruptedException e) { @@ -142,28 +143,36 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti } catch (ExecutionException e) { if (e.getCause() instanceof FormatterException) { for (FormatterDiagnostic diagnostic : ((FormatterException) e.getCause()).diagnostics()) { - errWriter.println(result.getKey() + ":" + diagnostic.toString()); + errWriter.println(path + ":" + diagnostic.toString()); } } else { - errWriter.println(result.getKey() + ": error: " + e.getCause().getMessage()); + errWriter.println(path + ": error: " + e.getCause().getMessage()); e.getCause().printStackTrace(errWriter); } allOk = false; continue; } + if (parameters.stdout()) { + outWriter.write(formatted); + } + boolean changed = !formatted.equals(inputs.get(path)); + if (!changed) { + continue; // preserve original file + } + if (parameters.isSetExitIfChanged()) { + allOk = false; + } + if (parameters.isDryRun()) { + outWriter.println(path); + continue; + } if (parameters.inPlace()) { - if (formatted.equals(inputs.get(result.getKey()))) { - continue; // preserve original file - } try { - Files.write(result.getKey(), formatted.getBytes(UTF_8)); + Files.write(path, formatted.getBytes(UTF_8)); } catch (IOException e) { - errWriter.println(result.getKey() + ": could not write file: " + e.getMessage()); + errWriter.println(path + ": could not write file: " + e.getMessage()); allOk = false; - continue; } - } else { - outWriter.write(formatted); } } return allOk ? 0 : 1; @@ -178,8 +187,15 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti } try { String output = new FormatFileCallable(parameters, input, options).call(); - outWriter.write(output); - return 0; + if (parameters.isDryRun()) { + outWriter.println(STDIN_FILENAME); + } else { + outWriter.write(output); + } + if (input.equals(output)) { + return 0; + } + return parameters.isSetExitIfChanged() ? 1 : 0; } catch (FormatterException e) { for (FormatterDiagnostic diagnostic : e.diagnostics()) { errWriter.println(STDIN_FILENAME + ":" + diagnostic.toString()); @@ -208,6 +224,9 @@ public static CommandLineOptions processArgs(String... args) throws UsageExcepti if (parameters.inPlace() && parameters.files().isEmpty()) { throw new UsageException("in-place formatting was requested but no files were provided"); } + if (parameters.inPlace() && parameters.isDryRun()) { + throw new UsageException("in-place formatting and dry-run can't be used at the same time"); + } if (parameters.isSelection() && filesToFormat != 1) { throw new UsageException("partial formatting is only support for a single file"); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java index 6a2999133..a78fad817 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java @@ -52,6 +52,10 @@ public final class UsageException extends Exception { " Character offset to format (0-based; default is all).", " --help, -help, -h", " Print this usage statement", + " --dry-run, -n", + " Prints the paths of the files whose contents would change if the formatter were run normally.", + " --set-exit-if-changed", + " Return exit code 1 if there are any formatting changes.", " --version, -version, -v", " Print the version.", "", diff --git a/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java b/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java index 7967f7299..9bfe2b1b1 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/CommandLineFlagsTest.java @@ -20,9 +20,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -/** - * Tests for command-line flags. - */ +/** Tests for command-line flags. */ @RunWith(JUnit4.class) public class CommandLineFlagsTest { @@ -148,4 +146,21 @@ public void noFilesToFormatRequiresEitherHelpOrVersion() { // expected } } + + @Test + public void formatInPlaceAndDryRunTogetherIsNotAllowed() { + try { + Main.processArgs("-i", "-n"); + fail(); + } catch (UsageException e) { + // expected + } + + try { + Main.processArgs("--replace", "--dry-run"); + fail(); + } catch (UsageException e) { + // expected + } + } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java index db47babfe..7a3088951 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java @@ -29,7 +29,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; +import java.util.ArrayList; import java.util.EnumSet; +import java.util.List; import java.util.Locale; import org.junit.Rule; import org.junit.Test; @@ -285,4 +287,57 @@ public void packageInfo() throws Exception { assertThat(main.format("-")).isEqualTo(0); assertThat(out.toString()).isEqualTo(joiner.join(input)); } + + @Test + public void dryRun() throws Exception { + StringWriter out = new StringWriter(); + StringWriter err = new StringWriter(); + Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); + + int errorCodeOk = main.format("-n", tempJava("Simple", "enum Simple {}\n")); + assertThat(errorCodeOk).named("Error Code").isEqualTo(0); + assertThat(out.toString()).isEmpty(); + assertThat(err.toString()).isEmpty(); + } + + @Test + public void dryRunNeedsFormattingExit0() throws Exception { + StringWriter out = new StringWriter(); + StringWriter err = new StringWriter(); + Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); + + int errorCode = dryRun(main, false); + assertThat(errorCode).named("Error Code").isEqualTo(0); + assertThat(out.toString()).contains("NeedsFormatting.java"); + assertThat(err.toString()).isEmpty(); + } + + @Test + public void dryRunNeedsFormattingExit1() throws Exception { + StringWriter out = new StringWriter(); + StringWriter err = new StringWriter(); + Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); + + int errorCode = dryRun(main, true); + assertThat(errorCode).named("Error Code").isEqualTo(1); + assertThat(out.toString()).contains("NeedsFormatting.java"); + assertThat(err.toString()).isEmpty(); + } + + private int dryRun(Main main, boolean setExitIfChanged) throws Exception { + List args = new ArrayList<>(); + args.add("--dry-run"); + if (setExitIfChanged) { + args.add("--set-exit-if-changed"); + } + args.add(tempJava("IsFormatted", "interface IsFormatted {}\n")); + args.add(tempJava("NeedsFormatting", " class NeedsFormatting { }\n")); + return main.format(args.toArray(new String[args.size()])); + } + + private String tempJava(String name, String code) throws Exception { + Path path = testFolder.newFile(name + ".java").toPath(); + Files.write(path, code.getBytes(UTF_8)); + return path.toAbsolutePath().toString(); + } } From b14d8da4d0d5b90aa533c772a480056091f3ce81 Mon Sep 17 00:00:00 2001 From: Christian Stein Date: Wed, 11 Oct 2017 13:01:49 +0200 Subject: [PATCH 2/2] Cleanup --- .../google/googlejavaformat/java/Main.java | 19 ++++++++----- .../googlejavaformat/java/FormatterTest.java | 28 +++++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index c31f52e54..1423add05 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -152,13 +152,15 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti allOk = false; continue; } + // in default mode always print formatted text to stdout, regardless of whether the input was formatted if (parameters.stdout()) { outWriter.write(formatted); } - boolean changed = !formatted.equals(inputs.get(path)); - if (!changed) { - continue; // preserve original file + // check for any change. if the file was already formatted, continue with the next entry + if (formatted.equals(inputs.get(path))) { + continue; } + // something changed! handle according to the selected run mode and other parameters if (parameters.isSetExitIfChanged()) { allOk = false; } @@ -187,15 +189,18 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti } try { String output = new FormatFileCallable(parameters, input, options).call(); + boolean changed = !output.equals(input); if (parameters.isDryRun()) { - outWriter.println(STDIN_FILENAME); + if (changed) { + outWriter.println(STDIN_FILENAME); + } } else { outWriter.write(output); } - if (input.equals(output)) { - return 0; + if (changed) { + return parameters.isSetExitIfChanged() ? 1 : 0; } - return parameters.isSetExitIfChanged() ? 1 : 0; + return 0; } catch (FormatterException e) { for (FormatterDiagnostic diagnostic : e.diagnostics()) { errWriter.println(STDIN_FILENAME + ":" + diagnostic.toString()); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java index f94ed8a26..bff7647c2 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java @@ -106,6 +106,34 @@ public void testFormatStdinStdoutWithDashFlag() throws Exception { System.setIn(oldIn); } + @Test + public void testFormatStdinStdoutWithDryRunAndExit0() throws Exception { + testFormatStdinStdoutWithArgs(0, "-", "-n"); + } + + @Test + public void testFormatStdinStdoutWithDryRunAndExit1() throws Exception { + testFormatStdinStdoutWithArgs(1, "-", "-n", "--set-exit-if-changed"); + } + + private void testFormatStdinStdoutWithArgs(int exit, String...args) throws Exception { + String input = "class Foo{\n" + "void f\n" + "() {\n" + "}\n" + "}\n"; + String expectedOutput = "" + System.lineSeparator(); // Main.STDIN_FILENAME + + InputStream in = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + StringWriter out = new StringWriter(); + StringWriter err = new StringWriter(); + + InputStream oldIn = System.in; + System.setIn(in); + + Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in); + assertThat(main.format(args)).isEqualTo(exit); + assertThat(out.toString()).isEqualTo(expectedOutput); + + System.setIn(oldIn); + } + @Test public void testFormatLengthUpToEOF() throws Exception { String input = "class Foo{\n" + "void f\n" + "() {\n" + "}\n" + "}\n\n\n\n\n\n";