Skip to content

Commit f257f46

Browse files
author
hujian06
committed
formatSourceFile method can be used now
1 parent 20c9af0 commit f257f46

File tree

2 files changed

+72
-46
lines changed

2 files changed

+72
-46
lines changed

core/src/main/java/com/google/googlejavaformat/java/Formatter.java

+72-30
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@
1414

1515
package com.google.googlejavaformat.java;
1616

17-
import static java.nio.charset.StandardCharsets.UTF_8;
18-
1917
import com.google.common.base.Strings;
2018
import com.google.common.collect.ImmutableList;
2119
import com.google.common.collect.Iterables;
@@ -33,10 +31,26 @@
3331
import com.google.googlejavaformat.Newlines;
3432
import com.google.googlejavaformat.Op;
3533
import com.google.googlejavaformat.OpsBuilder;
34+
import org.openjdk.javax.tools.Diagnostic;
35+
import org.openjdk.javax.tools.DiagnosticCollector;
36+
import org.openjdk.javax.tools.DiagnosticListener;
37+
import org.openjdk.javax.tools.JavaFileObject;
38+
import org.openjdk.javax.tools.SimpleJavaFileObject;
39+
import org.openjdk.javax.tools.StandardLocation;
40+
import org.openjdk.tools.javac.file.JavacFileManager;
41+
import org.openjdk.tools.javac.main.Option;
42+
import org.openjdk.tools.javac.parser.JavacParser;
43+
import org.openjdk.tools.javac.parser.ParserFactory;
44+
import org.openjdk.tools.javac.tree.JCTree.JCCompilationUnit;
45+
import org.openjdk.tools.javac.util.Context;
46+
import org.openjdk.tools.javac.util.Log;
47+
import org.openjdk.tools.javac.util.Options;
3648

3749
import java.io.File;
50+
import java.io.FileNotFoundException;
3851
import java.io.IOError;
3952
import java.io.IOException;
53+
import java.io.PrintWriter;
4054
import java.net.URI;
4155
import java.nio.file.Files;
4256
import java.nio.file.Path;
@@ -48,27 +62,13 @@
4862
import java.util.concurrent.CompletableFuture;
4963
import java.util.concurrent.ExecutionException;
5064
import java.util.concurrent.ExecutorService;
51-
import java.util.concurrent.Future;
5265
import java.util.concurrent.LinkedBlockingQueue;
5366
import java.util.concurrent.ThreadPoolExecutor;
5467
import java.util.concurrent.TimeUnit;
5568
import java.util.concurrent.TimeoutException;
5669
import java.util.stream.Collectors;
5770

58-
import org.openjdk.javax.tools.Diagnostic;
59-
import org.openjdk.javax.tools.DiagnosticCollector;
60-
import org.openjdk.javax.tools.DiagnosticListener;
61-
import org.openjdk.javax.tools.JavaFileObject;
62-
import org.openjdk.javax.tools.SimpleJavaFileObject;
63-
import org.openjdk.javax.tools.StandardLocation;
64-
import org.openjdk.tools.javac.file.JavacFileManager;
65-
import org.openjdk.tools.javac.main.Option;
66-
import org.openjdk.tools.javac.parser.JavacParser;
67-
import org.openjdk.tools.javac.parser.ParserFactory;
68-
import org.openjdk.tools.javac.tree.JCTree.JCCompilationUnit;
69-
import org.openjdk.tools.javac.util.Context;
70-
import org.openjdk.tools.javac.util.Log;
71-
import org.openjdk.tools.javac.util.Options;
71+
import static java.nio.charset.StandardCharsets.UTF_8;
7272

7373
/**
7474
* This is google-java-format, a new Java formatter that follows the Google Java Style Guide quite
@@ -104,7 +104,12 @@
104104
*/
105105
@Immutable
106106
public final class Formatter {
107-
static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(
107+
/**
108+
* This ExecutorService will be used at method {@link Formatter#formatSourceFile(String, boolean, boolean, long, TimeUnit, boolean)}
109+
* if the method's param {@code useExecutor} is true, then the formatter will submit the task to this Executor.
110+
* and the default timeout is 1 sec for each file.
111+
* */
112+
private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(
108113
Runtime.getRuntime().availableProcessors(),
109114
Math.min(Runtime.getRuntime().availableProcessors() * 2, 50),
110115
60,
@@ -221,32 +226,45 @@ public void formatSource(CharSource input, CharSink output)
221226
* The ExecuteService {@link Formatter#EXECUTOR_SERVICE} to submit a {@link FormatFileCallable}.
222227
* You should check the result list's element. if the element is empty, you should do not overwrite
223228
* it to source file path.
229+
* if you want to replace the old source by the formatted source, let the param {@code reWrite} as true
224230
*
231+
* @param reWrite whether to reWrite the source file.
225232
* @param file the input
226233
* @param useExecutor whether multi-thread mode
234+
* @param timeout the timeout value, for each java file.
235+
* @param unit the time unit
236+
* @param timeoutForAll if true, total timeout is {@code timeout}, else timeout is {@code timeout * fileCount}
227237
* @return the formatted java source
228238
*/
229-
public List<String> formatSourceFile(String file, boolean useExecutor)
239+
public List<String> formatSourceFile(String file, boolean useExecutor, boolean reWrite,
240+
long timeout, TimeUnit unit, boolean timeoutForAll)
230241
throws IOException, FormatterException {
231242
if (Strings.isNullOrEmpty(file)) {
232243
return Collections.emptyList();
233244
}
245+
// re-set the timeout value.
246+
if (timeout <= 0) {
247+
timeout = 1;
248+
unit = TimeUnit.SECONDS;
249+
timeoutForAll = false;
250+
}
234251
File sourceFile = new File(file);
235252
if (sourceFile.isFile()) {
236253
// this is a file
237254
if (useExecutor) {
238-
CompletableFuture<List<String>> formattedFuture = CompletableFuture.supplyAsync(()->{
255+
CompletableFuture<List<String>> formattedFuture = CompletableFuture.supplyAsync(() -> {
239256
Path path = Paths.get(file);
240257
String formatted;
241258
try {
242259
formatted = formatSource(new String(Files.readAllBytes(path), UTF_8));
260+
writeFile(file, formatted, reWrite);
243261
} catch (FormatterException | IOException e) {
244262
formatted = "";
245263
}
246264
return ImmutableList.of(formatted); // do not update the file source.
247265
}, EXECUTOR_SERVICE);
248266
try {
249-
if (formattedFuture.get(1, TimeUnit.SECONDS) == null) {
267+
if (formattedFuture.get(timeout, unit) == null) {
250268
return Collections.emptyList();
251269
} else {
252270
return formattedFuture.getNow(Collections.emptyList());
@@ -257,12 +275,13 @@ public List<String> formatSourceFile(String file, boolean useExecutor)
257275
} else {
258276
Path path = Paths.get(file);
259277
String formatted = formatSource(new String(Files.readAllBytes(path), UTF_8));
278+
writeFile(file, formatted, reWrite);
260279
return ImmutableList.of(formatted); // do not update the file source.
261280
}
262281
} else if (sourceFile.isDirectory()) {
263282
// this is a directory
264283
List<String> filePathLit = Lists.newArrayList();
265-
scanDirectory(file, filePathLit);
284+
scanJavaFileInDirectory(file, filePathLit);
266285
if (filePathLit.isEmpty()) {
267286
return Collections.emptyList();
268287
}
@@ -274,6 +293,7 @@ public List<String> formatSourceFile(String file, boolean useExecutor)
274293
String formatted;
275294
try {
276295
formatted = formatSource(new String(Files.readAllBytes(path), UTF_8));
296+
writeFile(p, formatted, reWrite);
277297
} catch (FormatterException | IOException e) {
278298
formatted = "";
279299
}
@@ -284,12 +304,14 @@ public List<String> formatSourceFile(String file, boolean useExecutor)
284304
CompletableFuture<List<String>> formattedResultFuture =
285305
CompletableFuture
286306
.allOf(formattedFutureList.toArray(new CompletableFuture[formattedFutureList.size()]))
287-
.thenApply(formattedFuture -> formattedFutureList
288-
.stream()
289-
.map(CompletableFuture::join)
290-
.collect(Collectors.toList()));
307+
.thenApply(formattedFuture ->
308+
formattedFutureList.stream().map(CompletableFuture::join).collect(Collectors.toList()));
291309
try {
292-
if (formattedResultFuture.get(formattedFutureList.size(), TimeUnit.SECONDS) == null) {
310+
long timeOutValue = timeout;
311+
if (!timeoutForAll) {
312+
timeOutValue = formattedFutureList.size() * timeout;
313+
}
314+
if (formattedResultFuture.get(timeOutValue, unit) == null) {
293315
return Collections.emptyList();
294316
} else {
295317
return formattedResultFuture.getNow(Collections.emptyList());
@@ -303,6 +325,7 @@ public List<String> formatSourceFile(String file, boolean useExecutor)
303325
Path path = Paths.get(p);
304326
String formatted = formatSource(new String(Files.readAllBytes(path), UTF_8));
305327
formattedList.add(formatted);
328+
writeFile(p, formatted, reWrite);
306329
}
307330
return formattedList;
308331
}
@@ -312,13 +335,32 @@ public List<String> formatSourceFile(String file, boolean useExecutor)
312335
}
313336
}
314337

338+
/**
339+
* Re-write file with the new content.
340+
*
341+
* @param filePath the file path
342+
* @param content the new content
343+
* @param reWrite whether to re-write
344+
* @throws FileNotFoundException Not Find
345+
*/
346+
private void writeFile(String filePath, String content, boolean reWrite)
347+
throws FileNotFoundException {
348+
if (!Strings.isNullOrEmpty(content) && reWrite) {
349+
// re-write the formatted source.
350+
PrintWriter printWriter = new PrintWriter(new File(filePath));
351+
printWriter.print(content);
352+
printWriter.flush();
353+
printWriter.close();
354+
}
355+
}
356+
315357
/**
316358
* Scan the directory {@code directory} to find all of the java files.
317359
*
318360
* @param directory the scan directory
319361
* @param filePathList the result.
320362
*/
321-
private void scanDirectory(String directory, List<String> filePathList) {
363+
private void scanJavaFileInDirectory(String directory, List<String> filePathList) {
322364
if (Strings.isNullOrEmpty(directory)) {
323365
return;
324366
}
@@ -334,10 +376,10 @@ private void scanDirectory(String directory, List<String> filePathList) {
334376
return; // no file
335377
}
336378
for (File file : fileList) {
337-
if (file.isFile()) {
379+
if (file.isFile() && file.getAbsolutePath().endsWith(".java")) {
338380
filePathList.add(file.getAbsolutePath());
339381
} else if (file.isDirectory()) {
340-
scanDirectory(directory, filePathList);
382+
scanJavaFileInDirectory(file.getAbsolutePath(), filePathList);
341383
}
342384
}
343385
}

core/src/test/java/com/google/googlejavaformat/FormatterTest.java

-16
This file was deleted.

0 commit comments

Comments
 (0)