Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> files,
Expand All @@ -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;
Expand All @@ -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. */
Expand Down Expand Up @@ -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();
}
Expand All @@ -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<String> filesBuilder() {
return files;
Expand Down Expand Up @@ -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(),
Expand All @@ -238,7 +271,9 @@ CommandLineOptions build() {
this.fixImportsOnly,
this.removeJavadocOnlyImports,
this.sortImports,
this.removeUnusedImports);
this.removeUnusedImports,
this.dryRun,
this.setExitIfChanged);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ static CommandLineOptions parse(Iterable<String> 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":
Expand Down
46 changes: 35 additions & 11 deletions core/src/main/java/com/google/googlejavaformat/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti
boolean allOk = true;
for (Map.Entry<Path, Future<String>> result : results.entrySet()) {
String formatted;
Path path = result.getKey();
try {
formatted = result.getValue().get();
} catch (InterruptedException e) {
Expand All @@ -142,28 +143,38 @@ 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;
}
// in default mode always print formatted text to stdout, regardless of whether the input was formatted
if (parameters.stdout()) {
outWriter.write(formatted);
}
// 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;
}
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;
Expand All @@ -178,7 +189,17 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti
}
try {
String output = new FormatFileCallable(parameters, input, options).call();
outWriter.write(output);
boolean changed = !output.equals(input);
if (parameters.isDryRun()) {
if (changed) {
outWriter.println(STDIN_FILENAME);
}
} else {
outWriter.write(output);
}
if (changed) {
return parameters.isSetExitIfChanged() ? 1 : 0;
}
return 0;
} catch (FormatterException e) {
for (FormatterDiagnostic diagnostic : e.diagnostics()) {
Expand Down Expand Up @@ -208,6 +229,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");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
"",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "<stdin>" + 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";
Expand Down
55 changes: 55 additions & 0 deletions core/src/test/java/com/google/googlejavaformat/java/MainTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String> 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();
}
}