aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/java/com/google/googlejavaformat/java/Main.java
blob: 953ca5860c3e6d68a45dc323c6d352598baea609 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
 * Copyright 2015 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.googlejavaformat.java;

import static java.lang.Math.min;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.io.ByteStreams;
import com.google.googlejavaformat.FormatterDiagnostic;
import com.google.googlejavaformat.java.JavaFormatterOptions.Style;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/** The main class for the Java formatter CLI. */
public final class Main {
  private static final int MAX_THREADS = 20;
  private static final String STDIN_FILENAME = "<stdin>";

  static String versionString() {
    return "google-java-format: Version " + GoogleJavaFormatVersion.version();
  }

  private final PrintWriter outWriter;
  private final PrintWriter errWriter;
  private final InputStream inStream;

  public Main(PrintWriter outWriter, PrintWriter errWriter, InputStream inStream) {
    this.outWriter = outWriter;
    this.errWriter = errWriter;
    this.inStream = inStream;
  }

  /**
   * The main method for the formatter, with some number of file names to format. We process them in
   * parallel, but we must be careful; if multiple file names refer to the same file (which is hard
   * to determine), we must serialize their updates.
   *
   * @param args the command-line arguments
   */
  public static void main(String[] args) {
    PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out, UTF_8));
    PrintWriter err = new PrintWriter(new OutputStreamWriter(System.err, UTF_8));
    int result = main(out, err, args);
    System.exit(result);
  }

  /**
   * Package-private main entry point used this CLI program and the java.util.spi.ToolProvider
   * implementation in the same package as this Main class.
   */
  static int main(PrintWriter out, PrintWriter err, String... args) {
    try {
      Main formatter = new Main(out, err, System.in);
      return formatter.format(args);
    } catch (UsageException e) {
      err.print(e.getMessage());
      return 0;
    } finally {
      err.flush();
      out.flush();
    }
  }

  /**
   * The main entry point for the formatter, with some number of file names to format. We process
   * them in parallel, but we must be careful; if multiple file names refer to the same file (which
   * is hard to determine), we must serialize their update.
   *
   * @param args the command-line arguments
   */
  public int format(String... args) throws UsageException {
    CommandLineOptions parameters = processArgs(args);
    if (parameters.version()) {
      errWriter.println(versionString());
      return 0;
    }
    if (parameters.help()) {
      throw new UsageException();
    }

    JavaFormatterOptions options =
        JavaFormatterOptions.builder()
            .style(parameters.aosp() ? Style.AOSP : Style.GOOGLE)
            .formatJavadoc(parameters.formatJavadoc())
            .build();

    if (parameters.stdin()) {
      return formatStdin(parameters, options);
    } else {
      return formatFiles(parameters, options);
    }
  }

  private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions options) {
    int numThreads = min(MAX_THREADS, parameters.files().size());
    ExecutorService executorService = Executors.newFixedThreadPool(numThreads);

    Map<Path, String> inputs = new LinkedHashMap<>();
    Map<Path, Future<String>> results = new LinkedHashMap<>();
    boolean allOk = true;

    for (String fileName : parameters.files()) {
      if (!fileName.endsWith(".java")) {
        errWriter.println("Skipping non-Java file: " + fileName);
        continue;
      }
      Path path = Paths.get(fileName);
      String input;
      try {
        input = new String(Files.readAllBytes(path), UTF_8);
        inputs.put(path, input);
        results.put(
            path, executorService.submit(new FormatFileCallable(parameters, input, options)));
      } catch (IOException e) {
        errWriter.println(fileName + ": could not read file: " + e.getMessage());
        allOk = false;
      }
    }

    for (Map.Entry<Path, Future<String>> result : results.entrySet()) {
      Path path = result.getKey();
      String formatted;
      try {
        formatted = result.getValue().get();
      } catch (InterruptedException e) {
        errWriter.println(e.getMessage());
        allOk = false;
        continue;
      } catch (ExecutionException e) {
        if (e.getCause() instanceof FormatterException) {
          for (FormatterDiagnostic diagnostic : ((FormatterException) e.getCause()).diagnostics()) {
            errWriter.println(path + ":" + diagnostic);
          }
        } else {
          errWriter.println(path + ": error: " + e.getCause().getMessage());
          e.getCause().printStackTrace(errWriter);
        }
        allOk = false;
        continue;
      }
      boolean changed = !formatted.equals(inputs.get(path));
      if (changed && parameters.setExitIfChanged()) {
        allOk = false;
      }
      if (parameters.inPlace()) {
        if (!changed) {
          continue; // preserve original file
        }
        try {
          Files.write(path, formatted.getBytes(UTF_8));
        } catch (IOException e) {
          errWriter.println(path + ": could not write file: " + e.getMessage());
          allOk = false;
          continue;
        }
      } else if (parameters.dryRun()) {
        if (changed) {
          outWriter.println(path);
        }
      } else {
        outWriter.write(formatted);
      }
    }
    return allOk ? 0 : 1;
  }

  private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions options) {
    String input;
    try {
      input = new String(ByteStreams.toByteArray(inStream), UTF_8);
    } catch (IOException e) {
      throw new IOError(e);
    }
    String stdinFilename = parameters.assumeFilename().orElse(STDIN_FILENAME);
    boolean ok = true;
    try {
      String output = new FormatFileCallable(parameters, input, options).call();
      boolean changed = !input.equals(output);
      if (changed && parameters.setExitIfChanged()) {
        ok = false;
      }
      if (parameters.dryRun()) {
        if (changed) {
          outWriter.println(stdinFilename);
        }
      } else {
        outWriter.write(output);
      }
    } catch (FormatterException e) {
      for (FormatterDiagnostic diagnostic : e.diagnostics()) {
        errWriter.println(stdinFilename + ":" + diagnostic);
      }
      ok = false;
      // TODO(cpovirk): Catch other types of exception (as we do in the formatFiles case).
    }
    return ok ? 0 : 1;
  }

  /** Parses and validates command-line flags. */
  public static CommandLineOptions processArgs(String... args) throws UsageException {
    CommandLineOptions parameters;
    try {
      parameters = CommandLineOptionsParser.parse(Arrays.asList(args));
    } catch (IllegalArgumentException e) {
      throw new UsageException(e.getMessage());
    } catch (Throwable t) {
      t.printStackTrace();
      throw new UsageException(t.getMessage());
    }
    int filesToFormat = parameters.files().size();
    if (parameters.stdin()) {
      filesToFormat++;
    }

    if (parameters.inPlace() && parameters.files().isEmpty()) {
      throw new UsageException("in-place formatting was requested but no files were provided");
    }
    if (parameters.isSelection() && filesToFormat != 1) {
      throw new UsageException("partial formatting is only support for a single file");
    }
    if (parameters.offsets().size() != parameters.lengths().size()) {
      throw new UsageException("-offsets and -lengths flags must be provided in matching pairs");
    }
    if (filesToFormat <= 0 && !parameters.version() && !parameters.help()) {
      throw new UsageException("no files were provided");
    }
    if (parameters.stdin() && !parameters.files().isEmpty()) {
      throw new UsageException("cannot format from standard input and files simultaneously");
    }
    if (parameters.assumeFilename().isPresent() && !parameters.stdin()) {
      throw new UsageException(
          "--assume-filename is only supported when formatting standard input");
    }
    if (parameters.dryRun() && parameters.inPlace()) {
      throw new UsageException("cannot use --dry-run and --in-place at the same time");
    }
    return parameters;
  }
}