com.google.googlejavaformat.java.FormatterException Java Examples

The following examples show how to use com.google.googlejavaformat.java.FormatterException. 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 vote down vote up
@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 vote down vote up
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 vote down vote up
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 vote down vote up
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 vote down vote up
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 vote down vote up
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
Example #7
Source File: SourceProjectImpl.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
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: GoogleJavaFormatter.java    From jdmn with Apache License 2.0 5 votes vote down vote up
@Override
public String formatSource(String code) {
    try {
        return FORMATTER.formatSource(code);
    } catch (FormatterException e) {
        throw new DMNRuntimeException("Failed to format java");
    }
}
 
Example #9
Source File: FormatterTool.java    From startup-os with Apache License 2.0 5 votes vote down vote up
@Override
public void format(Path path) throws IOException {
  try {
    File tempFile = File.createTempFile("prefix", "suffix");
    Path tempFilePath = Paths.get(tempFile.getAbsolutePath());
    // write formatted text to temporary file first
    Files.write(
        tempFilePath, Collections.singleton(javaFormatter.formatSource(readFile(path))));
    // move temporary file to original
    Files.move(tempFilePath, path, StandardCopyOption.REPLACE_EXISTING);
  } catch (FormatterException e) {
    e.printStackTrace();
  }
}
 
Example #10
Source File: FormattingJavaFileObject.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
 
Example #11
Source File: Main.java    From bazel-tools with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: GoogleJavaFormatter.java    From git-code-format-maven-plugin with MIT License 5 votes vote down vote up
@Override
public boolean validate(InputStream content) {
  try {
    String unformattedContent = IOUtils.toString(content, sourceEncoding);
    String formattedContent = doFormat(unformattedContent, LineRanges.all());
    return unformattedContent.equals(formattedContent);
  } catch (IOException | FormatterException e) {
    throw new MavenGitCodeFormatException(e);
  }
}
 
Example #13
Source File: GoogleJavaFormatter.java    From git-code-format-maven-plugin with MIT License 5 votes vote down vote up
private String fixImports(final String unformattedContent) throws FormatterException {
  String formattedContent = unformattedContent;
  if (!options.isSkipRemovingUnusedImports()) {
    formattedContent = RemoveUnusedImports.removeUnusedImports(formattedContent);
  }
  if (!options.isSkipSortingImports()) {
    formattedContent = ImportOrderer.reorderImports(formattedContent);
  }
  return formattedContent;
}
 
Example #14
Source File: FormattingJavaFileObject.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void write(String string) throws IOException {
      stringBuilder.append(string);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}