com.google.googlejavaformat.java.Formatter Java Examples
The following examples show how to use
com.google.googlejavaformat.java.Formatter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PrismBundler.java From Prism4j with Apache License 2.0 | 6 votes |
@NotNull private static String grammarLocatorSource( @NotNull String template, @NotNull ClassInfo classInfo, @NotNull Map<String, LanguageInfo> languages) { final StringBuilder builder = new StringBuilder(template); replaceTemplate(builder, TEMPLATE_PACKAGE_NAME, classInfo.packageName); replaceTemplate(builder, TEMPLATE_IMPORTS, createImports(languages)); replaceTemplate(builder, TEMPLATE_CLASS_NAME, classInfo.className); replaceTemplate(builder, TEMPLATE_REAL_LANGUAGE_NAME, createRealLanguageName(languages)); replaceTemplate(builder, TEMPLATE_OBTAIN_GRAMMAR, createObtainGrammar(languages)); replaceTemplate(builder, TEMPLATE_TRIGGER_MODIFY, createTriggerModify(languages)); replaceTemplate(builder, TEMPLATE_LANGUAGES, createLanguages(languages)); final Formatter formatter = new Formatter(JavaFormatterOptions.defaultOptions()); try { return formatter.formatSource(builder.toString()); } catch (FormatterException e) { System.out.printf("source: %n%s%n", builder.toString()); throw new RuntimeException(e); } }
Example #2
Source File: GoogleJavaFormatter.java From git-code-format-maven-plugin with MIT License | 6 votes |
private String doFormat(String unformattedContent, LineRanges lineRanges) throws FormatterException { if (options.isFixImportsOnly()) { if (!lineRanges.isAll()) { return unformattedContent; } return fixImports(unformattedContent); } if (lineRanges.isAll()) { return fixImports(formatter.formatSource(unformattedContent)); } RangeSet<Integer> charRangeSet = Formatter.lineRangesToCharRanges(unformattedContent, lineRanges.rangeSet()); return formatter.formatSource(unformattedContent, charRangeSet.asRanges()); }
Example #3
Source File: CompilationUnitBuilder.java From FreeBuilder with Apache License 2.0 | 6 votes |
private static String formatSource(String source) { try { return new Formatter().formatSource(source); } catch (FormatterException | RuntimeException e) { StringBuilder message = new StringBuilder() .append("Formatter failed:\n") .append(e.getMessage()) .append("\nGenerated source:"); int lineNo = 0; for (String line : source.split("\n")) { message .append("\n") .append(++lineNo) .append(": ") .append(line); } throw new RuntimeException(message.toString()); } }
Example #4
Source File: FormatterUtil.java From google-java-format with Apache License 2.0 | 6 votes |
static Map<TextRange, String> getReplacements( Formatter formatter, String text, Collection<TextRange> ranges) { try { ImmutableMap.Builder<TextRange, String> replacements = ImmutableMap.builder(); formatter .getFormatReplacements(text, toRanges(ranges)) .forEach( replacement -> replacements.put( toTextRange(replacement.getReplaceRange()), replacement.getReplacementString())); return replacements.build(); } catch (FormatterException e) { return ImmutableMap.of(); } }
Example #5
Source File: FormatFactory.java From java-n-IDE-for-Android with Apache License 2.0 | 5 votes |
private static String formatJava(Context context, String src) throws FormatterException { AppSetting setting = new AppSetting(context); JavaFormatterOptions.Builder builder = JavaFormatterOptions.builder(); builder.style(setting.getFormatType() == 0 ? JavaFormatterOptions.Style.GOOGLE : JavaFormatterOptions.Style.AOSP); return new Formatter(builder.build()).formatSource(src); }
Example #6
Source File: FormattingJavaFileObject.java From java-n-IDE-for-Android with Apache License 2.0 | 5 votes |
/** * Create a new {@link FormattingJavaFileObject}. * * @param delegate {@link JavaFileObject} to decorate * @param messager to log messages with. */ FormattingJavaFileObject( JavaFileObject delegate, Formatter formatter, @Nullable Messager messager) { super(checkNotNull(delegate)); this.formatter = checkNotNull(formatter); this.messager = messager; }
Example #7
Source File: SourceProjectImpl.java From chrome-devtools-java-client with Apache License 2.0 | 5 votes |
private static Function<CompilationUnit, String> googleCodeFormatter( JavaFormatterOptions options, Function<CompilationUnit, String> printer) { Formatter formatter = new Formatter(options); return compilationUnit -> { String source = printer.apply(compilationUnit); try { return formatter.formatSourceAndFixImports(source); } catch (FormatterException e) { throw new RuntimeException("Failed formatting source.", e); } }; }
Example #8
Source File: JavaFormatter.java From javaide with GNU General Public License v3.0 | 5 votes |
@Nullable @Override public CharSequence format(CharSequence input) { try { AppSetting setting = new AppSetting(context); JavaFormatterOptions.Builder builder = JavaFormatterOptions.builder(); builder.style(setting.getFormatType() == 0 ? JavaFormatterOptions.Style.GOOGLE : JavaFormatterOptions.Style.AOSP); return new Formatter(builder.build()).formatSource(input.toString()); } catch (Exception e) { return null; } }
Example #9
Source File: FormattingJavaFileObject.java From javaide with GNU General Public License v3.0 | 5 votes |
/** * Create a new {@link FormattingJavaFileObject}. * * @param delegate {@link JavaFileObject} to decorate * @param messager to log messages with. */ FormattingJavaFileObject( JavaFileObject delegate, Formatter formatter, @Nullable Messager messager) { super(checkNotNull(delegate)); this.formatter = checkNotNull(formatter); this.messager = messager; }
Example #10
Source File: Main.java From bazel-tools with Apache License 2.0 | 5 votes |
private static String formatJavaSource( final Formatter formatter, final Path javaFile, final String source) { final String formattedSource; try { formattedSource = formatter.formatSource(source); } catch (final FormatterException e) { throw new IllegalStateException("Could not format source in file " + javaFile, e); } return formattedSource; }
Example #11
Source File: GoogleJavaFormatCodeStyleManager.java From google-java-format with Apache License 2.0 | 5 votes |
/** * Format the ranges of the given document. * * <p>Overriding methods will need to modify the document with the result of the external * formatter (usually using {@link #performReplacements(Document, Map)}. */ private void format(Document document, Collection<TextRange> ranges) { Style style = GoogleJavaFormatSettings.getInstance(getProject()).getStyle(); Formatter formatter = new Formatter(JavaFormatterOptions.builder().style(style).build()); performReplacements( document, FormatterUtil.getReplacements(formatter, document.getText(), ranges)); }
Example #12
Source File: FormattingJavaFileObject.java From google-java-format with Apache License 2.0 | 5 votes |
/** * Create a new {@link FormattingJavaFileObject}. * * @param delegate {@link JavaFileObject} to decorate * @param messager to log messages with. */ FormattingJavaFileObject( JavaFileObject delegate, Formatter formatter, @Nullable Messager messager) { super(checkNotNull(delegate)); this.formatter = checkNotNull(formatter); this.messager = messager; }
Example #13
Source File: Main.java From bazel-tools with Apache License 2.0 | 4 votes |
private static void run( final Path workspaceDirectory, final Path buildifier, final boolean verify, final boolean gitChanges) throws IOException { final JavaFormatterOptions options = JavaFormatterOptions.builder().style(JavaFormatterOptions.Style.GOOGLE).build(); final Formatter formatter = new Formatter(options); final Set<Path> malformattedPaths = new ConcurrentSkipListSet<>(); final Sources sources; if (gitChanges) { final ImmutableList<Path> paths = listGitChanges(workspaceDirectory); sources = new GitChangesSources(paths); } else { sources = new AllSources(); } LOG.info("Processing Java files..."); try (final Stream<Path> javaFiles = sources.findFilesMatching(workspaceDirectory, "glob:**/*" + ".java")) { javaFiles .parallel() .forEach( javaFile -> handleResult(formatJavaFile(formatter, javaFile), verify, malformattedPaths)); } LOG.info("Processing Scala files..."); try (final Stream<Path> scalaFiles = sources.findFilesMatching(workspaceDirectory, "glob:**/*.scala")) { scalaFiles .parallel() .forEach( scalaFile -> handleResult(formatScalaFile(scalaFile), verify, malformattedPaths)); } LOG.info("Processing Bazel BUILD files..."); try (final Stream<Path> buildFiles = sources.findFilesMatching(workspaceDirectory, "glob:**/BUILD")) { buildFiles .parallel() .forEach( buildFile -> handleResult(formatBuildFile(buildifier, buildFile), verify, malformattedPaths)); } LOG.info("Processing Bazel WORKSPACE files..."); try (final Stream<Path> workspaceFiles = sources.findFilesMatching(workspaceDirectory, "glob:**/WORKSPACE")) { workspaceFiles .parallel() .forEach( workspaceFile -> handleResult( formatBuildFile(buildifier, workspaceFile), verify, malformattedPaths)); } if (!malformattedPaths.isEmpty()) { LOG.error("There are malformatted files, please run 'tools/format/run'!"); LOG.error("Malformatted file paths are:"); for (final Path malformattedPath : malformattedPaths) { LOG.error(" - {}", workspaceDirectory.relativize(malformattedPath)); } System.exit(1); } }
Example #14
Source File: Main.java From bazel-tools with Apache License 2.0 | 4 votes |
private static FormattingResult formatJavaFile(final Formatter formatter, final Path javaFile) { return FormattingResult.create( javaFile, formatJavaSource(formatter, javaFile, readFile(javaFile))); }
Example #15
Source File: GoogleJavaFormatter.java From git-code-format-maven-plugin with MIT License | 4 votes |
public GoogleJavaFormatter(GoogleJavaFormatterOptions options, String sourceEncoding) { this.options = requireNonNull(options); this.formatter = new Formatter(options.javaFormatterOptions()); this.sourceEncoding = sourceEncoding; }
Example #16
Source File: GoogleFormatterMojo.java From googleformatter-maven-plugin with Apache License 2.0 | 4 votes |
@Override public void execute() throws MojoExecutionException { if ("pom".equals(project.getPackaging())) { getLog().info("Project packaging is POM, skipping..."); return; } if (skip) { getLog().info("Skipping source reformatting due to plugin configuration."); return; } try { Set<File> sourceFiles = new HashSet<>(); if (formatMain) { sourceFiles.addAll(findFilesToReformat(sourceDirectory, outputDirectory)); } if (formatTest) { sourceFiles.addAll(findFilesToReformat(testSourceDirectory, testOutputDirectory)); } Set<File> sourceFilesToProcess = filterModified ? filterUnchangedFiles(sourceFiles) : sourceFiles; JavaFormatterOptions options = getJavaFormatterOptions(); for (File file : sourceFilesToProcess) { String source = CharStreams.toString(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); Formatter formatter = new Formatter(options); String formattedSource = fixImports ? formatter.formatSourceAndFixImports(source) : formatter.formatSource(source); HashCode sourceHash = Hashing.sha256().hashString(source, StandardCharsets.UTF_8); HashCode formattedHash = Hashing.sha256().hashString(formattedSource, StandardCharsets.UTF_8); if (!formattedHash.equals(sourceHash)) { // overwrite existing file Files.write(file.toPath(), formattedSource.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); getLog().info(String.format("Reformatted file %s", file.getPath())); } } } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } }