From cd86e6ad46bd1cc4cecf26786737b58aeb883658 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Mon, 5 Dec 2022 08:48:37 +0100 Subject: [PATCH 001/107] Add Swiss-Option as formatting to 120 characters long lines, Remove Plugins --- core/pom.xml | 546 ++++++++------- .../java/CommandLineOptions.java | 85 ++- .../java/CommandLineOptionsParser.java | 56 +- .../java/FormatFileCallable.java | 2 +- .../googlejavaformat/java/Formatter.java | 34 +- .../googlejavaformat/java/ImportOrderer.java | 20 +- .../java/JavaCommentsHelper.java | 4 +- .../java/JavaFormatterOptions.java | 28 +- .../google/googlejavaformat/java/Main.java | 2 +- .../googlejavaformat/java/StringWrapper.java | 2 +- eclipse_plugin/META-INF/MANIFEST.MF | 15 - eclipse_plugin/README.md | 43 -- eclipse_plugin/build.properties | 7 - eclipse_plugin/plugin.xml | 28 - eclipse_plugin/pom.xml | 141 ---- .../java/GoogleJavaFormatter.java | 144 ---- idea_plugin/.gitignore | 5 - idea_plugin/build.gradle | 62 -- idea_plugin/resources/META-INF/plugin.xml | 84 --- .../intellij/CodeStyleManagerDecorator.java | 246 ------- .../intellij/FormatterUtil.java | 64 -- .../GoogleJavaFormatCodeStyleManager.java | 172 ----- .../GoogleJavaFormatConfigurable.form | 40 -- .../GoogleJavaFormatConfigurable.java | 206 ------ .../intellij/GoogleJavaFormatInstaller.java | 57 -- .../intellij/GoogleJavaFormatSettings.java | 107 --- ...alConfigurationProjectManagerListener.java | 57 -- .../intellij/UiFormatterStyle.java | 52 -- pom.xml | 640 +++++++++--------- 29 files changed, 723 insertions(+), 2226 deletions(-) delete mode 100644 eclipse_plugin/META-INF/MANIFEST.MF delete mode 100644 eclipse_plugin/README.md delete mode 100644 eclipse_plugin/build.properties delete mode 100644 eclipse_plugin/plugin.xml delete mode 100644 eclipse_plugin/pom.xml delete mode 100644 eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java delete mode 100644 idea_plugin/.gitignore delete mode 100644 idea_plugin/build.gradle delete mode 100644 idea_plugin/resources/META-INF/plugin.xml delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/FormatterUtil.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatCodeStyleManager.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatInstaller.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java delete mode 100644 idea_plugin/src/com/google/googlejavaformat/intellij/UiFormatterStyle.java diff --git a/core/pom.xml b/core/pom.xml index 10565c66a..bfce4e27f 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -18,276 +18,296 @@ - 4.0.0 - - com.google.googlejavaformat - google-java-format-parent - HEAD-SNAPSHOT - + 4.0.0 + + com.github.mrdolch.googlejavaformat + google-java-format-parent + 1.15.0-SNAPSHOT + - google-java-format + google-java-format - Google Java Format + Google Java Format - - A Java source code formatter that follows Google Java Style. - + + A Java source code formatter that follows Google Java Style. + - - - - com.google.guava - guava - + + + + com.google.guava + guava + - - - org.checkerframework - checker-qual - true - - - com.google.errorprone - error_prone_annotations - true - - - com.google.auto.value - auto-value-annotations - true - - - com.google.auto.service - auto-service-annotations - true - + + + org.checkerframework + checker-qual + true + + + com.google.errorprone + error_prone_annotations + true + + + com.google.auto.value + auto-value-annotations + true + + + com.google.auto.service + auto-service-annotations + true + - - - junit - junit - - - com.google.guava - guava-testlib - - - com.google.truth - truth - - - com.google.truth.extensions - truth-java8-extension - test - - - com.google.testing.compile - compile-testing - 0.19 - test - - + + + junit + junit + + + com.google.guava + guava-testlib + + + com.google.truth + truth + + + com.google.truth.extensions + truth-java8-extension + test + + + com.google.testing.compile + compile-testing + 0.19 + test + + - - - - maven-javadoc-plugin - - 11 - UTF-8 - UTF-8 - UTF-8 - - https://guava.dev/releases/${guava.version}/api/docs/ - https://docs.oracle.com/en/java/javase/11/docs/api - - - --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED,com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED,com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED,com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED,com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED,com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED,com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED,com.google.googlejavaformat - - - - - attach-docs - post-integration-test - - jar - - - - - - org.apache.maven.plugins - maven-shade-plugin - 3.2.4 - - - shade-all-deps - package - - shade - - - true - all-deps - false - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - com.google.googlejavaformat.java.Main - - true - - - - - com.google.googlejavaformat - - - - - - - com.google.code.maven-replacer-plugin - replacer - 1.5.3 - - - generate-sources - - replace - - - - - ${project.basedir}/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java.template - ${project.build.directory}/generated-sources/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java - - - %VERSION% - ${project.version} - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 3.3.0 - - - add-source - generate-sources - - add-source - - - - ${project.build.directory}/generated-sources/java/ - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 11 - 11 - - - - - - - - jdk11 - - (,17) - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - **/Java17InputAstVisitor.java - - - - - maven-javadoc-plugin - - com.google.googlejavaformat.java.java17 - - - - - - - native - + - - org.graalvm.buildtools - native-maven-plugin - 0.9.13 - true - - - build-native - - build - - package - - - test-native - - test - - test - - - - google-java-format - - ${project.build.directory}/${project.artifactId}-${project.version}-all-deps.jar - - - -H:IncludeResourceBundles=com.sun.tools.javac.resources.compiler - --no-fallback - --initialize-at-build-time=com.sun.tools.javac.file.Locations - - - + + maven-javadoc-plugin + + 11 + UTF-8 + UTF-8 + UTF-8 + + https://guava.dev/releases/${guava.version}/api/docs/ + https://docs.oracle.com/en/java/javase/11/docs/api + + + + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED,com.google.googlejavaformat + + + --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED,com.google.googlejavaformat + + + --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED,com.google.googlejavaformat + + + --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED,com.google.googlejavaformat + + + --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED,com.google.googlejavaformat + + + --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED,com.google.googlejavaformat + + + --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED,com.google.googlejavaformat + + + + + + attach-docs + post-integration-test + + jar + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + shade-all-deps + package + + shade + + + true + all-deps + false + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.google.googlejavaformat.java.Main + + true + + + + + com.google.googlejavaformat + + + + + + + com.google.code.maven-replacer-plugin + replacer + 1.5.3 + + + generate-sources + + replace + + + + + + ${project.basedir}/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java.template + + + ${project.build.directory}/generated-sources/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java + + + + %VERSION% + ${project.version} + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.3.0 + + + add-source + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/java/ + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 11 + 11 + + - - - + + + + + jdk11 + + (,17) + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/Java17InputAstVisitor.java + + + + + maven-javadoc-plugin + + com.google.googlejavaformat.java.java17 + + + + + + + native + + + + org.graalvm.buildtools + native-maven-plugin + 0.9.13 + true + + + build-native + + build + + package + + + test-native + + test + + test + + + + google-java-format + + + ${project.build.directory}/${project.artifactId}-${project.version}-all-deps.jar + + + + -H:IncludeResourceBundles=com.sun.tools.javac.resources.compiler + --no-fallback + --initialize-at-build-time=com.sun.tools.javac.file.Locations + + + + + + + diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java index 5a233284a..d37713246 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java @@ -21,8 +21,7 @@ /** * Command line options for google-java-format. * - *

google-java-format doesn't depend on AutoValue, to allow AutoValue to depend on - * google-java-format. + *

google-java-format doesn't depend on AutoValue, to allow AutoValue to depend on google-java-format. */ final class CommandLineOptions { @@ -32,6 +31,7 @@ final class CommandLineOptions { private final ImmutableList offsets; private final ImmutableList lengths; private final boolean aosp; + private final boolean swiss; private final boolean version; private final boolean help; private final boolean stdin; @@ -45,29 +45,31 @@ final class CommandLineOptions { private final boolean formatJavadoc; CommandLineOptions( - ImmutableList files, - boolean inPlace, - ImmutableRangeSet lines, - ImmutableList offsets, - ImmutableList lengths, - boolean aosp, - boolean version, - boolean help, - boolean stdin, - boolean fixImportsOnly, - boolean sortImports, - boolean removeUnusedImports, - boolean dryRun, - boolean setExitIfChanged, - Optional assumeFilename, - boolean reflowLongStrings, - boolean formatJavadoc) { + final ImmutableList files, + final boolean inPlace, + final ImmutableRangeSet lines, + final ImmutableList offsets, + final ImmutableList lengths, + final boolean aosp, + final boolean swiss, + final boolean version, + final boolean help, + final boolean stdin, + final boolean fixImportsOnly, + final boolean sortImports, + final boolean removeUnusedImports, + final boolean dryRun, + final boolean setExitIfChanged, + final Optional assumeFilename, + final boolean reflowLongStrings, + final boolean formatJavadoc) { this.files = files; this.inPlace = inPlace; this.lines = lines; this.offsets = offsets; this.lengths = lengths; this.aosp = aosp; + this.swiss = swiss; this.version = version; this.help = help; this.stdin = stdin; @@ -110,6 +112,10 @@ ImmutableList lengths() { boolean aosp() { return aosp; } + /** Use SWISS style instead of Google Style (120 Characters line length). */ + boolean swiss() { + return swiss; + } /** Print the version. */ boolean version() { @@ -141,9 +147,7 @@ boolean removeUnusedImports() { return removeUnusedImports; } - /** - * Print the paths of the files whose contents would change if the formatter were run normally. - */ + /** Print the paths of the files whose contents would change if the formatter were run normally. */ boolean dryRun() { return dryRun; } @@ -183,6 +187,7 @@ static class Builder { private final ImmutableList.Builder lengths = ImmutableList.builder(); private boolean inPlace = false; private boolean aosp = false; + private boolean swiss = false; private boolean version = false; private boolean help = false; private boolean stdin = false; @@ -199,7 +204,7 @@ ImmutableList.Builder filesBuilder() { return files; } - Builder inPlace(boolean inPlace) { + Builder inPlace(final boolean inPlace) { this.inPlace = inPlace; return this; } @@ -208,72 +213,77 @@ ImmutableRangeSet.Builder linesBuilder() { return lines; } - Builder addOffset(Integer offset) { + Builder addOffset(final Integer offset) { offsets.add(offset); return this; } - Builder addLength(Integer length) { + Builder addLength(final Integer length) { lengths.add(length); return this; } - Builder aosp(boolean aosp) { + Builder aosp(final boolean aosp) { this.aosp = aosp; return this; } - Builder version(boolean version) { + Builder swiss(final boolean swiss) { + this.swiss = swiss; + return this; + } + + Builder version(final boolean version) { this.version = version; return this; } - Builder help(boolean help) { + Builder help(final boolean help) { this.help = help; return this; } - Builder stdin(boolean stdin) { + Builder stdin(final boolean stdin) { this.stdin = stdin; return this; } - Builder fixImportsOnly(boolean fixImportsOnly) { + Builder fixImportsOnly(final boolean fixImportsOnly) { this.fixImportsOnly = fixImportsOnly; return this; } - Builder sortImports(boolean sortImports) { + Builder sortImports(final boolean sortImports) { this.sortImports = sortImports; return this; } - Builder removeUnusedImports(boolean removeUnusedImports) { + Builder removeUnusedImports(final boolean removeUnusedImports) { this.removeUnusedImports = removeUnusedImports; return this; } - Builder dryRun(boolean dryRun) { + Builder dryRun(final boolean dryRun) { this.dryRun = dryRun; return this; } - Builder setExitIfChanged(boolean setExitIfChanged) { + Builder setExitIfChanged(final boolean setExitIfChanged) { this.setExitIfChanged = setExitIfChanged; return this; } - Builder assumeFilename(String assumeFilename) { + Builder assumeFilename(final String assumeFilename) { this.assumeFilename = Optional.of(assumeFilename); return this; } - Builder reflowLongStrings(boolean reflowLongStrings) { + Builder reflowLongStrings(final boolean reflowLongStrings) { this.reflowLongStrings = reflowLongStrings; return this; } - Builder formatJavadoc(boolean formatJavadoc) { + Builder formatJavadoc(final boolean formatJavadoc) { this.formatJavadoc = formatJavadoc; return this; } @@ -286,6 +296,7 @@ CommandLineOptions build() { offsets.build(), lengths.build(), aosp, + swiss, version, help, stdin, diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java index f7c3dec95..60192670b 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java @@ -14,12 +14,11 @@ package com.google.googlejavaformat.java; -import static java.nio.charset.StandardCharsets.UTF_8; - import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.Range; + import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -29,6 +28,8 @@ import java.util.Iterator; import java.util.List; +import static java.nio.charset.StandardCharsets.UTF_8; + /** A parser for {@link CommandLineOptions}. */ final class CommandLineOptionsParser { @@ -38,20 +39,20 @@ final class CommandLineOptionsParser { Splitter.on(CharMatcher.breakingWhitespace()).omitEmptyStrings().trimResults(); /** Parses {@link CommandLineOptions}. */ - static CommandLineOptions parse(Iterable options) { - CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); - List expandedOptions = new ArrayList<>(); + static CommandLineOptions parse(final Iterable options) { + final CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); + final List expandedOptions = new ArrayList<>(); expandParamsFiles(options, expandedOptions); - Iterator it = expandedOptions.iterator(); + final Iterator it = expandedOptions.iterator(); while (it.hasNext()) { - String option = it.next(); + final String option = it.next(); if (!option.startsWith("-")) { optionsBuilder.filesBuilder().add(option).addAll(it); break; } - String flag; - String value; - int idx = option.indexOf('='); + final String flag; + final String value; + final int idx = option.indexOf('='); if (idx >= 0) { flag = option.substring(0, idx); value = option.substring(idx + 1); @@ -86,6 +87,11 @@ static CommandLineOptions parse(Iterable options) { case "-a": optionsBuilder.aosp(true); break; + case "--swiss": + case "-swiss": + case "-s": + optionsBuilder.swiss(true); + break; case "--version": case "-version": case "-v": @@ -132,16 +138,16 @@ static CommandLineOptions parse(Iterable options) { return optionsBuilder.build(); } - private static Integer parseInteger(Iterator it, String flag, String value) { + private static Integer parseInteger(final Iterator it, final String flag, final String value) { try { return Integer.valueOf(getValue(flag, it, value)); - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { throw new IllegalArgumentException( String.format("invalid integer value for %s: %s", flag, value), e); } } - private static String getValue(String flag, Iterator it, String value) { + private static String getValue(final String flag, final Iterator it, final String value) { if (value != null) { return value; } @@ -157,8 +163,8 @@ private static String getValue(String flag, Iterator it, String value) { * number. Line numbers are {@code 1}-based, but are converted to the {@code 0}-based numbering * used internally by google-java-format. */ - private static void parseRangeSet(ImmutableRangeSet.Builder result, String ranges) { - for (String range : COMMA_SPLITTER.split(ranges)) { + private static void parseRangeSet(final ImmutableRangeSet.Builder result, final String ranges) { + for (final String range : COMMA_SPLITTER.split(ranges)) { result.add(parseRange(range)); } } @@ -167,15 +173,15 @@ private static void parseRangeSet(ImmutableRangeSet.Builder result, Str * Parse a range, as in "1:12" or "42". Line numbers provided are {@code 1}-based, but are * converted here to {@code 0}-based. */ - private static Range parseRange(String arg) { - List args = COLON_SPLITTER.splitToList(arg); + private static Range parseRange(final String arg) { + final List args = COLON_SPLITTER.splitToList(arg); switch (args.size()) { case 1: - int line = Integer.parseInt(args.get(0)) - 1; + final int line = Integer.parseInt(args.get(0)) - 1; return Range.closedOpen(line, line + 1); case 2: - int line0 = Integer.parseInt(args.get(0)) - 1; - int line1 = Integer.parseInt(args.get(1)) - 1; + final int line0 = Integer.parseInt(args.get(0)) - 1; + final int line1 = Integer.parseInt(args.get(1)) - 1; return Range.closedOpen(line0, line1 + 1); default: throw new IllegalArgumentException(arg); @@ -186,8 +192,8 @@ private static Range parseRange(String arg) { * Pre-processes an argument list, expanding arguments of the form {@code @filename} by reading * the content of the file and appending whitespace-delimited options to {@code arguments}. */ - private static void expandParamsFiles(Iterable args, List expanded) { - for (String arg : args) { + private static void expandParamsFiles(final Iterable args, final List expanded) { + for (final String arg : args) { if (arg.isEmpty()) { continue; } @@ -196,11 +202,11 @@ private static void expandParamsFiles(Iterable args, List expand } else if (arg.startsWith("@@")) { expanded.add(arg.substring(1)); } else { - Path path = Paths.get(arg.substring(1)); + final Path path = Paths.get(arg.substring(1)); try { - String sequence = new String(Files.readAllBytes(path), UTF_8); + final String sequence = new String(Files.readAllBytes(path), UTF_8); expandParamsFiles(ARG_SPLITTER.split(sequence), expanded); - } catch (IOException e) { + } catch (final IOException e) { throw new UncheckedIOException(path + ": could not read file: " + e.getMessage(), e); } } diff --git a/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java b/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java index 9d8ae41ca..a17c43d62 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java @@ -45,7 +45,7 @@ public String call() throws FormatterException { String formatted = formatter.formatSource(input, characterRanges(input).asRanges()); formatted = fixImports(formatted); if (parameters.reflowLongStrings()) { - formatted = StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, formatted, formatter); + formatted = StringWrapper.wrap(options.style().getMaxLineLength(), formatted, formatter); } return formatted; } diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index 841e88a8a..4326c3788 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -14,23 +14,11 @@ package com.google.googlejavaformat.java; -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Iterators; -import com.google.common.collect.Range; -import com.google.common.collect.RangeSet; -import com.google.common.collect.TreeRangeSet; +import com.google.common.collect.*; import com.google.common.io.CharSink; import com.google.common.io.CharSource; import com.google.errorprone.annotations.Immutable; -import com.google.googlejavaformat.Doc; -import com.google.googlejavaformat.DocBuilder; -import com.google.googlejavaformat.FormattingError; -import com.google.googlejavaformat.Newlines; -import com.google.googlejavaformat.Op; -import com.google.googlejavaformat.OpsBuilder; +import com.google.googlejavaformat.*; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.parser.JavacParser; import com.sun.tools.javac.parser.ParserFactory; @@ -38,18 +26,16 @@ import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Options; + +import javax.tools.*; import java.io.IOError; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import javax.tools.Diagnostic; -import javax.tools.DiagnosticCollector; -import javax.tools.DiagnosticListener; -import javax.tools.JavaFileObject; -import javax.tools.SimpleJavaFileObject; -import javax.tools.StandardLocation; + +import static java.nio.charset.StandardCharsets.UTF_8; /** * This is google-java-format, a new Java formatter that follows the Google Java Style Guide quite @@ -86,8 +72,6 @@ @Immutable public final class Formatter { - public static final int MAX_LINE_LENGTH = 100; - static final Range EMPTY_RANGE = Range.closedOpen(-1, -1); private final JavaFormatterOptions options; @@ -101,6 +85,9 @@ public Formatter(JavaFormatterOptions options) { this.options = options; } + public int getMaxLineLength() { + return this.options.style().getMaxLineLength(); + } /** * Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link * JavaInput} and the corresponding {@link JavaOutput}. @@ -168,7 +155,8 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept builder.sync(javaInput.getText().length()); builder.drain(); Doc doc = new DocBuilder().withOps(builder.build()).build(); - doc.computeBreaks(javaOutput.getCommentsHelper(), MAX_LINE_LENGTH, new Doc.State(+0, 0)); + doc.computeBreaks( + javaOutput.getCommentsHelper(), options.style().getMaxLineLength(), new Doc.State(+0, 0)); doc.write(javaOutput); javaOutput.flush(); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java index dcbaea172..5ca934e05 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java @@ -172,14 +172,18 @@ private ImportOrderer(String text, ImmutableList toks, Style style) { this.text = text; this.toks = toks; this.lineSeparator = Newlines.guessLineSeparator(text); - if (style.equals(Style.GOOGLE)) { - this.importComparator = GOOGLE_IMPORT_COMPARATOR; - this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineGoogle; - } else if (style.equals(Style.AOSP)) { - this.importComparator = AOSP_IMPORT_COMPARATOR; - this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineAosp; - } else { - throw new IllegalArgumentException("Unsupported code style: " + style); + switch (style) { + case SWISS: + case GOOGLE: + this.importComparator = GOOGLE_IMPORT_COMPARATOR; + this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineGoogle; + break; + case AOSP: + this.importComparator = AOSP_IMPORT_COMPARATOR; + this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineAosp; + break; + default: + throw new IllegalArgumentException("Unsupported code style: " + style); } } diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java index d34ecc43f..9a0c6274a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java @@ -123,8 +123,8 @@ private List wrapLineComments(List lines, int column0) { result.add(line); continue; } - while (line.length() + column0 > Formatter.MAX_LINE_LENGTH) { - int idx = Formatter.MAX_LINE_LENGTH - column0; + while (line.length() + column0 > options.style().getMaxLineLength()) { + int idx = options.style().getMaxLineLength() - column0; // only break on whitespace characters, and ignore the leading `// ` while (idx >= 2 && !CharMatcher.whitespace().matches(line.charAt(idx))) { idx--; diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java b/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java index fbb6fe7e4..abbc7796b 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java @@ -19,38 +19,44 @@ /** * Options for a google-java-format invocation. * - *

Like gofmt, the google-java-format CLI exposes no configuration options (aside from - * {@code --aosp}). + *

Like gofmt, the google-java-format CLI exposes no configuration options (aside from {@code --aosp}). * - *

The goal of google-java-format is to provide consistent formatting, and to free developers - * from arguments over style choices. It is an explicit non-goal to support developers' individual - * preferences, and in fact it would work directly against our primary goals. + *

The goal of google-java-format is to provide consistent formatting, and to free developers from arguments over + * style choices. It is an explicit non-goal to support developers' individual preferences, and in fact it would work + * directly against our primary goals. */ @Immutable public class JavaFormatterOptions { public enum Style { /** The default Google Java Style configuration. */ - GOOGLE(1), + GOOGLE(1, 100), + SWISS(1, 120), /** The AOSP-compliant configuration. */ - AOSP(2); + AOSP(2, 100); private final int indentationMultiplier; + private final int maxLineLength; - Style(int indentationMultiplier) { + Style(final int indentationMultiplier, final int maxLineLength) { this.indentationMultiplier = indentationMultiplier; + this.maxLineLength = maxLineLength; } int indentationMultiplier() { return indentationMultiplier; } + + public int getMaxLineLength() { + return maxLineLength; + } } private final Style style; private final boolean formatJavadoc; - private JavaFormatterOptions(Style style, boolean formatJavadoc) { + private JavaFormatterOptions(final Style style, final boolean formatJavadoc) { this.style = style; this.formatJavadoc = formatJavadoc; } @@ -86,12 +92,12 @@ public static class Builder { private Builder() {} - public Builder style(Style style) { + public Builder style(final Style style) { this.style = style; return this; } - public Builder formatJavadoc(boolean formatJavadoc) { + public Builder formatJavadoc(final boolean formatJavadoc) { this.formatJavadoc = formatJavadoc; return this; } diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index 953ca5860..b58242c4a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -105,7 +105,7 @@ public int format(String... args) throws UsageException { JavaFormatterOptions options = JavaFormatterOptions.builder() - .style(parameters.aosp() ? Style.AOSP : Style.GOOGLE) + .style(parameters.aosp() ? Style.AOSP : parameters.swiss() ? Style.SWISS : Style.GOOGLE) .formatJavadoc(parameters.formatJavadoc()) .build(); diff --git a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java index d801c9b86..2c5b5c3e5 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -63,7 +63,7 @@ public final class StringWrapper { /** Reflows long string literals in the given Java source code. */ public static String wrap(String input, Formatter formatter) throws FormatterException { - return StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, input, formatter); + return StringWrapper.wrap(formatter.getMaxLineLength(), input, formatter); } /** diff --git a/eclipse_plugin/META-INF/MANIFEST.MF b/eclipse_plugin/META-INF/MANIFEST.MF deleted file mode 100644 index 913245393..000000000 --- a/eclipse_plugin/META-INF/MANIFEST.MF +++ /dev/null @@ -1,15 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: google-java-format -Bundle-SymbolicName: google-java-format-eclipse-plugin;singleton:=true -Bundle-Vendor: Google -Bundle-Version: 1.13.0 -Bundle-RequiredExecutionEnvironment: JavaSE-11 -Require-Bundle: org.eclipse.jdt.core;bundle-version="3.10.0", - org.eclipse.jface, - org.eclipse.text, - org.eclipse.ui, - org.eclipse.equinox.common -Bundle-ClassPath: ., - lib/guava.jar, - lib/google-java-format.jar diff --git a/eclipse_plugin/README.md b/eclipse_plugin/README.md deleted file mode 100644 index 395a368dc..000000000 --- a/eclipse_plugin/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Google Java Format Eclipse Plugin - -## Enabling - -See https://github.com/google/google-java-format#eclipse - -## Development - -### Prerequisites - -Before building the plugin, make sure to run `mvn -tycho-versions:update-eclipse-metadata` to update the bundle version in -`META-INF/MANIFEST.MF`. - -### Building the Plugin - -1) Run `mvn clean package` in the `eclipse_plugin` directory. This will first copy the dependencies -of the plugin to `eclipse_plugin/lib/` and then triggers the tycho build that uses these -dependencies (as declared in `build.properties`) for the actual Eclipse plugin build.

-If you also want to add the build artifact to the local maven repository, you can use -`mvn clean install -Dtycho.localArtifacts=ignore` instead. Note, however, that you then must use -this build command for every build with that specific version number until you clear the build -artifact (or the -[p2-local-metadata.properties](https://wiki.eclipse.org/Tycho/Target_Platform#Locally_built_artifacts)) -from your local repository. Otherwise, you might run into issues caused by the build using an -outdated build artifact created by a previous build instead of re-building the plugin. More -information on this issue is given -[in this thread](https://www.eclipse.org/lists/tycho-user/msg00952.html) and -[this bug tracker entry](https://bugs.eclipse.org/bugs/show_bug.cgi?id=355367). - -2) You can find the built plugin in -`eclipse_plugin/target/google-java-format-eclipse-plugin-.jar` - -#### Building against a local (snapshot) release of the core - -With the current build setup, the Eclipse plugin build pulls the needed build -artifacts of the google java format core from the maven repository and copies it -into the `eclipse_plugin/lib/` directory. - -If you instead want to build against a local (snapshot) build of the core which -is not available in a maven repository (local or otherwise), you will have to -place the appropriate version into the `eclipse_plugin/lib/` directory yourself -before the build. diff --git a/eclipse_plugin/build.properties b/eclipse_plugin/build.properties deleted file mode 100644 index dd1d835c5..000000000 --- a/eclipse_plugin/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -source.. = src/ -output.. = target/classes -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - lib/guava.jar,\ - lib/google-java-format.jar diff --git a/eclipse_plugin/plugin.xml b/eclipse_plugin/plugin.xml deleted file mode 100644 index 1fdfb6e41..000000000 --- a/eclipse_plugin/plugin.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - diff --git a/eclipse_plugin/pom.xml b/eclipse_plugin/pom.xml deleted file mode 100644 index 9e6acdac0..000000000 --- a/eclipse_plugin/pom.xml +++ /dev/null @@ -1,141 +0,0 @@ - - - - 4.0.0 - - com.google.googlejavaformat - google-java-format-eclipse-plugin - eclipse-plugin - 1.13.0 - - Google Java Format Plugin for Eclipse 4.5+ - - - A Java source code formatter plugin for Eclipse that follows Google Java Style. - - - - UTF-8 - 3.0.0 - - - - - com.google.googlejavaformat - google-java-format - ${project.version} - - - - - - mars - p2 - https://download.eclipse.org/releases/mars - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 3.3.0 - - - copy-dependencies - initialize - - copy-dependencies - - - - - lib - runtime - true - true - true - guava,google-java-format - - - - - org.eclipse.tycho - tycho-maven-plugin - ${tycho-version} - true - - - - org.eclipse.tycho - tycho-versions-plugin - ${tycho-version} - - ${project.version} - - - - - org.eclipse.tycho - target-platform-configuration - ${tycho-version} - - - - linux - gtk - x86 - - - linux - gtk - x86_64 - - - win32 - win32 - x86 - - - win32 - win32 - x86_64 - - - macosx - cocoa - x86_64 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 11 - 11 - - - - - diff --git a/eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java b/eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java deleted file mode 100644 index c300514be..000000000 --- a/eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright 2017 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 com.google.common.base.Preconditions; -import com.google.common.collect.Range; -import com.google.googlejavaformat.java.SnippetFormatter.SnippetKind; -import java.util.ArrayList; -import java.util.List; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.formatter.CodeFormatter; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; - -/** Runs the Google Java formatter on the given code. */ -public class GoogleJavaFormatter extends CodeFormatter { - - private static final int INDENTATION_SIZE = 2; - - @Override - public TextEdit format( - int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { - IRegion[] regions = new IRegion[] {new Region(offset, length)}; - return formatInternal(kind, source, regions, indentationLevel); - } - - @Override - public TextEdit format( - int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator) { - return formatInternal(kind, source, regions, indentationLevel); - } - - @Override - public String createIndentationString(int indentationLevel) { - Preconditions.checkArgument( - indentationLevel >= 0, - "Indentation level cannot be less than zero. Given: %s", - indentationLevel); - int spaces = indentationLevel * INDENTATION_SIZE; - StringBuilder buf = new StringBuilder(spaces); - for (int i = 0; i < spaces; i++) { - buf.append(' '); - } - return buf.toString(); - } - - /** Runs the Google Java formatter on the given source, with only the given ranges specified. */ - private TextEdit formatInternal(int kind, String source, IRegion[] regions, int initialIndent) { - try { - boolean includeComments = - (kind & CodeFormatter.F_INCLUDE_COMMENTS) == CodeFormatter.F_INCLUDE_COMMENTS; - kind &= ~CodeFormatter.F_INCLUDE_COMMENTS; - SnippetKind snippetKind; - switch (kind) { - case ASTParser.K_EXPRESSION: - snippetKind = SnippetKind.EXPRESSION; - break; - case ASTParser.K_STATEMENTS: - snippetKind = SnippetKind.STATEMENTS; - break; - case ASTParser.K_CLASS_BODY_DECLARATIONS: - snippetKind = SnippetKind.CLASS_BODY_DECLARATIONS; - break; - case ASTParser.K_COMPILATION_UNIT: - snippetKind = SnippetKind.COMPILATION_UNIT; - break; - default: - throw new IllegalArgumentException(String.format("Unknown snippet kind: %d", kind)); - } - List replacements = - new SnippetFormatter() - .format( - snippetKind, source, rangesFromRegions(regions), initialIndent, includeComments); - if (idempotent(source, regions, replacements)) { - // Do not create edits if there's no diff. - return null; - } - // Convert replacements to text edits. - return editFromReplacements(replacements); - } catch (IllegalArgumentException | FormatterException exception) { - // Do not format on errors. - return null; - } - } - - private List> rangesFromRegions(IRegion[] regions) { - List> ranges = new ArrayList<>(); - for (IRegion region : regions) { - ranges.add(Range.closedOpen(region.getOffset(), region.getOffset() + region.getLength())); - } - return ranges; - } - - /** @return {@code true} if input and output texts are equal, else {@code false}. */ - private boolean idempotent(String source, IRegion[] regions, List replacements) { - // This implementation only checks for single replacement. - if (replacements.size() == 1) { - Replacement replacement = replacements.get(0); - String output = replacement.getReplacementString(); - // Entire source case: input = output, nothing changed. - if (output.equals(source)) { - return true; - } - // Single region and single replacement case: if they are equal, nothing changed. - if (regions.length == 1) { - Range range = replacement.getReplaceRange(); - String snippet = source.substring(range.lowerEndpoint(), range.upperEndpoint()); - if (output.equals(snippet)) { - return true; - } - } - } - return false; - } - - private TextEdit editFromReplacements(List replacements) { - // Split the replacements that cross line boundaries. - TextEdit edit = new MultiTextEdit(); - for (Replacement replacement : replacements) { - Range replaceRange = replacement.getReplaceRange(); - edit.addChild( - new ReplaceEdit( - replaceRange.lowerEndpoint(), - replaceRange.upperEndpoint() - replaceRange.lowerEndpoint(), - replacement.getReplacementString())); - } - return edit; - } -} diff --git a/idea_plugin/.gitignore b/idea_plugin/.gitignore deleted file mode 100644 index 16bc65a53..000000000 --- a/idea_plugin/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -build -.gradle -gradle -gradlew -gradlew.bat \ No newline at end of file diff --git a/idea_plugin/build.gradle b/idea_plugin/build.gradle deleted file mode 100644 index 294d77e73..000000000 --- a/idea_plugin/build.gradle +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * 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. - */ - -plugins { - id "org.jetbrains.intellij" version "1.4.0" -} - -repositories { - mavenCentral() -} - -ext { - googleJavaFormatVersion = "1.15.0" -} - -apply plugin: "org.jetbrains.intellij" -apply plugin: "java" - -sourceCompatibility = JavaVersion.VERSION_11 -targetCompatibility = JavaVersion.VERSION_11 - -intellij { - pluginName = "google-java-format" - plugins = ["java"] - version = "221.3427-EAP-CANDIDATE-SNAPSHOT" -} - -patchPluginXml { - pluginDescription = "Formats source code using the google-java-format tool. This version of " + - "the plugin uses version ${googleJavaFormatVersion} of the tool." - version.set("${googleJavaFormatVersion}.0") - sinceBuild = "203" - untilBuild = "" -} - -publishPlugin { - token = project.ext.properties.jetbrainsPluginRepoToken -} - -sourceSets { - main { - java.srcDir "src" - resources.srcDir "resources" - } -} - -dependencies { - implementation "com.google.googlejavaformat:google-java-format:${googleJavaFormatVersion}" -} diff --git a/idea_plugin/resources/META-INF/plugin.xml b/idea_plugin/resources/META-INF/plugin.xml deleted file mode 100644 index 42d5f3b31..000000000 --- a/idea_plugin/resources/META-INF/plugin.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - google-java-format - google-java-format - - Google - - - - com.intellij.java - - -

1.15.0.0
-
Updated to use google-java-format 1.15.0.
-
1.14.0.0
-
Updated to use google-java-format 1.14.
-
1.13.0.0
-
Updated to use google-java-format 1.13.
-
1.12.0.0
-
Updated to use google-java-format 1.12.
-
1.11.0.0
-
Updated to use google-java-format 1.11.
-
1.10.0.0
-
Updated to use google-java-format 1.10.
-
1.9.0.0
-
Updated to use google-java-format 1.9.
-
1.8.0.1
-
Fixed support for 2020.2 IDEs.
-
1.8.0.0
-
Updated to use google-java-format 1.8.
-
1.7.0.5
-
Added a version for 2020.1+ IDEs.
-
1.7.0.4
-
Marked the plugin as being incompatible with 2020.1+ IDEs.
-
1.7.0.3
-
Fixed the plugin on 2019.3 IDEs.
-
1.7.0.2
-
Added support for all IDEs after 2017.3.
-
1.7.0.1
-
Added support for 2019.1 IDEs.
-
1.7.0.0
-
Upgraded to google-java-format 1.7.
- - ]]> - - - - - - - - - - - - - diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java b/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java deleted file mode 100644 index af5da957a..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.intellij.formatting.FormattingMode; -import com.intellij.lang.ASTNode; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.fileTypes.FileType; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Computable; -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.codeStyle.ChangedRangesInfo; -import com.intellij.psi.codeStyle.CodeStyleManager; -import com.intellij.psi.codeStyle.DocCommentSettings; -import com.intellij.psi.codeStyle.FormattingModeAwareIndentAdjuster; -import com.intellij.psi.codeStyle.Indent; -import com.intellij.util.IncorrectOperationException; -import com.intellij.util.ThrowableRunnable; -import java.util.Collection; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.jetbrains.annotations.NotNull; - -/** - * Decorates the {@link CodeStyleManager} abstract class by delegating to a concrete implementation - * instance (likely IntelliJ's default instance). - */ -@SuppressWarnings("deprecation") -class CodeStyleManagerDecorator extends CodeStyleManager - implements FormattingModeAwareIndentAdjuster { - - private final CodeStyleManager delegate; - - CodeStyleManagerDecorator(CodeStyleManager delegate) { - this.delegate = delegate; - } - - CodeStyleManager getDelegate() { - return delegate; - } - - @Override - public @NotNull Project getProject() { - return delegate.getProject(); - } - - @Override - public @NotNull PsiElement reformat(@NotNull PsiElement element) - throws IncorrectOperationException { - return delegate.reformat(element); - } - - @Override - public @NotNull PsiElement reformat(@NotNull PsiElement element, boolean canChangeWhiteSpacesOnly) - throws IncorrectOperationException { - return delegate.reformat(element, canChangeWhiteSpacesOnly); - } - - @Override - public PsiElement reformatRange(@NotNull PsiElement element, int startOffset, int endOffset) - throws IncorrectOperationException { - return delegate.reformatRange(element, startOffset, endOffset); - } - - @Override - public PsiElement reformatRange( - @NotNull PsiElement element, int startOffset, int endOffset, boolean canChangeWhiteSpacesOnly) - throws IncorrectOperationException { - return delegate.reformatRange(element, startOffset, endOffset, canChangeWhiteSpacesOnly); - } - - @Override - public void reformatText(@NotNull PsiFile file, int startOffset, int endOffset) - throws IncorrectOperationException { - delegate.reformatText(file, startOffset, endOffset); - } - - @Override - public void reformatText(@NotNull PsiFile file, @NotNull Collection ranges) - throws IncorrectOperationException { - delegate.reformatText(file, ranges); - } - - @Override - public void reformatTextWithContext( - @NotNull PsiFile psiFile, @NotNull ChangedRangesInfo changedRangesInfo) - throws IncorrectOperationException { - delegate.reformatTextWithContext(psiFile, changedRangesInfo); - } - - @Override - public void reformatTextWithContext( - @NotNull PsiFile file, @NotNull Collection ranges) - throws IncorrectOperationException { - delegate.reformatTextWithContext(file, ranges); - } - - @Override - public void adjustLineIndent(@NotNull PsiFile file, TextRange rangeToAdjust) - throws IncorrectOperationException { - delegate.adjustLineIndent(file, rangeToAdjust); - } - - @Override - public int adjustLineIndent(@NotNull PsiFile file, int offset) - throws IncorrectOperationException { - return delegate.adjustLineIndent(file, offset); - } - - @Override - public int adjustLineIndent(@NotNull Document document, int offset) { - return delegate.adjustLineIndent(document, offset); - } - - public void scheduleIndentAdjustment(@NotNull Document document, int offset) { - delegate.scheduleIndentAdjustment(document, offset); - } - - @Override - public boolean isLineToBeIndented(@NotNull PsiFile file, int offset) { - return delegate.isLineToBeIndented(file, offset); - } - - @Override - @Nullable - public String getLineIndent(@NotNull PsiFile file, int offset) { - return delegate.getLineIndent(file, offset); - } - - @Override - @Nullable - public String getLineIndent(@NotNull PsiFile file, int offset, FormattingMode mode) { - return delegate.getLineIndent(file, offset, mode); - } - - @Override - @Nullable - public String getLineIndent(@NotNull Document document, int offset) { - return delegate.getLineIndent(document, offset); - } - - @Override - public Indent getIndent(String text, FileType fileType) { - return delegate.getIndent(text, fileType); - } - - @Override - public String fillIndent(Indent indent, FileType fileType) { - return delegate.fillIndent(indent, fileType); - } - - @Override - public Indent zeroIndent() { - return delegate.zeroIndent(); - } - - @Override - public void reformatNewlyAddedElement(@NotNull ASTNode block, @NotNull ASTNode addedElement) - throws IncorrectOperationException { - delegate.reformatNewlyAddedElement(block, addedElement); - } - - @Override - public boolean isSequentialProcessingAllowed() { - return delegate.isSequentialProcessingAllowed(); - } - - @Override - public void performActionWithFormatterDisabled(Runnable r) { - delegate.performActionWithFormatterDisabled(r); - } - - @Override - public void performActionWithFormatterDisabled(ThrowableRunnable r) - throws T { - delegate.performActionWithFormatterDisabled(r); - } - - @Override - public T performActionWithFormatterDisabled(Computable r) { - return delegate.performActionWithFormatterDisabled(r); - } - - @Override - public int getSpacing(@NotNull PsiFile file, int offset) { - return delegate.getSpacing(file, offset); - } - - @Override - public int getMinLineFeeds(@NotNull PsiFile file, int offset) { - return delegate.getMinLineFeeds(file, offset); - } - - @Override - public void runWithDocCommentFormattingDisabled( - @NotNull PsiFile file, @NotNull Runnable runnable) { - delegate.runWithDocCommentFormattingDisabled(file, runnable); - } - - @Override - public @NotNull DocCommentSettings getDocCommentSettings(@NotNull PsiFile file) { - return delegate.getDocCommentSettings(file); - } - - // From FormattingModeAwareIndentAdjuster - - /** Uses same fallback as {@link CodeStyleManager#getCurrentFormattingMode}. */ - @Override - public FormattingMode getCurrentFormattingMode() { - if (delegate instanceof FormattingModeAwareIndentAdjuster) { - return ((FormattingModeAwareIndentAdjuster) delegate).getCurrentFormattingMode(); - } - return FormattingMode.REFORMAT; - } - - @Override - public int adjustLineIndent( - final @NotNull Document document, final int offset, FormattingMode mode) - throws IncorrectOperationException { - if (delegate instanceof FormattingModeAwareIndentAdjuster) { - return ((FormattingModeAwareIndentAdjuster) delegate) - .adjustLineIndent(document, offset, mode); - } - return offset; - } - - @Override - public void scheduleReformatWhenSettingsComputed(@NotNull PsiFile file) { - delegate.scheduleReformatWhenSettingsComputed(file); - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/FormatterUtil.java b/idea_plugin/src/com/google/googlejavaformat/intellij/FormatterUtil.java deleted file mode 100644 index a5e69c93d..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/FormatterUtil.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import static com.google.common.base.Preconditions.checkState; - -import com.google.common.collect.BoundType; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Range; -import com.google.googlejavaformat.java.Formatter; -import com.google.googlejavaformat.java.FormatterException; -import com.intellij.openapi.util.TextRange; -import java.util.Collection; -import java.util.Map; -import java.util.stream.Collectors; - -final class FormatterUtil { - - private FormatterUtil() {} - - static Map getReplacements( - Formatter formatter, String text, Collection ranges) { - try { - ImmutableMap.Builder 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(); - } - } - - private static Collection> toRanges(Collection textRanges) { - return textRanges.stream() - .map(textRange -> Range.closedOpen(textRange.getStartOffset(), textRange.getEndOffset())) - .collect(Collectors.toList()); - } - - private static TextRange toTextRange(Range range) { - checkState( - range.lowerBoundType().equals(BoundType.CLOSED) - && range.upperBoundType().equals(BoundType.OPEN)); - return new TextRange(range.lowerEndpoint(), range.upperEndpoint()); - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatCodeStyleManager.java b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatCodeStyleManager.java deleted file mode 100644 index 3d56743ee..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatCodeStyleManager.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import static java.util.Comparator.comparing; - -import com.google.common.collect.ImmutableList; -import com.google.googlejavaformat.java.Formatter; -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.google.googlejavaformat.java.JavaFormatterOptions.Style; -import com.intellij.ide.highlighter.JavaFileType; -import com.intellij.openapi.application.ApplicationManager; -import com.intellij.openapi.command.WriteCommandAction; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiDocumentManager; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.codeStyle.ChangedRangesInfo; -import com.intellij.psi.codeStyle.CodeStyleManager; -import com.intellij.psi.impl.CheckUtil; -import com.intellij.util.IncorrectOperationException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; -import org.jetbrains.annotations.NotNull; - -/** - * A {@link CodeStyleManager} implementation which formats .java files with google-java-format. - * Formatting of all other types of files is delegated to IntelliJ's default implementation. - */ -class GoogleJavaFormatCodeStyleManager extends CodeStyleManagerDecorator { - - public GoogleJavaFormatCodeStyleManager(@NotNull CodeStyleManager original) { - super(original); - } - - @Override - public void reformatText(@NotNull PsiFile file, int startOffset, int endOffset) - throws IncorrectOperationException { - if (overrideFormatterForFile(file)) { - formatInternal(file, ImmutableList.of(new TextRange(startOffset, endOffset))); - } else { - super.reformatText(file, startOffset, endOffset); - } - } - - @Override - public void reformatText(@NotNull PsiFile file, @NotNull Collection ranges) - throws IncorrectOperationException { - if (overrideFormatterForFile(file)) { - formatInternal(file, ranges); - } else { - super.reformatText(file, ranges); - } - } - - @Override - public void reformatTextWithContext(@NotNull PsiFile file, @NotNull ChangedRangesInfo info) - throws IncorrectOperationException { - List ranges = new ArrayList<>(); - if (info.insertedRanges != null) { - ranges.addAll(info.insertedRanges); - } - ranges.addAll(info.allChangedRanges); - reformatTextWithContext(file, ranges); - } - - @Override - public void reformatTextWithContext( - @NotNull PsiFile file, @NotNull Collection ranges) { - if (overrideFormatterForFile(file)) { - formatInternal(file, ranges); - } else { - super.reformatTextWithContext(file, ranges); - } - } - - @Override - public PsiElement reformatRange( - @NotNull PsiElement element, - int startOffset, - int endOffset, - boolean canChangeWhiteSpacesOnly) { - // Only handle elements that are PsiFile for now -- otherwise we need to search for some - // element within the file at new locations given the original startOffset and endOffsets - // to serve as the return value. - PsiFile file = element instanceof PsiFile ? (PsiFile) element : null; - if (file != null && canChangeWhiteSpacesOnly && overrideFormatterForFile(file)) { - formatInternal(file, ImmutableList.of(new TextRange(startOffset, endOffset))); - return file; - } else { - return super.reformatRange(element, startOffset, endOffset, canChangeWhiteSpacesOnly); - } - } - - /** Return whether this formatter can handle formatting the given file. */ - private boolean overrideFormatterForFile(PsiFile file) { - return JavaFileType.INSTANCE.equals(file.getFileType()) - && GoogleJavaFormatSettings.getInstance(getProject()).isEnabled(); - } - - private void formatInternal(PsiFile file, Collection ranges) { - ApplicationManager.getApplication().assertWriteAccessAllowed(); - PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject()); - documentManager.commitAllDocuments(); - CheckUtil.checkWritable(file); - - Document document = documentManager.getDocument(file); - - if (document == null) { - return; - } - // If there are postponed PSI changes (e.g., during a refactoring), just abort. - // If we apply them now, then the incoming text ranges may no longer be valid. - if (documentManager.isDocumentBlockedByPsi(document)) { - return; - } - - format(document, ranges); - } - - /** - * Format the ranges of the given document. - * - *

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 ranges) { - Style style = GoogleJavaFormatSettings.getInstance(getProject()).getStyle(); - Formatter formatter = new Formatter(JavaFormatterOptions.builder().style(style).build()); - performReplacements( - document, FormatterUtil.getReplacements(formatter, document.getText(), ranges)); - } - - private void performReplacements( - final Document document, final Map replacements) { - - if (replacements.isEmpty()) { - return; - } - - TreeMap sorted = new TreeMap<>(comparing(TextRange::getStartOffset)); - sorted.putAll(replacements); - WriteCommandAction.runWriteCommandAction( - getProject(), - () -> { - for (Entry entry : sorted.descendingMap().entrySet()) { - document.replaceString( - entry.getKey().getStartOffset(), entry.getKey().getEndOffset(), entry.getValue()); - } - PsiDocumentManager.getInstance(getProject()).commitDocument(document); - }); - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form deleted file mode 100644 index 1db1d7920..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form +++ /dev/null @@ -1,40 +0,0 @@ - -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java deleted file mode 100644 index 2f34b7471..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.googlejavaformat.intellij.GoogleJavaFormatSettings.EnabledState; -import com.intellij.openapi.options.BaseConfigurable; -import com.intellij.openapi.options.ConfigurationException; -import com.intellij.openapi.options.SearchableConfigurable; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.ComboBox; -import com.intellij.uiDesigner.core.GridConstraints; -import com.intellij.uiDesigner.core.GridLayoutManager; -import com.intellij.uiDesigner.core.Spacer; -import java.awt.Insets; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.NotNull; - -class GoogleJavaFormatConfigurable extends BaseConfigurable implements SearchableConfigurable { - - private final Project project; - private JPanel panel; - private JCheckBox enable; - private JComboBox styleComboBox; - - public GoogleJavaFormatConfigurable(Project project) { - this.project = project; - } - - @NotNull - @Override - public String getId() { - return "google-java-format.settings"; - } - - @Nullable - @Override - public Runnable enableSearch(String option) { - return null; - } - - @Nls - @Override - public String getDisplayName() { - return "google-java-format Settings"; - } - - @Nullable - @Override - public String getHelpTopic() { - return null; - } - - @Nullable - @Override - public JComponent createComponent() { - return panel; - } - - @Override - public void apply() throws ConfigurationException { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - settings.setEnabled(enable.isSelected() ? EnabledState.ENABLED : getDisabledState()); - settings.setStyle(((UiFormatterStyle) styleComboBox.getSelectedItem()).convert()); - } - - private EnabledState getDisabledState() { - // The default settings (inherited by new projects) are either 'enabled' or - // 'show notification'. There's no way to default new projects to disabled. If someone wants - // that, we can add another checkbox, I suppose. - return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED; - } - - @Override - public void reset() { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - enable.setSelected(settings.isEnabled()); - styleComboBox.setSelectedItem(UiFormatterStyle.convert(settings.getStyle())); - } - - @Override - public boolean isModified() { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - return enable.isSelected() != settings.isEnabled() - || !styleComboBox.getSelectedItem().equals(UiFormatterStyle.convert(settings.getStyle())); - } - - @Override - public void disposeUIResources() {} - - private void createUIComponents() { - styleComboBox = new ComboBox<>(UiFormatterStyle.values()); - } - - { - // GUI initializer generated by IntelliJ IDEA GUI Designer - // >>> IMPORTANT!! <<< - // DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); - } - - /** - * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR - * call it in your code! - * - * @noinspection ALL - */ - private void $$$setupUI$$$() { - createUIComponents(); - panel = new JPanel(); - panel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1)); - enable = new JCheckBox(); - enable.setText("Enable google-java-format"); - panel.add( - enable, - new GridConstraints( - 0, - 0, - 1, - 2, - GridConstraints.ANCHOR_WEST, - GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, - null, - null, - null, - 0, - false)); - final Spacer spacer1 = new Spacer(); - panel.add( - spacer1, - new GridConstraints( - 2, - 0, - 1, - 2, - GridConstraints.ANCHOR_CENTER, - GridConstraints.FILL_VERTICAL, - 1, - GridConstraints.SIZEPOLICY_WANT_GROW, - null, - null, - null, - 0, - false)); - final JLabel label1 = new JLabel(); - label1.setText("Code style"); - panel.add( - label1, - new GridConstraints( - 1, - 0, - 1, - 1, - GridConstraints.ANCHOR_WEST, - GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_FIXED, - GridConstraints.SIZEPOLICY_FIXED, - null, - null, - null, - 0, - false)); - panel.add( - styleComboBox, - new GridConstraints( - 1, - 1, - 1, - 1, - GridConstraints.ANCHOR_WEST, - GridConstraints.FILL_HORIZONTAL, - GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, - null, - null, - null, - 1, - false)); - } - - /** @noinspection ALL */ - public JComponent $$$getRootComponent$$$() { - return panel; - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatInstaller.java b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatInstaller.java deleted file mode 100644 index c60673602..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatInstaller.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import static com.google.common.base.Preconditions.checkState; - -import com.intellij.ide.plugins.IdeaPluginDescriptor; -import com.intellij.ide.plugins.PluginManagerCore; -import com.intellij.openapi.extensions.PluginId; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.project.ProjectManagerListener; -import com.intellij.psi.codeStyle.CodeStyleManager; -import com.intellij.serviceContainer.ComponentManagerImpl; -import org.jetbrains.annotations.NotNull; - -/** - * A component that replaces the default IntelliJ {@link CodeStyleManager} with one that formats via - * google-java-format. - */ -final class GoogleJavaFormatInstaller implements ProjectManagerListener { - - @Override - public void projectOpened(@NotNull Project project) { - installFormatter(project); - } - - private static void installFormatter(Project project) { - CodeStyleManager currentManager = CodeStyleManager.getInstance(project); - - if (currentManager instanceof GoogleJavaFormatCodeStyleManager) { - currentManager = ((GoogleJavaFormatCodeStyleManager) currentManager).getDelegate(); - } - - setManager(project, new GoogleJavaFormatCodeStyleManager(currentManager)); - } - - private static void setManager(Project project, CodeStyleManager newManager) { - ComponentManagerImpl platformComponentManager = (ComponentManagerImpl) project; - IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(PluginId.getId("google-java-format")); - checkState(plugin != null, "Couldn't locate our own PluginDescriptor."); - platformComponentManager.registerServiceInstance(CodeStyleManager.class, newManager, plugin); - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java deleted file mode 100644 index 1e92a4bdd..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.intellij.openapi.components.PersistentStateComponent; -import com.intellij.openapi.components.ServiceManager; -import com.intellij.openapi.components.State; -import com.intellij.openapi.components.Storage; -import com.intellij.openapi.project.Project; -import org.checkerframework.checker.nullness.qual.Nullable; -import org.jetbrains.annotations.NotNull; - -@State( - name = "GoogleJavaFormatSettings", - storages = {@Storage("google-java-format.xml")}) -class GoogleJavaFormatSettings implements PersistentStateComponent { - - private State state = new State(); - - static GoogleJavaFormatSettings getInstance(Project project) { - return ServiceManager.getService(project, GoogleJavaFormatSettings.class); - } - - @Nullable - @Override - public State getState() { - return state; - } - - @Override - public void loadState(@NotNull State state) { - this.state = state; - } - - boolean isEnabled() { - return state.enabled.equals(EnabledState.ENABLED); - } - - void setEnabled(boolean enabled) { - setEnabled(enabled ? EnabledState.ENABLED : EnabledState.DISABLED); - } - - void setEnabled(EnabledState enabled) { - state.enabled = enabled; - } - - boolean isUninitialized() { - return state.enabled.equals(EnabledState.UNKNOWN); - } - - JavaFormatterOptions.Style getStyle() { - return state.style; - } - - void setStyle(JavaFormatterOptions.Style style) { - state.style = style; - } - - enum EnabledState { - UNKNOWN, - ENABLED, - DISABLED - } - - static class State { - - private EnabledState enabled = EnabledState.UNKNOWN; - public JavaFormatterOptions.Style style = JavaFormatterOptions.Style.GOOGLE; - - // enabled used to be a boolean so we use bean property methods for backwards compatibility - public void setEnabled(@Nullable String enabledStr) { - if (enabledStr == null) { - enabled = EnabledState.UNKNOWN; - } else if (Boolean.parseBoolean(enabledStr)) { - enabled = EnabledState.ENABLED; - } else { - enabled = EnabledState.DISABLED; - } - } - - public String getEnabled() { - switch (enabled) { - case ENABLED: - return "true"; - case DISABLED: - return "false"; - default: - return null; - } - } - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java b/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java deleted file mode 100644 index 1906347f7..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.intellij.notification.Notification; -import com.intellij.notification.NotificationGroup; -import com.intellij.notification.NotificationGroupManager; -import com.intellij.notification.NotificationType; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.project.ProjectManagerListener; -import org.jetbrains.annotations.NotNull; - -final class InitialConfigurationProjectManagerListener implements ProjectManagerListener { - - private static final String NOTIFICATION_TITLE = "Enable google-java-format"; - private static final NotificationGroup NOTIFICATION_GROUP = - NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_TITLE); - - @Override - public void projectOpened(@NotNull Project project) { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - - if (settings.isUninitialized()) { - settings.setEnabled(false); - displayNewUserNotification(project, settings); - } - } - - private void displayNewUserNotification(Project project, GoogleJavaFormatSettings settings) { - Notification notification = - new Notification( - NOTIFICATION_GROUP.getDisplayId(), - NOTIFICATION_TITLE, - "The google-java-format plugin is disabled by default. " - + "Enable for this project.", - NotificationType.INFORMATION, - (n, e) -> { - settings.setEnabled(true); - n.expire(); - }); - notification.notify(project); - } -} diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/UiFormatterStyle.java b/idea_plugin/src/com/google/googlejavaformat/intellij/UiFormatterStyle.java deleted file mode 100644 index 24ed6f62c..000000000 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/UiFormatterStyle.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.google.googlejavaformat.java.JavaFormatterOptions.Style; -import java.util.Arrays; -import java.util.Objects; - -/** Configuration options for the formatting style. */ -enum UiFormatterStyle { - GOOGLE("Default Google Java style", Style.GOOGLE), - AOSP("Android Open Source Project (AOSP) style", Style.AOSP); - - private final String description; - private final JavaFormatterOptions.Style style; - - UiFormatterStyle(String description, JavaFormatterOptions.Style style) { - this.description = description; - this.style = style; - } - - @Override - public String toString() { - return description; - } - - public JavaFormatterOptions.Style convert() { - return style; - } - - static UiFormatterStyle convert(JavaFormatterOptions.Style style) { - return Arrays.stream(UiFormatterStyle.values()) - .filter(value -> Objects.equals(value.style, style)) - .findFirst() - .get(); - } -} diff --git a/pom.xml b/pom.xml index 150173ee6..a35f0488c 100644 --- a/pom.xml +++ b/pom.xml @@ -18,222 +18,222 @@ - 4.0.0 + 4.0.0 - com.google.googlejavaformat - google-java-format-parent - pom - HEAD-SNAPSHOT + com.github.mrdolch.googlejavaformat + google-java-format-parent + pom + 1.15.0-SNAPSHOT - - core - + + core + - Google Java Format Parent + Google Java Format Parent - - A Java source code formatter that follows Google Java Style. - + + A Java source code formatter that follows Google Java Style. + - https://github.com/google/google-java-format + https://github.com/google/google-java-format - 2015 + 2015 - - Google Inc. - http://www.google.com/ - + + Google Inc. + http://www.google.com/ + - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + - - - jdd - John DeTreville - jdd@google.com - Google Inc. - http://www.google.com/ - - owner - developer - - -8 - - + + + jdd + John DeTreville + jdd@google.com + Google Inc. + http://www.google.com/ + + owner + developer + + -8 + + - - http://github.com/google/google-java-format/ - scm:git:git://github.com/google/google-java-format.git - scm:git:ssh://git@github.com/google/google-java-format.git - HEAD - + + http://github.com/google/google-java-format/ + scm:git:git://github.com/google/google-java-format.git + scm:git:ssh://git@github.com/google/google-java-format.git + HEAD + - - GitHub Issues - http://github.com/google/google-java-format/issues - + + GitHub Issues + http://github.com/google/google-java-format/issues + - - 3.0.3 - + + 3.0.3 + - - UTF-8 - 1.8 - 31.1-jre - 1.1.3 - 3.21.2 - 2.16 - 1.9 - 1.0.1 - 3.4.0 - 3.2.1 - + + UTF-8 + 1.8 + 31.1-jre + 1.1.3 + 3.21.2 + 2.16 + 1.9 + 1.0.1 + 3.4.0 + 3.2.1 + - - - - - com.google.guava - guava - ${guava.version} - + + + + + com.google.guava + guava + ${guava.version} + - - - org.checkerframework - checker-qual - ${checker.version} - - - com.google.errorprone - error_prone_annotations - ${errorprone.version} - - - com.google.auto.value - auto-value-annotations - ${auto-value.version} - - - com.google.auto.service - auto-service-annotations - ${auto-service.version} - + + + org.checkerframework + checker-qual + ${checker.version} + + + com.google.errorprone + error_prone_annotations + ${errorprone.version} + + + com.google.auto.value + auto-value-annotations + ${auto-value.version} + + + com.google.auto.service + auto-service-annotations + ${auto-service.version} + - - - junit - junit - 4.13.2 - test - - - com.google.guava - guava-testlib - ${guava.version} - test - - - com.google.truth - truth - ${truth.version} - test - - - com.google.truth.extensions - truth-java8-extension - ${truth.version} - test - - - + + + junit + junit + 4.13.2 + test + + + com.google.guava + guava-testlib + ${guava.version} + test + + + com.google.truth + truth + ${truth.version} + test + + + com.google.truth.extensions + truth-java8-extension + ${truth.version} + test + + + - - - - - maven-compiler-plugin - 3.9.0 - - - maven-jar-plugin - 3.2.2 - - - maven-source-plugin - 3.2.1 - - - maven-javadoc-plugin - 3.4.0 - - - maven-gpg-plugin - 3.0.1 - - - org.apache.felix - maven-bundle-plugin - 5.1.4 - - - + + + + + maven-compiler-plugin + 3.9.0 + + + maven-jar-plugin + 3.2.2 + + + maven-source-plugin + 3.2.1 + + + maven-javadoc-plugin + 3.4.0 + + + maven-gpg-plugin + 3.0.1 + + + org.apache.felix + maven-bundle-plugin + 5.1.4 + + + - - - maven-compiler-plugin - - ${java.version} - ${java.version} - UTF-8 - - - -XDcompilePolicy=simple - -Xplugin:ErrorProne - --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED - - - - com.google.errorprone - error_prone_core - ${errorprone.version} - - - com.google.auto.value - auto-value - ${auto-value.version} - - - com.google.auto.service - auto-service - ${auto-service.version} - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - com.google.googlejavaformat.java.Main - - - + -XDcompilePolicy=simple + -Xplugin:ErrorProne + --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + + + + com.google.errorprone + error_prone_core + ${errorprone.version} + + + com.google.auto.value + auto-value + ${auto-value.version} + + + com.google.auto.service + auto-service + ${auto-service.version} + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.google.googlejavaformat.java.Main + + + jdk.compiler/com.sun.tools.javac.api jdk.compiler/com.sun.tools.javac.file jdk.compiler/com.sun.tools.javac.main jdk.compiler/com.sun.tools.javac.tree jdk.compiler/com.sun.tools.javac.util - jdk.compiler/com.sun.tools.javac.code jdk.compiler/com.sun.tools.javac.comp - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.4.0 - - none - - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - -Xmx1024m - --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED - --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED - --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED - --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED - - - - - + jdk.compiler/com.sun.tools.javac.code jdk.compiler/com.sun.tools.javac.comp + + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.4.0 + + none + + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + -Xmx1024m + --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED + + + + + - - - sonatype-nexus-snapshots - Sonatype Nexus Snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - - sonatype-nexus-staging - Nexus Release Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - + + + sonatype-nexus-snapshots + Sonatype Nexus Snapshots + https://oss.sonatype.org/content/repositories/snapshots/ + + + sonatype-nexus-staging + Nexus Release Repository + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + - - - sonatype-oss-release - - - - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 3.0.1 - - - sign-artifacts - verify - - sign - - - - - - - - - eclipse - - [17,) - - - eclipse_plugin - - - + + + sonatype-oss-release + + + + org.apache.maven.plugins + maven-source-plugin + ${maven-source-plugin.version} + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.0.1 + + + sign-artifacts + verify + + sign + + + + + + + + From 8768ba2ed9dacdf0409a71768c98a0f8368da694 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Thu, 8 Dec 2022 09:47:10 +0100 Subject: [PATCH 002/107] Fix artifact name and do release --- .github/dependabot.yml | 6 --- .github/workflows/ci.yml | 89 ----------------------------------- .github/workflows/release.yml | 74 ----------------------------- core/pom.xml | 6 +-- pom.xml | 4 +- 5 files changed, 5 insertions(+), 174 deletions(-) delete mode 100644 .github/dependabot.yml delete mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/release.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index daec31893..000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,6 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "maven" - directory: "/" - schedule: - interval: "daily" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index 79a260eab..000000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright 2020 The Error Prone Authors. -# -# 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. - -name: CI - -on: - push: - branches: - - master - pull_request: - branches: - - master - -jobs: - test: - name: "JDK ${{ matrix.java }} on ${{ matrix.os }}" - strategy: - fail-fast: false - matrix: - os: [ ubuntu-latest ] - java: [ 19, 17, 11 ] - experimental: [ false ] - include: - # Only test on macos and windows with a single recent JDK to avoid a - # combinatorial explosion of test configurations. - - os: macos-latest - java: 19 - experimental: false - - os: windows-latest - java: 19 - experimental: false - - os: ubuntu-latest - java: 20-ea - experimental: true - runs-on: ${{ matrix.os }} - continue-on-error: ${{ matrix.experimental }} - steps: - - name: Cancel previous - uses: styfle/cancel-workflow-action@0.9.1 - with: - access_token: ${{ github.token }} - - name: 'Check out repository' - uses: actions/checkout@v2 - - name: 'Set up JDK ${{ matrix.java }}' - uses: actions/setup-java@v2 - with: - java-version: ${{ matrix.java }} - distribution: 'zulu' - cache: 'maven' - - name: 'Install' - shell: bash - run: mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V - - name: 'Test' - shell: bash - run: mvn test -B - - publish_snapshot: - name: 'Publish snapshot' - needs: test - if: github.event_name == 'push' && github.repository == 'google/google-java-format' && github.ref == 'refs/heads/master' - runs-on: ubuntu-latest - steps: - - name: 'Check out repository' - uses: actions/checkout@v2 - - name: 'Set up JDK 17' - uses: actions/setup-java@v2 - with: - java-version: 17 - distribution: 'zulu' - cache: 'maven' - server-id: sonatype-nexus-snapshots - server-username: CI_DEPLOY_USERNAME - server-password: CI_DEPLOY_PASSWORD - - name: 'Publish' - env: - CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} - CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} - run: mvn -pl '!eclipse_plugin' source:jar deploy -B -DskipTests=true -Dinvoker.skip=true -Dmaven.javadoc.skip=true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index a3f066df0..000000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,74 +0,0 @@ -name: Release google-java-format - -on: - workflow_dispatch: - inputs: - version: - description: "version number for this release." - required: true - -jobs: - build-maven-jars: - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Setup Signing Key - run: | - gpg-agent --daemon --default-cache-ttl 7200 - echo -e "${{ secrets.GPG_SIGNING_KEY }}" | gpg --batch --import --no-tty - echo "hello world" > temp.txt - gpg --detach-sig --yes -v --output=/dev/null --pinentry-mode loopback --passphrase "${{ secrets.GPG_PASSPHRASE }}" temp.txt - rm temp.txt - gpg --list-secret-keys --keyid-format LONG - - - name: Checkout - uses: actions/checkout@v2.4.0 - - - name: Set up JDK - uses: actions/setup-java@v2.5.0 - with: - java-version: 17 - distribution: 'zulu' - cache: 'maven' - server-id: sonatype-nexus-staging - server-username: CI_DEPLOY_USERNAME - server-password: CI_DEPLOY_PASSWORD - - - name: Bump Version Number - run: | - mvn --no-transfer-progress versions:set versions:commit -DnewVersion="${{ github.event.inputs.version }}" - mvn tycho-versions:update-eclipse-metadata -pl eclipse_plugin - git ls-files | grep 'pom.xml$' | xargs git add - git config --global user.email "${{ github.actor }}@users.noreply.github.com" - git config --global user.name "${{ github.actor }}" - git commit -m "Release google-java-format ${{ github.event.inputs.version }}" - git tag "v${{ github.event.inputs.version }}" - echo "TARGET_COMMITISH=$(git rev-parse HEAD)" >> $GITHUB_ENV - git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/google/google-java-format.git - - - name: Deploy to Sonatype staging - env: - CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} - CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} - run: - mvn --no-transfer-progress -pl '!eclipse_plugin' -P sonatype-oss-release clean deploy -Dgpg.passphrase="${{ secrets.GPG_PASSPHRASE }}" - - - name: Build Eclipse plugin - run: - mvn --no-transfer-progress -pl 'eclipse_plugin' verify gpg:sign -DskipTests=true -Dgpg.passphrase="${{ secrets.GPG_PASSPHRASE }}" - - - name: Push tag - run: | - git push origin "v${{ github.event.inputs.version }}" - - - name: Add Jars to Release Entry - uses: softprops/action-gh-release@v0.1.14 - with: - draft: true - name: ${{ github.event.input.version }} - tag_name: "v${{ github.event.inputs.version }}" - target_commitish: ${{ env.TARGET_COMMITISH }} - files: | - core/target/google-java-format-*.jar - eclipse_plugin/target/google-java-format-eclipse-plugin-*.jar diff --git a/core/pom.xml b/core/pom.xml index bfce4e27f..6bf017430 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -21,11 +21,11 @@ 4.0.0 com.github.mrdolch.googlejavaformat - google-java-format-parent - 1.15.0-SNAPSHOT + swiss-google-java-format-parent + 1.15.0 - google-java-format + swiss-google-java-format Google Java Format diff --git a/pom.xml b/pom.xml index a35f0488c..35e6468d6 100644 --- a/pom.xml +++ b/pom.xml @@ -21,9 +21,9 @@ 4.0.0 com.github.mrdolch.googlejavaformat - google-java-format-parent + swiss-google-java-format-parent pom - 1.15.0-SNAPSHOT + 1.15.0 core From 80adde7dbe9936d5c841754c5d24af45c550cbe9 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Mon, 12 Dec 2022 22:57:12 +0100 Subject: [PATCH 003/107] Change name to Configurable and add Option --width --- core/pom.xml | 4 +- .../java/CommandLineOptions.java | 21 ++-- .../java/CommandLineOptionsParser.java | 8 +- .../java/FormatFileCallable.java | 8 +- .../googlejavaformat/java/Formatter.java | 77 +++++++-------- .../googlejavaformat/java/ImportOrderer.java | 94 +++++++++--------- .../java/JavaCommentsHelper.java | 48 +++++----- .../java/JavaFormatterOptions.java | 28 +++--- .../google/googlejavaformat/java/Main.java | 96 +++++++++---------- pom.xml | 2 +- 10 files changed, 193 insertions(+), 193 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 6bf017430..a049fd0cc 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -21,11 +21,11 @@ 4.0.0 com.github.mrdolch.googlejavaformat - swiss-google-java-format-parent + configurable-google-java-format-parent 1.15.0 - swiss-google-java-format + configurable-google-java-format Google Java Format diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java index d37713246..bf442438c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptions.java @@ -31,7 +31,7 @@ final class CommandLineOptions { private final ImmutableList offsets; private final ImmutableList lengths; private final boolean aosp; - private final boolean swiss; + private final int width ; private final boolean version; private final boolean help; private final boolean stdin; @@ -51,7 +51,7 @@ final class CommandLineOptions { final ImmutableList offsets, final ImmutableList lengths, final boolean aosp, - final boolean swiss, + final int width, final boolean version, final boolean help, final boolean stdin, @@ -69,7 +69,7 @@ final class CommandLineOptions { this.offsets = offsets; this.lengths = lengths; this.aosp = aosp; - this.swiss = swiss; + this.width = width; this.version = version; this.help = help; this.stdin = stdin; @@ -112,9 +112,10 @@ ImmutableList lengths() { boolean aosp() { return aosp; } - /** Use SWISS style instead of Google Style (120 Characters line length). */ - boolean swiss() { - return swiss; + + /** Maximal line length. */ + int width() { + return width; } /** Print the version. */ @@ -187,7 +188,7 @@ static class Builder { private final ImmutableList.Builder lengths = ImmutableList.builder(); private boolean inPlace = false; private boolean aosp = false; - private boolean swiss = false; + private int width = 100; private boolean version = false; private boolean help = false; private boolean stdin = false; @@ -228,8 +229,8 @@ Builder aosp(final boolean aosp) { return this; } - Builder swiss(final boolean swiss) { - this.swiss = swiss; + Builder width(final int width) { + this.width = width; return this; } @@ -296,7 +297,7 @@ CommandLineOptions build() { offsets.build(), lengths.build(), aosp, - swiss, + width, version, help, stdin, diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java index 60192670b..187b70e1c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java @@ -87,10 +87,10 @@ static CommandLineOptions parse(final Iterable options) { case "-a": optionsBuilder.aosp(true); break; - case "--swiss": - case "-swiss": - case "-s": - optionsBuilder.swiss(true); + case "--width": + case "-width": + case "-w": + optionsBuilder.width(parseInteger(it, flag, value)); break; case "--version": case "-version": diff --git a/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java b/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java index a17c43d62..bce5bf7e6 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatFileCallable.java @@ -29,7 +29,7 @@ class FormatFileCallable implements Callable { private final JavaFormatterOptions options; public FormatFileCallable( - CommandLineOptions parameters, String input, JavaFormatterOptions options) { + final CommandLineOptions parameters, final String input, final JavaFormatterOptions options) { this.input = input; this.parameters = parameters; this.options = options; @@ -41,11 +41,11 @@ public String call() throws FormatterException { return fixImports(input); } - Formatter formatter = new Formatter(options); + final Formatter formatter = new Formatter(options); String formatted = formatter.formatSource(input, characterRanges(input).asRanges()); formatted = fixImports(formatted); if (parameters.reflowLongStrings()) { - formatted = StringWrapper.wrap(options.style().getMaxLineLength(), formatted, formatter); + formatted = StringWrapper.wrap(options.getMaxLineLength(), formatted, formatter); } return formatted; } @@ -60,7 +60,7 @@ private String fixImports(String input) throws FormatterException { return input; } - private RangeSet characterRanges(String input) { + private RangeSet characterRanges(final String input) { final RangeSet characterRanges = TreeRangeSet.create(); if (parameters.lines().isEmpty() && parameters.offsets().isEmpty()) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index 4326c3788..81871f4a3 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -81,12 +81,12 @@ public Formatter() { this(JavaFormatterOptions.defaultOptions()); } - public Formatter(JavaFormatterOptions options) { + public Formatter(final JavaFormatterOptions options) { this.options = options; } public int getMaxLineLength() { - return this.options.style().getMaxLineLength(); + return this.options.getMaxLineLength(); } /** * Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link @@ -96,31 +96,31 @@ public int getMaxLineLength() { * @param javaOutput the {@link JavaOutput} * @param options the {@link JavaFormatterOptions} */ - static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatterOptions options) + static void format(final JavaInput javaInput, final JavaOutput javaOutput, final JavaFormatterOptions options) throws FormatterException { - Context context = new Context(); - DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + final Context context = new Context(); + final DiagnosticCollector diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); Options.instance(context).put("--enable-preview", "true"); - JCCompilationUnit unit; - JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); + final JCCompilationUnit unit; + final JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.of()); - } catch (IOException e) { + } catch (final IOException e) { // impossible throw new IOError(e); } - SimpleJavaFileObject source = + final SimpleJavaFileObject source = new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) { @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { + public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws IOException { return javaInput.getText(); } }; Log.instance(context).useSource(source); - ParserFactory parserFactory = ParserFactory.instance(context); - JavacParser parser = + final ParserFactory parserFactory = ParserFactory.instance(context); + final JavacParser parser = parserFactory.newParser( javaInput.getText(), /* keepDocComments= */ true, @@ -130,14 +130,14 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept unit.sourcefile = source; javaInput.setCompilationUnit(unit); - Iterable> errorDiagnostics = + final Iterable> errorDiagnostics = Iterables.filter(diagnostics.getDiagnostics(), Formatter::errorDiagnostic); if (!Iterables.isEmpty(errorDiagnostics)) { throw FormatterException.fromJavacDiagnostics(errorDiagnostics); } - OpsBuilder builder = new OpsBuilder(javaInput, javaOutput); + final OpsBuilder builder = new OpsBuilder(javaInput, javaOutput); // Output the compilation unit. - JavaInputAstVisitor visitor; + final JavaInputAstVisitor visitor; if (Runtime.version().feature() >= 17) { try { visitor = @@ -145,7 +145,7 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept .asSubclass(JavaInputAstVisitor.class) .getConstructor(OpsBuilder.class, int.class) .newInstance(builder, options.indentationMultiplier()); - } catch (ReflectiveOperationException e) { + } catch (final ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } else { @@ -154,24 +154,21 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept visitor.scan(unit, null); builder.sync(javaInput.getText().length()); builder.drain(); - Doc doc = new DocBuilder().withOps(builder.build()).build(); + final Doc doc = new DocBuilder().withOps(builder.build()).build(); doc.computeBreaks( - javaOutput.getCommentsHelper(), options.style().getMaxLineLength(), new Doc.State(+0, 0)); + javaOutput.getCommentsHelper(), options.getMaxLineLength(), new Doc.State(+0, 0)); doc.write(javaOutput); javaOutput.flush(); } - static boolean errorDiagnostic(Diagnostic input) { + static boolean errorDiagnostic(final Diagnostic input) { if (input.getKind() != Diagnostic.Kind.ERROR) { return false; } - switch (input.getCode()) { - case "compiler.err.invalid.meth.decl.ret.type.req": - // accept constructor-like method declarations that don't match the name of their - // enclosing class - return false; - default: - break; + if (input.getCode().equals("compiler.err.invalid.meth.decl.ret.type.req")) { + // accept constructor-like method declarations that don't match the name of their + // enclosing class + return false; } return true; } @@ -181,7 +178,7 @@ static boolean errorDiagnostic(Diagnostic input) { * * @throws FormatterException if the input cannot be parsed */ - public void formatSource(CharSource input, CharSink output) + public void formatSource(final CharSource input, final CharSink output) throws FormatterException, IOException { // TODO(cushon): proper support for streaming input/output. Input may // not be feasible (parsing) but output should be easier. @@ -197,7 +194,7 @@ public void formatSource(CharSource input, CharSink output) * @return the output string * @throws FormatterException if the input string cannot be parsed */ - public String formatSource(String input) throws FormatterException { + public String formatSource(final String input) throws FormatterException { return formatSource(input, ImmutableList.of(Range.closedOpen(0, input.length()))); } @@ -230,7 +227,7 @@ public String formatSourceAndFixImports(String input) throws FormatterException * @return the output string * @throws FormatterException if the input string cannot be parsed */ - public String formatSource(String input, Collection> characterRanges) + public String formatSource(final String input, final Collection> characterRanges) throws FormatterException { return JavaOutput.applyReplacements(input, getFormatReplacements(input, characterRanges)); } @@ -244,7 +241,7 @@ public String formatSource(String input, Collection> characterRan * @throws FormatterException if the input string cannot be parsed */ public ImmutableList getFormatReplacements( - String input, Collection> characterRanges) throws FormatterException { + final String input, final Collection> characterRanges) throws FormatterException { JavaInput javaInput = new JavaInput(input); // TODO(cushon): this is only safe because the modifier ordering doesn't affect whitespace, @@ -252,15 +249,15 @@ public ImmutableList getFormatReplacements( // 'de-linting' changes (e.g. import ordering). javaInput = ModifierOrderer.reorderModifiers(javaInput, characterRanges); - String lineSeparator = Newlines.guessLineSeparator(input); - JavaOutput javaOutput = + final String lineSeparator = Newlines.guessLineSeparator(input); + final JavaOutput javaOutput = new JavaOutput(lineSeparator, javaInput, new JavaCommentsHelper(lineSeparator, options)); try { format(javaInput, javaOutput, options); - } catch (FormattingError e) { + } catch (final FormattingError e) { throw new FormatterException(e.diagnostics()); } - RangeSet tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges); + final RangeSet tokenRangeSet = javaInput.characterRangesToTokenRanges(characterRanges); return javaOutput.getFormatReplacements(tokenRangeSet); } @@ -268,19 +265,19 @@ public ImmutableList getFormatReplacements( * Converts zero-indexed, [closed, open) line ranges in the given source file to character ranges. */ public static RangeSet lineRangesToCharRanges( - String input, RangeSet lineRanges) { - List lines = new ArrayList<>(); + final String input, final RangeSet lineRanges) { + final List lines = new ArrayList<>(); Iterators.addAll(lines, Newlines.lineOffsetIterator(input)); lines.add(input.length() + 1); final RangeSet characterRanges = TreeRangeSet.create(); - for (Range lineRange : + for (final Range lineRange : lineRanges.subRangeSet(Range.closedOpen(0, lines.size() - 1)).asRanges()) { - int lineStart = lines.get(lineRange.lowerEndpoint()); + final int lineStart = lines.get(lineRange.lowerEndpoint()); // Exclude the trailing newline. This isn't strictly necessary, but handling blank lines // as empty ranges is convenient. - int lineEnd = lines.get(lineRange.upperEndpoint()) - 1; - Range range = Range.closedOpen(lineStart, lineEnd); + final int lineEnd = lines.get(lineRange.upperEndpoint()) - 1; + final Range range = Range.closedOpen(lineStart, lineEnd); characterRanges.add(range); } return characterRanges; diff --git a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java index 5ca934e05..e39fc9416 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java @@ -13,9 +13,6 @@ */ package com.google.googlejavaformat.java; -import static com.google.common.collect.Iterables.getLast; -import static com.google.common.primitives.Booleans.trueFirst; - import com.google.common.base.CharMatcher; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; @@ -26,6 +23,7 @@ import com.google.googlejavaformat.java.JavaFormatterOptions.Style; import com.google.googlejavaformat.java.JavaInput.Tok; import com.sun.tools.javac.parser.Tokens.TokenKind; + import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -33,6 +31,9 @@ import java.util.function.BiFunction; import java.util.stream.Stream; +import static com.google.common.collect.Iterables.getLast; +import static com.google.common.primitives.Booleans.trueFirst; + /** Orders imports in Java source code. */ public class ImportOrderer { @@ -44,8 +45,8 @@ public class ImportOrderer { * * @throws FormatterException if the input could not be parsed. */ - public static String reorderImports(String text, Style style) throws FormatterException { - ImmutableList toks = JavaInput.buildToks(text, CLASS_START); + public static String reorderImports(final String text, final Style style) throws FormatterException { + final ImmutableList toks = JavaInput.buildToks(text, CLASS_START); return new ImportOrderer(text, toks, style).reorderImports(); } @@ -58,42 +59,42 @@ public static String reorderImports(String text, Style style) throws FormatterEx * @throws FormatterException if the input could not be parsed. */ @Deprecated - public static String reorderImports(String text) throws FormatterException { + public static String reorderImports(final String text) throws FormatterException { return reorderImports(text, Style.GOOGLE); } private String reorderImports() throws FormatterException { - int firstImportStart; - Optional maybeFirstImport = findIdentifier(0, IMPORT_OR_CLASS_START); + final int firstImportStart; + final Optional maybeFirstImport = findIdentifier(0, IMPORT_OR_CLASS_START); if (!maybeFirstImport.isPresent() || !tokenAt(maybeFirstImport.get()).equals("import")) { // No imports, so nothing to do. return text; } firstImportStart = maybeFirstImport.get(); - int unindentedFirstImportStart = unindent(firstImportStart); + final int unindentedFirstImportStart = unindent(firstImportStart); - ImportsAndIndex imports = scanImports(firstImportStart); - int afterLastImport = imports.index; + final ImportsAndIndex imports = scanImports(firstImportStart); + final int afterLastImport = imports.index; // Make sure there are no more imports before the next class (etc) definition. - Optional maybeLaterImport = findIdentifier(afterLastImport, IMPORT_OR_CLASS_START); + final Optional maybeLaterImport = findIdentifier(afterLastImport, IMPORT_OR_CLASS_START); if (maybeLaterImport.isPresent() && tokenAt(maybeLaterImport.get()).equals("import")) { throw new FormatterException("Imports not contiguous (perhaps a comment separates them?)"); } - StringBuilder result = new StringBuilder(); - String prefix = tokString(0, unindentedFirstImportStart); + final StringBuilder result = new StringBuilder(); + final String prefix = tokString(0, unindentedFirstImportStart); result.append(prefix); if (!prefix.isEmpty() && Newlines.getLineEnding(prefix) == null) { result.append(lineSeparator).append(lineSeparator); } result.append(reorderedImportsString(imports.imports)); - List tail = new ArrayList<>(); + final List tail = new ArrayList<>(); tail.add(CharMatcher.whitespace().trimLeadingFrom(tokString(afterLastImport, toks.size()))); if (!toks.isEmpty()) { - Tok lastTok = getLast(toks); - int tailStart = lastTok.getPosition() + lastTok.length(); + final Tok lastTok = getLast(toks); + final int tailStart = lastTok.getPosition() + lastTok.length(); tail.add(text.substring(tailStart)); } if (tail.stream().anyMatch(s -> !s.isEmpty())) { @@ -143,7 +144,7 @@ private String reorderImports() throws FormatterException { * Determines whether to insert a blank line between the {@code prev} and {@code curr} {@link * Import}s based on Google style. */ - private static boolean shouldInsertBlankLineGoogle(Import prev, Import curr) { + private static boolean shouldInsertBlankLineGoogle(final Import prev, final Import curr) { return prev.isStatic() && !curr.isStatic(); } @@ -151,7 +152,7 @@ private static boolean shouldInsertBlankLineGoogle(Import prev, Import curr) { * Determines whether to insert a blank line between the {@code prev} and {@code curr} {@link * Import}s based on AOSP style. */ - private static boolean shouldInsertBlankLineAosp(Import prev, Import curr) { + private static boolean shouldInsertBlankLineAosp(final Import prev, final Import curr) { if (prev.isStatic() && !curr.isStatic()) { return true; } @@ -168,12 +169,11 @@ private static boolean shouldInsertBlankLineAosp(Import prev, Import curr) { private final Comparator importComparator; private final BiFunction shouldInsertBlankLineFn; - private ImportOrderer(String text, ImmutableList toks, Style style) { + private ImportOrderer(final String text, final ImmutableList toks, final Style style) { this.text = text; this.toks = toks; this.lineSeparator = Newlines.guessLineSeparator(text); switch (style) { - case SWISS: case GOOGLE: this.importComparator = GOOGLE_IMPORT_COMPARATOR; this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineGoogle; @@ -193,7 +193,7 @@ class Import { private final boolean isStatic; private final String trailing; - Import(String imported, String trailing, boolean isStatic) { + Import(final String imported, final String trailing, final boolean isStatic) { this.imported = imported; this.trailing = trailing; this.isStatic = isStatic; @@ -250,7 +250,7 @@ public boolean isThirdParty() { // terminator. @Override public String toString() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append("import "); if (isStatic()) { sb.append("static "); @@ -265,8 +265,8 @@ public String toString() { } } - private String tokString(int start, int end) { - StringBuilder sb = new StringBuilder(); + private String tokString(final int start, final int end) { + final StringBuilder sb = new StringBuilder(); for (int i = start; i < end; i++) { sb.append(toks.get(i).getOriginalText()); } @@ -277,7 +277,7 @@ private static class ImportsAndIndex { final ImmutableSortedSet imports; final int index; - ImportsAndIndex(ImmutableSortedSet imports, int index) { + ImportsAndIndex(final ImmutableSortedSet imports, final int index) { this.imports = imports; this.index = index; } @@ -299,7 +299,7 @@ private static class ImportsAndIndex { */ private ImportsAndIndex scanImports(int i) throws FormatterException { int afterLastImport = i; - ImmutableSortedSet.Builder imports = ImmutableSortedSet.orderedBy(importComparator); + final ImmutableSortedSet.Builder imports = ImmutableSortedSet.orderedBy(importComparator); // JavaInput.buildToks appends a zero-width EOF token after all tokens. It won't match any // of our tests here and protects us from running off the end of the toks list. Since it is // zero-width it doesn't matter if we include it in our string concatenation at the end. @@ -308,7 +308,7 @@ private ImportsAndIndex scanImports(int i) throws FormatterException { if (isSpaceToken(i)) { i++; } - boolean isStatic = tokenAt(i).equals("static"); + final boolean isStatic = tokenAt(i).equals("static"); if (isStatic) { i++; if (isSpaceToken(i)) { @@ -318,8 +318,8 @@ private ImportsAndIndex scanImports(int i) throws FormatterException { if (!isIdentifierToken(i)) { throw new FormatterException("Unexpected token after import: " + tokenAt(i)); } - StringAndIndex imported = scanImported(i); - String importedName = imported.string; + final StringAndIndex imported = scanImported(i); + final String importedName = imported.string; i = imported.index; if (isSpaceToken(i)) { i++; @@ -331,7 +331,7 @@ private ImportsAndIndex scanImports(int i) throws FormatterException { // Extra semicolons are not allowed by the JLS but are accepted by javac. i++; } - StringBuilder trailing = new StringBuilder(); + final StringBuilder trailing = new StringBuilder(); if (isSpaceToken(i)) { trailing.append(tokenAt(i)); i++; @@ -367,15 +367,15 @@ private ImportsAndIndex scanImports(int i) throws FormatterException { } // Produces the sorted output based on the imports we have scanned. - private String reorderedImportsString(ImmutableSortedSet imports) { + private String reorderedImportsString(final ImmutableSortedSet imports) { Preconditions.checkArgument(!imports.isEmpty(), "imports"); // Pretend that the first import was preceded by another import of the same kind, so we don't // insert a newline there. Import prevImport = imports.iterator().next(); - StringBuilder sb = new StringBuilder(); - for (Import currImport : imports) { + final StringBuilder sb = new StringBuilder(); + for (final Import currImport : imports) { if (shouldInsertBlankLineFn.apply(prevImport, currImport)) { // Blank line between static and non-static imports. sb.append(lineSeparator); @@ -390,7 +390,7 @@ private static class StringAndIndex { private final String string; private final int index; - StringAndIndex(String string, int index) { + StringAndIndex(final String string, final int index) { this.string = string; this.index = index; } @@ -408,9 +408,9 @@ private static class StringAndIndex { * token after the imported thing ({@code ;} in the example). * @throws FormatterException if the imported name could not be parsed. */ - private StringAndIndex scanImported(int start) throws FormatterException { + private StringAndIndex scanImported(final int start) throws FormatterException { int i = start; - StringBuilder imported = new StringBuilder(); + final StringBuilder imported = new StringBuilder(); // At the start of each iteration of this loop, i points to an identifier. // On exit from the loop, i points to a token after an identifier or after *. while (true) { @@ -438,10 +438,10 @@ private StringAndIndex scanImported(int start) throws FormatterException { * @param start the index to start looking at * @param identifiers the identifiers to look for */ - private Optional findIdentifier(int start, ImmutableSet identifiers) { + private Optional findIdentifier(final int start, final ImmutableSet identifiers) { for (int i = start; i < toks.size(); i++) { if (isIdentifierToken(i)) { - String id = tokenAt(i); + final String id = tokenAt(i); if (identifiers.contains(id)) { return Optional.of(i); } @@ -451,7 +451,7 @@ private Optional findIdentifier(int start, ImmutableSet identif } /** Returns the given token, or the preceding token if it is a whitespace token. */ - private int unindent(int i) { + private int unindent(final int i) { if (i > 0 && isSpaceToken(i - 1)) { return i - 1; } else { @@ -459,17 +459,17 @@ private int unindent(int i) { } } - private String tokenAt(int i) { + private String tokenAt(final int i) { return toks.get(i).getOriginalText(); } - private boolean isIdentifierToken(int i) { - String s = tokenAt(i); + private boolean isIdentifierToken(final int i) { + final String s = tokenAt(i); return !s.isEmpty() && Character.isJavaIdentifierStart(s.codePointAt(0)); } - private boolean isSpaceToken(int i) { - String s = tokenAt(i); + private boolean isSpaceToken(final int i) { + final String s = tokenAt(i); if (s.isEmpty()) { return false; } else { @@ -477,11 +477,11 @@ private boolean isSpaceToken(int i) { } } - private boolean isSlashSlashCommentToken(int i) { + private boolean isSlashSlashCommentToken(final int i) { return toks.get(i).isSlashSlashComment(); } - private boolean isNewlineToken(int i) { + private boolean isNewlineToken(final int i) { return toks.get(i).isNewline(); } } diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java index 9a0c6274a..81d030b40 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java @@ -32,13 +32,13 @@ public final class JavaCommentsHelper implements CommentsHelper { private final String lineSeparator; private final JavaFormatterOptions options; - public JavaCommentsHelper(String lineSeparator, JavaFormatterOptions options) { + public JavaCommentsHelper(final String lineSeparator, final JavaFormatterOptions options) { this.lineSeparator = lineSeparator; this.options = options; } @Override - public String rewrite(Tok tok, int maxWidth, int column0) { + public String rewrite(final Tok tok, final int maxWidth, final int column0) { if (!tok.isComment()) { return tok.getOriginalText(); } @@ -46,8 +46,8 @@ public String rewrite(Tok tok, int maxWidth, int column0) { if (tok.isJavadocComment() && options.formatJavadoc()) { text = JavadocFormatter.formatJavadoc(text, column0); } - List lines = new ArrayList<>(); - Iterator it = Newlines.lineIterator(text); + final List lines = new ArrayList<>(); + final Iterator it = Newlines.lineIterator(text); while (it.hasNext()) { lines.add(CharMatcher.whitespace().trimTrailingFrom(it.next())); } @@ -64,13 +64,13 @@ public String rewrite(Tok tok, int maxWidth, int column0) { // For non-javadoc-shaped block comments, shift the entire block to the correct // column, but do not adjust relative indentation. - private String preserveIndentation(List lines, int column0) { - StringBuilder builder = new StringBuilder(); + private String preserveIndentation(final List lines, final int column0) { + final StringBuilder builder = new StringBuilder(); // find the leftmost non-whitespace character in all trailing lines int startCol = -1; for (int i = 1; i < lines.size(); i++) { - int lineIdx = CharMatcher.whitespace().negate().indexIn(lines.get(i)); + final int lineIdx = CharMatcher.whitespace().negate().indexIn(lines.get(i)); if (lineIdx >= 0 && (startCol == -1 || lineIdx < startCol)) { startCol = lineIdx; } @@ -93,11 +93,11 @@ private String preserveIndentation(List lines, int column0) { } // Wraps and re-indents line comments. - private String indentLineComments(List lines, int column0) { + private String indentLineComments(List lines, final int column0) { lines = wrapLineComments(lines, column0); - StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); builder.append(lines.get(0).trim()); - String indentString = Strings.repeat(" ", column0); + final String indentString = Strings.repeat(" ", column0); for (int i = 1; i < lines.size(); ++i) { builder.append(lineSeparator).append(indentString).append(lines.get(i).trim()); } @@ -109,13 +109,13 @@ private String indentLineComments(List lines, int column0) { private static final Pattern LINE_COMMENT_MISSING_SPACE_PREFIX = Pattern.compile("^(//+)(?!noinspection|\\$NON-NLS-\\d+\\$)[^\\s/]"); - private List wrapLineComments(List lines, int column0) { - List result = new ArrayList<>(); + private List wrapLineComments(final List lines, final int column0) { + final List result = new ArrayList<>(); for (String line : lines) { // Add missing leading spaces to line comments: `//foo` -> `// foo`. - Matcher matcher = LINE_COMMENT_MISSING_SPACE_PREFIX.matcher(line); + final Matcher matcher = LINE_COMMENT_MISSING_SPACE_PREFIX.matcher(line); if (matcher.find()) { - int length = matcher.group(1).length(); + final int length = matcher.group(1).length(); line = Strings.repeat("/", length) + " " + line.substring(length); } if (line.startsWith("// MOE:")) { @@ -123,8 +123,8 @@ private List wrapLineComments(List lines, int column0) { result.add(line); continue; } - while (line.length() + column0 > options.style().getMaxLineLength()) { - int idx = options.style().getMaxLineLength() - column0; + while (line.length() + column0 > options.getMaxLineLength()) { + int idx = options.getMaxLineLength() - column0; // only break on whitespace characters, and ignore the leading `// ` while (idx >= 2 && !CharMatcher.whitespace().matches(line.charAt(idx))) { idx--; @@ -142,14 +142,14 @@ private List wrapLineComments(List lines, int column0) { // Remove leading whitespace (trailing was already removed), and re-indent. // Add a +1 indent before '*', and add the '*' if necessary. - private String indentJavadoc(List lines, int column0) { - StringBuilder builder = new StringBuilder(); + private String indentJavadoc(final List lines, final int column0) { + final StringBuilder builder = new StringBuilder(); builder.append(lines.get(0).trim()); - int indent = column0 + 1; - String indentString = Strings.repeat(" ", indent); + final int indent = column0 + 1; + final String indentString = Strings.repeat(" ", indent); for (int i = 1; i < lines.size(); ++i) { builder.append(lineSeparator).append(indentString); - String line = lines.get(i).trim(); + final String line = lines.get(i).trim(); if (!line.startsWith("*")) { builder.append("* "); } @@ -159,12 +159,12 @@ private String indentJavadoc(List lines, int column0) { } // Returns true if the comment looks like javadoc - private static boolean javadocShaped(List lines) { - Iterator it = lines.iterator(); + private static boolean javadocShaped(final List lines) { + final Iterator it = lines.iterator(); if (!it.hasNext()) { return false; } - String first = it.next().trim(); + final String first = it.next().trim(); // if it's actually javadoc, we're done if (first.startsWith("/**")) { return true; diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java b/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java index abbc7796b..d8a0ba6d9 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaFormatterOptions.java @@ -30,35 +30,30 @@ public class JavaFormatterOptions { public enum Style { /** The default Google Java Style configuration. */ - GOOGLE(1, 100), - SWISS(1, 120), - + GOOGLE(1), /** The AOSP-compliant configuration. */ - AOSP(2, 100); + AOSP(2); private final int indentationMultiplier; - private final int maxLineLength; - Style(final int indentationMultiplier, final int maxLineLength) { + Style(final int indentationMultiplier) { this.indentationMultiplier = indentationMultiplier; - this.maxLineLength = maxLineLength; } int indentationMultiplier() { return indentationMultiplier; } - public int getMaxLineLength() { - return maxLineLength; - } } private final Style style; private final boolean formatJavadoc; + private final int maxLineWidth; - private JavaFormatterOptions(final Style style, final boolean formatJavadoc) { + private JavaFormatterOptions(final Style style, final boolean formatJavadoc, final int maxLineWidth) { this.style = style; this.formatJavadoc = formatJavadoc; + this.maxLineWidth = maxLineWidth; } /** Returns the multiplier for the unit of indent. */ @@ -70,6 +65,10 @@ public boolean formatJavadoc() { return formatJavadoc; } + public int getMaxLineLength() { + return maxLineWidth; + } + /** Returns the code style. */ public Style style() { return style; @@ -89,6 +88,7 @@ public static Builder builder() { public static class Builder { private Style style = Style.GOOGLE; private boolean formatJavadoc = true; + private int maxLineWidth = 100; private Builder() {} @@ -101,9 +101,13 @@ public Builder formatJavadoc(final boolean formatJavadoc) { this.formatJavadoc = formatJavadoc; return this; } + public Builder maxLineWidth(final int maxLineWidth) { + this.maxLineWidth = maxLineWidth; + return this; + } public JavaFormatterOptions build() { - return new JavaFormatterOptions(style, formatJavadoc); + return new JavaFormatterOptions(style, formatJavadoc, maxLineWidth); } } } diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index b58242c4a..934ad3372 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -14,17 +14,11 @@ 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.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -36,6 +30,9 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; +import static java.lang.Math.min; +import static java.nio.charset.StandardCharsets.UTF_8; + /** The main class for the Java formatter CLI. */ public final class Main { private static final int MAX_THREADS = 20; @@ -49,7 +46,7 @@ static String versionString() { private final PrintWriter errWriter; private final InputStream inStream; - public Main(PrintWriter outWriter, PrintWriter errWriter, InputStream inStream) { + public Main(final PrintWriter outWriter, final PrintWriter errWriter, final InputStream inStream) { this.outWriter = outWriter; this.errWriter = errWriter; this.inStream = inStream; @@ -62,10 +59,10 @@ public Main(PrintWriter outWriter, PrintWriter errWriter, InputStream inStream) * * @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); + public static void main(final String[] args) { + final PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out, UTF_8)); + final PrintWriter err = new PrintWriter(new OutputStreamWriter(System.err, UTF_8)); + final int result = main(out, err, args); System.exit(result); } @@ -73,11 +70,11 @@ public static void main(String[] args) { * 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) { + static int main(final PrintWriter out, final PrintWriter err, final String... args) { try { - Main formatter = new Main(out, err, System.in); + final Main formatter = new Main(out, err, System.in); return formatter.format(args); - } catch (UsageException e) { + } catch (final UsageException e) { err.print(e.getMessage()); return 0; } finally { @@ -93,8 +90,8 @@ static int main(PrintWriter out, PrintWriter err, String... args) { * * @param args the command-line arguments */ - public int format(String... args) throws UsageException { - CommandLineOptions parameters = processArgs(args); + public int format(final String... args) throws UsageException { + final CommandLineOptions parameters = processArgs(args); if (parameters.version()) { errWriter.println(versionString()); return 0; @@ -103,10 +100,11 @@ public int format(String... args) throws UsageException { throw new UsageException(); } - JavaFormatterOptions options = + final JavaFormatterOptions options = JavaFormatterOptions.builder() - .style(parameters.aosp() ? Style.AOSP : parameters.swiss() ? Style.SWISS : Style.GOOGLE) + .style(parameters.aosp() ? Style.AOSP : Style.GOOGLE) .formatJavadoc(parameters.formatJavadoc()) + .maxLineWidth(parameters.width()) .build(); if (parameters.stdin()) { @@ -116,44 +114,44 @@ public int format(String... args) throws UsageException { } } - private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions options) { - int numThreads = min(MAX_THREADS, parameters.files().size()); - ExecutorService executorService = Executors.newFixedThreadPool(numThreads); + private int formatFiles(final CommandLineOptions parameters, final JavaFormatterOptions options) { + final int numThreads = min(MAX_THREADS, parameters.files().size()); + final ExecutorService executorService = Executors.newFixedThreadPool(numThreads); - Map inputs = new LinkedHashMap<>(); - Map> results = new LinkedHashMap<>(); + final Map inputs = new LinkedHashMap<>(); + final Map> results = new LinkedHashMap<>(); boolean allOk = true; - for (String fileName : parameters.files()) { + for (final String fileName : parameters.files()) { if (!fileName.endsWith(".java")) { errWriter.println("Skipping non-Java file: " + fileName); continue; } - Path path = Paths.get(fileName); - String input; + final Path path = Paths.get(fileName); + final 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) { + } catch (final IOException e) { errWriter.println(fileName + ": could not read file: " + e.getMessage()); allOk = false; } } - for (Map.Entry> result : results.entrySet()) { - Path path = result.getKey(); - String formatted; + for (final Map.Entry> result : results.entrySet()) { + final Path path = result.getKey(); + final String formatted; try { formatted = result.getValue().get(); - } catch (InterruptedException e) { + } catch (final InterruptedException e) { errWriter.println(e.getMessage()); allOk = false; continue; - } catch (ExecutionException e) { + } catch (final ExecutionException e) { if (e.getCause() instanceof FormatterException) { - for (FormatterDiagnostic diagnostic : ((FormatterException) e.getCause()).diagnostics()) { + for (final FormatterDiagnostic diagnostic : ((FormatterException) e.getCause()).diagnostics()) { errWriter.println(path + ":" + diagnostic); } } else { @@ -163,7 +161,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti allOk = false; continue; } - boolean changed = !formatted.equals(inputs.get(path)); + final boolean changed = !formatted.equals(inputs.get(path)); if (changed && parameters.setExitIfChanged()) { allOk = false; } @@ -173,7 +171,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti } try { Files.write(path, formatted.getBytes(UTF_8)); - } catch (IOException e) { + } catch (final IOException e) { errWriter.println(path + ": could not write file: " + e.getMessage()); allOk = false; continue; @@ -189,18 +187,18 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti return allOk ? 0 : 1; } - private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions options) { - String input; + private int formatStdin(final CommandLineOptions parameters, final JavaFormatterOptions options) { + final String input; try { input = new String(ByteStreams.toByteArray(inStream), UTF_8); - } catch (IOException e) { + } catch (final IOException e) { throw new IOError(e); } - String stdinFilename = parameters.assumeFilename().orElse(STDIN_FILENAME); + final String stdinFilename = parameters.assumeFilename().orElse(STDIN_FILENAME); boolean ok = true; try { - String output = new FormatFileCallable(parameters, input, options).call(); - boolean changed = !input.equals(output); + final String output = new FormatFileCallable(parameters, input, options).call(); + final boolean changed = !input.equals(output); if (changed && parameters.setExitIfChanged()) { ok = false; } @@ -211,8 +209,8 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti } else { outWriter.write(output); } - } catch (FormatterException e) { - for (FormatterDiagnostic diagnostic : e.diagnostics()) { + } catch (final FormatterException e) { + for (final FormatterDiagnostic diagnostic : e.diagnostics()) { errWriter.println(stdinFilename + ":" + diagnostic); } ok = false; @@ -222,13 +220,13 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti } /** Parses and validates command-line flags. */ - public static CommandLineOptions processArgs(String... args) throws UsageException { - CommandLineOptions parameters; + public static CommandLineOptions processArgs(final String... args) throws UsageException { + final CommandLineOptions parameters; try { parameters = CommandLineOptionsParser.parse(Arrays.asList(args)); - } catch (IllegalArgumentException e) { + } catch (final IllegalArgumentException e) { throw new UsageException(e.getMessage()); - } catch (Throwable t) { + } catch (final Throwable t) { t.printStackTrace(); throw new UsageException(t.getMessage()); } diff --git a/pom.xml b/pom.xml index 35e6468d6..2dc0e4ba6 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ 4.0.0 com.github.mrdolch.googlejavaformat - swiss-google-java-format-parent + configurable-google-java-format-parent pom 1.15.0 From 7b73471d362aec9bba042f326733f739b8956674 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Fri, 16 Dec 2022 19:33:22 +0100 Subject: [PATCH 004/107] Repect --width also in JavaDoc --- .../java/JavaCommentsHelper.java | 2 +- .../java/javadoc/JavadocFormatter.java | 48 ++++++------- .../java/javadoc/JavadocWriter.java | 69 +++++++++---------- 3 files changed, 59 insertions(+), 60 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java index 81d030b40..82df60fd1 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaCommentsHelper.java @@ -44,7 +44,7 @@ public String rewrite(final Tok tok, final int maxWidth, final int column0) { } String text = tok.getOriginalText(); if (tok.isJavadocComment() && options.formatJavadoc()) { - text = JavadocFormatter.formatJavadoc(text, column0); + text = JavadocFormatter.formatJavadoc(text, column0, maxWidth); } final List lines = new ArrayList<>(); final Iterator it = Newlines.lineIterator(text); diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java index 03938a677..47ef1f7e5 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocFormatter.java @@ -14,18 +14,19 @@ package com.google.googlejavaformat.java.javadoc; -import static com.google.googlejavaformat.java.javadoc.JavadocLexer.lex; -import static com.google.googlejavaformat.java.javadoc.Token.Type.BR_TAG; -import static com.google.googlejavaformat.java.javadoc.Token.Type.PARAGRAPH_OPEN_TAG; -import static java.util.regex.Pattern.CASE_INSENSITIVE; -import static java.util.regex.Pattern.compile; - import com.google.common.collect.ImmutableList; import com.google.googlejavaformat.java.javadoc.JavadocLexer.LexException; + import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static com.google.googlejavaformat.java.javadoc.JavadocLexer.lex; +import static com.google.googlejavaformat.java.javadoc.Token.Type.BR_TAG; +import static com.google.googlejavaformat.java.javadoc.Token.Type.PARAGRAPH_OPEN_TAG; +import static java.util.regex.Pattern.CASE_INSENSITIVE; +import static java.util.regex.Pattern.compile; + /** * Entry point for formatting Javadoc. * @@ -36,26 +37,25 @@ */ public final class JavadocFormatter { - static final int MAX_LINE_LENGTH = 100; /** * Formats the given Javadoc comment, which must start with ∕✱✱ and end with ✱∕. The output will * start and end with the same characters. */ - public static String formatJavadoc(String input, int blockIndent) { - ImmutableList tokens; + public static String formatJavadoc(final String input, final int blockIndent, final int maxWidth) { + final ImmutableList tokens; try { tokens = lex(input); - } catch (LexException e) { + } catch (final LexException e) { return input; } - String result = render(tokens, blockIndent); - return makeSingleLineIfPossible(blockIndent, result); + final String result = render(tokens, blockIndent, maxWidth); + return makeSingleLineIfPossible(blockIndent, result, maxWidth); } - private static String render(List input, int blockIndent) { - JavadocWriter output = new JavadocWriter(blockIndent); - for (Token token : input) { + private static String render(final List input, final int blockIndent, final int maxWidth) { + final JavadocWriter output = new JavadocWriter(blockIndent, maxWidth); + for (final Token token : input) { switch (token.getType()) { case BEGIN_JAVADOC: output.writeBeginJavadoc(); @@ -143,15 +143,15 @@ private static String render(List input, int blockIndent) { * should include them as part of its own postprocessing? Or even the writer could make sense. */ - private static Token standardizeBrToken(Token token) { + private static Token standardizeBrToken(final Token token) { return standardize(token, STANDARD_BR_TOKEN); } - private static Token standardizePToken(Token token) { + private static Token standardizePToken(final Token token) { return standardize(token, STANDARD_P_TOKEN); } - private static Token standardize(Token token, Token standardToken) { + private static Token standardize(final Token token, final Token standardToken) { return SIMPLE_TAG_PATTERN.matcher(token.getValue()).matches() ? standardToken : token; } @@ -165,21 +165,21 @@ private static Token standardize(Token token, Token standardToken) { * Returns the given string or a one-line version of it (e.g., "∕✱✱ Tests for foos. ✱∕") if it * fits on one line. */ - private static String makeSingleLineIfPossible(int blockIndent, String input) { - Matcher matcher = ONE_CONTENT_LINE_PATTERN.matcher(input); + private static String makeSingleLineIfPossible(final int blockIndent, final String input, final int maxWidth) { + final Matcher matcher = ONE_CONTENT_LINE_PATTERN.matcher(input); if (matcher.matches()) { - String line = matcher.group(1); + final String line = matcher.group(1); if (line.isEmpty()) { return "/** */"; - } else if (oneLineJavadoc(line, blockIndent)) { + } else if (oneLineJavadoc(line, blockIndent, maxWidth)) { return "/** " + line + " */"; } } return input; } - private static boolean oneLineJavadoc(String line, int blockIndent) { - int oneLinerContentLength = MAX_LINE_LENGTH - "/** */".length() - blockIndent; + private static boolean oneLineJavadoc(final String line, final int blockIndent, final int maxWidth) { + final int oneLinerContentLength = maxWidth - "/** */".length() - blockIndent; if (line.length() > oneLinerContentLength) { return false; } diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java index 0361415a1..bd436a0a0 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java @@ -14,21 +14,17 @@ package com.google.googlejavaformat.java.javadoc; +import com.google.common.collect.ImmutableSet; +import com.google.googlejavaformat.java.javadoc.Token.Type; + import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Comparators.max; import static com.google.common.collect.Sets.immutableEnumSet; import static com.google.googlejavaformat.java.javadoc.JavadocWriter.AutoIndent.AUTO_INDENT; import static com.google.googlejavaformat.java.javadoc.JavadocWriter.AutoIndent.NO_AUTO_INDENT; -import static com.google.googlejavaformat.java.javadoc.JavadocWriter.RequestedWhitespace.BLANK_LINE; -import static com.google.googlejavaformat.java.javadoc.JavadocWriter.RequestedWhitespace.NEWLINE; -import static com.google.googlejavaformat.java.javadoc.JavadocWriter.RequestedWhitespace.NONE; import static com.google.googlejavaformat.java.javadoc.JavadocWriter.RequestedWhitespace.WHITESPACE; -import static com.google.googlejavaformat.java.javadoc.Token.Type.HEADER_OPEN_TAG; -import static com.google.googlejavaformat.java.javadoc.Token.Type.LIST_ITEM_OPEN_TAG; -import static com.google.googlejavaformat.java.javadoc.Token.Type.PARAGRAPH_OPEN_TAG; - -import com.google.common.collect.ImmutableSet; -import com.google.googlejavaformat.java.javadoc.Token.Type; +import static com.google.googlejavaformat.java.javadoc.JavadocWriter.RequestedWhitespace.*; +import static com.google.googlejavaformat.java.javadoc.Token.Type.*; /** * Stateful object that accepts "requests" and "writes," producing formatted Javadoc. @@ -39,6 +35,8 @@ */ final class JavadocWriter { private final int blockIndent; + private final int maxWidth; + private final StringBuilder output = new StringBuilder(); /** * Whether we are inside an {@code
  • } element, excluding the case in which the {@code
  • } @@ -58,8 +56,9 @@ final class JavadocWriter { private int indentForMoeEndStripComment; private boolean wroteAnythingSignificant; - JavadocWriter(int blockIndent) { + JavadocWriter(final int blockIndent, final int maxWidth) { this.blockIndent = blockIndent; + this.maxWidth = maxWidth; } /** @@ -71,7 +70,7 @@ void requestWhitespace() { requestWhitespace(WHITESPACE); } - void requestMoeBeginStripComment(Token token) { + void requestMoeBeginStripComment(final Token token) { // We queue this up so that we can put it after any requested whitespace. requestedMoeBeginStripComment = checkNotNull(token); } @@ -91,7 +90,7 @@ void writeEndJavadoc() { output.append("*/"); } - void writeFooterJavadocTagStart(Token token) { + void writeFooterJavadocTagStart(final Token token) { // Close any unclosed lists (e.g.,
  • without
      ). // TODO(cpovirk): Actually generate
    , etc.? /* @@ -123,7 +122,7 @@ void writeFooterJavadocTagStart(Token token) { continuingFooterTag = true; } - void writeListOpen(Token token) { + void writeListOpen(final Token token) { requestBlankLine(); writeToken(token); @@ -134,7 +133,7 @@ void writeListOpen(Token token) { requestNewline(); } - void writeListClose(Token token) { + void writeListClose(final Token token) { requestNewline(); continuingListItemCount.decrementIfPositive(); @@ -145,7 +144,7 @@ void writeListClose(Token token) { requestBlankLine(); } - void writeListItemOpen(Token token) { + void writeListItemOpen(final Token token) { requestNewline(); if (continuingListItemOfInnermostList) { @@ -157,19 +156,19 @@ void writeListItemOpen(Token token) { continuingListItemCount.increment(); } - void writeHeaderOpen(Token token) { + void writeHeaderOpen(final Token token) { requestBlankLine(); writeToken(token); } - void writeHeaderClose(Token token) { + void writeHeaderClose(final Token token) { writeToken(token); requestBlankLine(); } - void writeParagraphOpen(Token token) { + void writeParagraphOpen(final Token token) { if (!wroteAnythingSignificant) { /* * The user included an initial

    tag. Ignore it, and don't request a blank line before the @@ -183,7 +182,7 @@ void writeParagraphOpen(Token token) { writeToken(token); } - void writeBlockquoteOpenOrClose(Token token) { + void writeBlockquoteOpenOrClose(final Token token) { requestBlankLine(); writeToken(token); @@ -191,39 +190,39 @@ void writeBlockquoteOpenOrClose(Token token) { requestBlankLine(); } - void writePreOpen(Token token) { + void writePreOpen(final Token token) { requestBlankLine(); writeToken(token); } - void writePreClose(Token token) { + void writePreClose(final Token token) { writeToken(token); requestBlankLine(); } - void writeCodeOpen(Token token) { + void writeCodeOpen(final Token token) { writeToken(token); } - void writeCodeClose(Token token) { + void writeCodeClose(final Token token) { writeToken(token); } - void writeTableOpen(Token token) { + void writeTableOpen(final Token token) { requestBlankLine(); writeToken(token); } - void writeTableClose(Token token) { + void writeTableClose(final Token token) { writeToken(token); requestBlankLine(); } - void writeMoeEndStripComment(Token token) { + void writeMoeEndStripComment(final Token token) { writeLineBreakNoAutoIndent(); appendSpaces(indentForMoeEndStripComment); @@ -233,7 +232,7 @@ void writeMoeEndStripComment(Token token) { requestNewline(); } - void writeHtmlComment(Token token) { + void writeHtmlComment(final Token token) { requestNewline(); writeToken(token); @@ -241,7 +240,7 @@ void writeHtmlComment(Token token) { requestNewline(); } - void writeBr(Token token) { + void writeBr(final Token token) { writeToken(token); requestNewline(); @@ -251,7 +250,7 @@ void writeLineBreakNoAutoIndent() { writeNewline(NO_AUTO_INDENT); } - void writeLiteral(Token token) { + void writeLiteral(final Token token) { writeToken(token); } @@ -268,7 +267,7 @@ private void requestNewline() { requestWhitespace(NEWLINE); } - private void requestWhitespace(RequestedWhitespace requestedWhitespace) { + private void requestWhitespace(final RequestedWhitespace requestedWhitespace) { this.requestedWhitespace = max(requestedWhitespace, this.requestedWhitespace); } @@ -286,7 +285,7 @@ enum RequestedWhitespace { ; } - private void writeToken(Token token) { + private void writeToken(final Token token) { if (requestedMoeBeginStripComment != null) { requestNewline(); } @@ -310,7 +309,7 @@ private void writeToken(Token token) { writeNewline(); requestedWhitespace = NONE; } - boolean needWhitespace = (requestedWhitespace == WHITESPACE); + final boolean needWhitespace = (requestedWhitespace == WHITESPACE); /* * Write a newline if necessary to respect the line limit. (But if we're at the beginning of the @@ -366,12 +365,12 @@ private void writeNewline() { writeNewline(AUTO_INDENT); } - private void writeNewline(AutoIndent autoIndent) { + private void writeNewline(final AutoIndent autoIndent) { output.append("\n"); appendSpaces(blockIndent + 1); output.append("*"); appendSpaces(1); - remainingOnLine = JavadocFormatter.MAX_LINE_LENGTH - blockIndent - 3; + remainingOnLine = maxWidth - blockIndent - 3; if (autoIndent == AUTO_INDENT) { appendSpaces(innerIndent()); remainingOnLine -= innerIndent(); @@ -393,7 +392,7 @@ private int innerIndent() { } // If this is a hotspot, keep a String of many spaces around, and call append(string, start, end). - private void appendSpaces(int count) { + private void appendSpaces(final int count) { output.append(" ".repeat(count)); } From a4137c6cffd5c48d8af262e2164da30f6936c549 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Fri, 16 Dec 2022 19:39:58 +0100 Subject: [PATCH 005/107] Prepare Release --- core/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index a049fd0cc..7a472ff40 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent - 1.15.0 + 1.15.0.1 configurable-google-java-format diff --git a/pom.xml b/pom.xml index 2dc0e4ba6..6cf194e91 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent pom - 1.15.0 + 1.15.0.1 core From 8a9734535da363c62ea192e5ae3274f08f1146a3 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Fri, 16 Dec 2022 20:47:20 +0100 Subject: [PATCH 006/107] Create maven-publish.yml --- .github/workflows/maven-publish.yml | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 .github/workflows/maven-publish.yml diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml new file mode 100644 index 000000000..dab69fef7 --- /dev/null +++ b/.github/workflows/maven-publish.yml @@ -0,0 +1,34 @@ +# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created +# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path + +name: Maven Package + +on: + release: + types: [created] + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 11 + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'temurin' + server-id: github # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + + - name: Build with Maven + run: mvn -B package --file pom.xml + + - name: Publish to GitHub Packages Apache Maven + run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml + env: + GITHUB_TOKEN: ${{ github.token }} From 34af2570e33618c1322f61149e5de669de1b20a3 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Fri, 16 Dec 2022 20:57:48 +0100 Subject: [PATCH 007/107] Prepare Release --- core/pom.xml | 2 +- pom.xml | 15 +-------------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 7a472ff40..5f6a6705f 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent - 1.15.0.1 + 1.15.0.2 configurable-google-java-format diff --git a/pom.xml b/pom.xml index 6cf194e91..f014d1b64 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent pom - 1.15.0.1 + 1.15.0.2 core @@ -301,19 +301,6 @@ - - - sonatype-nexus-snapshots - Sonatype Nexus Snapshots - https://oss.sonatype.org/content/repositories/snapshots/ - - - sonatype-nexus-staging - Nexus Release Repository - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - sonatype-oss-release From da9d7377dcf274eb3387a0373714d581be8e27e9 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 17:01:42 +0200 Subject: [PATCH 008/107] Merging upstream automatically --- .github/workflows/update-from-template.yml | 93 ++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 .github/workflows/update-from-template.yml diff --git a/.github/workflows/update-from-template.yml b/.github/workflows/update-from-template.yml new file mode 100644 index 000000000..d354dfeb6 --- /dev/null +++ b/.github/workflows/update-from-template.yml @@ -0,0 +1,93 @@ +name: Update from Template + +# This workflow keeps the repo up to date with changes from the template repo (REMOTE_URL) +# It duplicates the REMOTE_BRANCH (into UPDATE_BRANCH) and tries to merge it into +# this repos default branch (which is checked out here) +# Note that this requires a PAT (Personal Access Token) - at best from a servicing account +# Also note that you should have at least once merged the template repo into the current +# repo manually otherwise a "refusing to merge unrelated histories" error might occur. + +on: + schedule: + - cron: '55 2 * * 1' + workflow_dispatch: + +env: + UPDATE_BRANCH: update-from-template + REMOTE_URL: https://github.com/google/google-java-format.git + REMOTE_BRANCH: master + +permissions: + contents: write + pull-requests: write + +jobs: + update: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + # Required because otherwise there are always changes detected when executing diff/rev-list + fetch-depth: 0 + # If no PAT is used the following error occurs on a push: + # refusing to allow a GitHub App to create or update workflow `.github/workflows/xxx.yml` without `workflows` permission + token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + + - name: Init Git + run: | + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + - name: Main workflow + id: main + run: | + echo "Adding remote template-repo" + git remote add template ${{ env.REMOTE_URL }} + + echo "Fetching remote template repo" + git fetch template + + echo "Deleting local branch that will contain the updates - if present" + git branch -D ${{ env.UPDATE_BRANCH }} || true + + echo "Checking if the remote template repo has new commits" + git rev-list ..template/${{ env.REMOTE_BRANCH }} + + if [ $(git rev-list --count ..template/${{ env.REMOTE_BRANCH }}) -eq 0 ]; then + echo "There are no commits new commits on the template repo" + + echo "Deleting origin branch that contains the updates - if present" + git push -f origin --delete ${{ env.UPDATE_BRANCH }} || true + + echo "abort=1" >> $GITHUB_OUTPUT + exit 0 + fi + + echo "Found new commits on the template repo" + + echo "Creating update branch" + git branch ${{ env.UPDATE_BRANCH }} template/${{ env.REMOTE_BRANCH }} + git branch --unset-upstream ${{ env.UPDATE_BRANCH }} + + echo "Pushing update branch" + git push -f -u origin ${{ env.UPDATE_BRANCH }} + + echo "Getting current branch" + current_branch=$(git branch --show-current) + echo "Current branch is $current_branch" + echo "current_branch=$current_branch" >> $GITHUB_OUTPUT + + echo "abort=0" >> $GITHUB_OUTPUT + + - name: pull-request + if: steps.main.outputs.abort == 0 + env: + GH_TOKEN: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + run: | + gh_pr_up() { + gh pr create -H "${{ env.UPDATE_BRANCH }}" "$@" || (git checkout "${{ env.UPDATE_BRANCH }}" && gh pr edit "$@") + } + gh_pr_up -B "${{ steps.main.outputs.current_branch }}" \ + --title "Update from template" \ + --body "An automated PR to sync changes from the template into this repo" From 078d96ae91d5bb3848374078744e7bf1eca3094d Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 20:55:32 +0200 Subject: [PATCH 009/107] Merging upstream automatically --- eclipse_plugin/META-INF/MANIFEST.MF | 15 -- eclipse_plugin/README.md | 43 --- eclipse_plugin/build.properties | 7 - eclipse_plugin/plugin.xml | 28 -- eclipse_plugin/pom.xml | 141 ---------- .../java/GoogleJavaFormatter.java | 144 ---------- idea_plugin/.gitignore | 5 - idea_plugin/build.gradle.kts | 70 ----- .../GoogleJavaFormatConfigurable.form | 40 --- .../GoogleJavaFormatConfigurable.java | 206 --------------- .../GoogleJavaFormatFormattingService.java | 141 ---------- .../GoogleJavaFormatImportOptimizer.java | 90 ------- .../intellij/GoogleJavaFormatSettings.java | 115 -------- .../InitialConfigurationStartupActivity.java | 60 ----- .../intellij/JreConfigurationChecker.java | 104 -------- .../intellij/Notifications.java | 38 --- .../intellij/UiFormatterStyle.java | 52 ---- .../src/main/resources/META-INF/plugin.xml | 111 -------- ...GoogleJavaFormatFormattingServiceTest.java | 250 ------------------ .../GoogleJavaFormatImportOptimizerTest.java | 168 ------------ pom.xml | 9 - 21 files changed, 1837 deletions(-) delete mode 100644 eclipse_plugin/META-INF/MANIFEST.MF delete mode 100644 eclipse_plugin/README.md delete mode 100644 eclipse_plugin/build.properties delete mode 100644 eclipse_plugin/plugin.xml delete mode 100644 eclipse_plugin/pom.xml delete mode 100644 eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java delete mode 100644 idea_plugin/.gitignore delete mode 100644 idea_plugin/build.gradle.kts delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingService.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizer.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/InitialConfigurationStartupActivity.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/JreConfigurationChecker.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/Notifications.java delete mode 100644 idea_plugin/src/main/java/com/google/googlejavaformat/intellij/UiFormatterStyle.java delete mode 100644 idea_plugin/src/main/resources/META-INF/plugin.xml delete mode 100644 idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingServiceTest.java delete mode 100644 idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizerTest.java diff --git a/eclipse_plugin/META-INF/MANIFEST.MF b/eclipse_plugin/META-INF/MANIFEST.MF deleted file mode 100644 index 913245393..000000000 --- a/eclipse_plugin/META-INF/MANIFEST.MF +++ /dev/null @@ -1,15 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: google-java-format -Bundle-SymbolicName: google-java-format-eclipse-plugin;singleton:=true -Bundle-Vendor: Google -Bundle-Version: 1.13.0 -Bundle-RequiredExecutionEnvironment: JavaSE-11 -Require-Bundle: org.eclipse.jdt.core;bundle-version="3.10.0", - org.eclipse.jface, - org.eclipse.text, - org.eclipse.ui, - org.eclipse.equinox.common -Bundle-ClassPath: ., - lib/guava.jar, - lib/google-java-format.jar diff --git a/eclipse_plugin/README.md b/eclipse_plugin/README.md deleted file mode 100644 index 395a368dc..000000000 --- a/eclipse_plugin/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Google Java Format Eclipse Plugin - -## Enabling - -See https://github.com/google/google-java-format#eclipse - -## Development - -### Prerequisites - -Before building the plugin, make sure to run `mvn -tycho-versions:update-eclipse-metadata` to update the bundle version in -`META-INF/MANIFEST.MF`. - -### Building the Plugin - -1) Run `mvn clean package` in the `eclipse_plugin` directory. This will first copy the dependencies -of the plugin to `eclipse_plugin/lib/` and then triggers the tycho build that uses these -dependencies (as declared in `build.properties`) for the actual Eclipse plugin build.

    -If you also want to add the build artifact to the local maven repository, you can use -`mvn clean install -Dtycho.localArtifacts=ignore` instead. Note, however, that you then must use -this build command for every build with that specific version number until you clear the build -artifact (or the -[p2-local-metadata.properties](https://wiki.eclipse.org/Tycho/Target_Platform#Locally_built_artifacts)) -from your local repository. Otherwise, you might run into issues caused by the build using an -outdated build artifact created by a previous build instead of re-building the plugin. More -information on this issue is given -[in this thread](https://www.eclipse.org/lists/tycho-user/msg00952.html) and -[this bug tracker entry](https://bugs.eclipse.org/bugs/show_bug.cgi?id=355367). - -2) You can find the built plugin in -`eclipse_plugin/target/google-java-format-eclipse-plugin-.jar` - -#### Building against a local (snapshot) release of the core - -With the current build setup, the Eclipse plugin build pulls the needed build -artifacts of the google java format core from the maven repository and copies it -into the `eclipse_plugin/lib/` directory. - -If you instead want to build against a local (snapshot) build of the core which -is not available in a maven repository (local or otherwise), you will have to -place the appropriate version into the `eclipse_plugin/lib/` directory yourself -before the build. diff --git a/eclipse_plugin/build.properties b/eclipse_plugin/build.properties deleted file mode 100644 index dd1d835c5..000000000 --- a/eclipse_plugin/build.properties +++ /dev/null @@ -1,7 +0,0 @@ -source.. = src/ -output.. = target/classes -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - lib/guava.jar,\ - lib/google-java-format.jar diff --git a/eclipse_plugin/plugin.xml b/eclipse_plugin/plugin.xml deleted file mode 100644 index 1fdfb6e41..000000000 --- a/eclipse_plugin/plugin.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - diff --git a/eclipse_plugin/pom.xml b/eclipse_plugin/pom.xml deleted file mode 100644 index b2c6e368a..000000000 --- a/eclipse_plugin/pom.xml +++ /dev/null @@ -1,141 +0,0 @@ - - - - 4.0.0 - - com.google.googlejavaformat - google-java-format-eclipse-plugin - eclipse-plugin - 1.13.0 - - Google Java Format Plugin for Eclipse 4.5+ - - - A Java source code formatter plugin for Eclipse that follows Google Java Style. - - - - UTF-8 - 3.0.5 - - - - - com.google.googlejavaformat - google-java-format - ${project.version} - - - - - - mars - p2 - https://download.eclipse.org/releases/mars - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 3.3.0 - - - copy-dependencies - initialize - - copy-dependencies - - - - - lib - runtime - true - true - true - guava,google-java-format - - - - - org.eclipse.tycho - tycho-maven-plugin - ${tycho-version} - true - - - - org.eclipse.tycho - tycho-versions-plugin - ${tycho-version} - - ${project.version} - - - - - org.eclipse.tycho - target-platform-configuration - ${tycho-version} - - - - linux - gtk - x86 - - - linux - gtk - x86_64 - - - win32 - win32 - x86 - - - win32 - win32 - x86_64 - - - macosx - cocoa - x86_64 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.7.0 - - 11 - 11 - - - - - diff --git a/eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java b/eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java deleted file mode 100644 index c300514be..000000000 --- a/eclipse_plugin/src/com/google/googlejavaformat/java/GoogleJavaFormatter.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright 2017 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 com.google.common.base.Preconditions; -import com.google.common.collect.Range; -import com.google.googlejavaformat.java.SnippetFormatter.SnippetKind; -import java.util.ArrayList; -import java.util.List; -import org.eclipse.jdt.core.dom.ASTParser; -import org.eclipse.jdt.core.formatter.CodeFormatter; -import org.eclipse.jface.text.IRegion; -import org.eclipse.jface.text.Region; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; - -/** Runs the Google Java formatter on the given code. */ -public class GoogleJavaFormatter extends CodeFormatter { - - private static final int INDENTATION_SIZE = 2; - - @Override - public TextEdit format( - int kind, String source, int offset, int length, int indentationLevel, String lineSeparator) { - IRegion[] regions = new IRegion[] {new Region(offset, length)}; - return formatInternal(kind, source, regions, indentationLevel); - } - - @Override - public TextEdit format( - int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator) { - return formatInternal(kind, source, regions, indentationLevel); - } - - @Override - public String createIndentationString(int indentationLevel) { - Preconditions.checkArgument( - indentationLevel >= 0, - "Indentation level cannot be less than zero. Given: %s", - indentationLevel); - int spaces = indentationLevel * INDENTATION_SIZE; - StringBuilder buf = new StringBuilder(spaces); - for (int i = 0; i < spaces; i++) { - buf.append(' '); - } - return buf.toString(); - } - - /** Runs the Google Java formatter on the given source, with only the given ranges specified. */ - private TextEdit formatInternal(int kind, String source, IRegion[] regions, int initialIndent) { - try { - boolean includeComments = - (kind & CodeFormatter.F_INCLUDE_COMMENTS) == CodeFormatter.F_INCLUDE_COMMENTS; - kind &= ~CodeFormatter.F_INCLUDE_COMMENTS; - SnippetKind snippetKind; - switch (kind) { - case ASTParser.K_EXPRESSION: - snippetKind = SnippetKind.EXPRESSION; - break; - case ASTParser.K_STATEMENTS: - snippetKind = SnippetKind.STATEMENTS; - break; - case ASTParser.K_CLASS_BODY_DECLARATIONS: - snippetKind = SnippetKind.CLASS_BODY_DECLARATIONS; - break; - case ASTParser.K_COMPILATION_UNIT: - snippetKind = SnippetKind.COMPILATION_UNIT; - break; - default: - throw new IllegalArgumentException(String.format("Unknown snippet kind: %d", kind)); - } - List replacements = - new SnippetFormatter() - .format( - snippetKind, source, rangesFromRegions(regions), initialIndent, includeComments); - if (idempotent(source, regions, replacements)) { - // Do not create edits if there's no diff. - return null; - } - // Convert replacements to text edits. - return editFromReplacements(replacements); - } catch (IllegalArgumentException | FormatterException exception) { - // Do not format on errors. - return null; - } - } - - private List> rangesFromRegions(IRegion[] regions) { - List> ranges = new ArrayList<>(); - for (IRegion region : regions) { - ranges.add(Range.closedOpen(region.getOffset(), region.getOffset() + region.getLength())); - } - return ranges; - } - - /** @return {@code true} if input and output texts are equal, else {@code false}. */ - private boolean idempotent(String source, IRegion[] regions, List replacements) { - // This implementation only checks for single replacement. - if (replacements.size() == 1) { - Replacement replacement = replacements.get(0); - String output = replacement.getReplacementString(); - // Entire source case: input = output, nothing changed. - if (output.equals(source)) { - return true; - } - // Single region and single replacement case: if they are equal, nothing changed. - if (regions.length == 1) { - Range range = replacement.getReplaceRange(); - String snippet = source.substring(range.lowerEndpoint(), range.upperEndpoint()); - if (output.equals(snippet)) { - return true; - } - } - } - return false; - } - - private TextEdit editFromReplacements(List replacements) { - // Split the replacements that cross line boundaries. - TextEdit edit = new MultiTextEdit(); - for (Replacement replacement : replacements) { - Range replaceRange = replacement.getReplaceRange(); - edit.addChild( - new ReplaceEdit( - replaceRange.lowerEndpoint(), - replaceRange.upperEndpoint() - replaceRange.lowerEndpoint(), - replacement.getReplacementString())); - } - return edit; - } -} diff --git a/idea_plugin/.gitignore b/idea_plugin/.gitignore deleted file mode 100644 index 16bc65a53..000000000 --- a/idea_plugin/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -build -.gradle -gradle -gradlew -gradlew.bat \ No newline at end of file diff --git a/idea_plugin/build.gradle.kts b/idea_plugin/build.gradle.kts deleted file mode 100644 index 0ba5032dc..000000000 --- a/idea_plugin/build.gradle.kts +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2017 Google Inc. All Rights Reserved. - * - * 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. - */ - -// https://github.com/JetBrains/intellij-platform-gradle-plugin/releases -plugins { id("org.jetbrains.intellij") version "1.17.3" } - -apply(plugin = "org.jetbrains.intellij") - -apply(plugin = "java") - -repositories { mavenCentral() } - -// https://github.com/google/google-java-format/releases -val googleJavaFormatVersion = "1.22.0" - -java { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 -} - -intellij { - pluginName.set("google-java-format") - plugins.set(listOf("java")) - version.set("2021.3") -} - -tasks { - patchPluginXml { - version.set("${googleJavaFormatVersion}.0") - sinceBuild.set("213") - untilBuild.set("") - } - - publishPlugin { - val jetbrainsPluginRepoToken: String by project - token.set(jetbrainsPluginRepoToken) - } - - withType().configureEach { - jvmArgs( - "--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", - "--add-exports", "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", - "--add-exports", "jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED", - "--add-exports", "jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED", - "--add-exports", "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", - "--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", - ) - } -} - -dependencies { - implementation("com.google.googlejavaformat:google-java-format:${googleJavaFormatVersion}") - // https://mvnrepository.com/artifact/junit/junit - testImplementation("junit:junit:4.13.2") - // https://mvnrepository.com/artifact/com.google.truth/truth - testImplementation("com.google.truth:truth:1.4.2") -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form deleted file mode 100644 index 1db1d7920..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.form +++ /dev/null @@ -1,40 +0,0 @@ - -

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java deleted file mode 100644 index 759decc0f..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.googlejavaformat.intellij.GoogleJavaFormatSettings.EnabledState; -import com.intellij.openapi.options.BaseConfigurable; -import com.intellij.openapi.options.ConfigurationException; -import com.intellij.openapi.options.SearchableConfigurable; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.ui.ComboBox; -import com.intellij.uiDesigner.core.GridConstraints; -import com.intellij.uiDesigner.core.GridLayoutManager; -import com.intellij.uiDesigner.core.Spacer; -import java.awt.Insets; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -class GoogleJavaFormatConfigurable extends BaseConfigurable implements SearchableConfigurable { - - private final Project project; - private JPanel panel; - private JCheckBox enable; - private JComboBox styleComboBox; - - public GoogleJavaFormatConfigurable(Project project) { - this.project = project; - } - - @NotNull - @Override - public String getId() { - return "google-java-format.settings"; - } - - @Nullable - @Override - public Runnable enableSearch(String option) { - return null; - } - - @Nls - @Override - public String getDisplayName() { - return "google-java-format Settings"; - } - - @Nullable - @Override - public String getHelpTopic() { - return null; - } - - @Nullable - @Override - public JComponent createComponent() { - return panel; - } - - @Override - public void apply() throws ConfigurationException { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - settings.setEnabled(enable.isSelected() ? EnabledState.ENABLED : getDisabledState()); - settings.setStyle(((UiFormatterStyle) styleComboBox.getSelectedItem()).convert()); - } - - private EnabledState getDisabledState() { - // The default settings (inherited by new projects) are either 'enabled' or - // 'show notification'. There's no way to default new projects to disabled. If someone wants - // that, we can add another checkbox, I suppose. - return project.isDefault() ? EnabledState.UNKNOWN : EnabledState.DISABLED; - } - - @Override - public void reset() { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - enable.setSelected(settings.isEnabled()); - styleComboBox.setSelectedItem(UiFormatterStyle.convert(settings.getStyle())); - } - - @Override - public boolean isModified() { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - return enable.isSelected() != settings.isEnabled() - || !styleComboBox.getSelectedItem().equals(UiFormatterStyle.convert(settings.getStyle())); - } - - @Override - public void disposeUIResources() {} - - private void createUIComponents() { - styleComboBox = new ComboBox<>(UiFormatterStyle.values()); - } - - { - // GUI initializer generated by IntelliJ IDEA GUI Designer - // >>> IMPORTANT!! <<< - // DO NOT EDIT OR ADD ANY CODE HERE! - $$$setupUI$$$(); - } - - /** - * Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR - * call it in your code! - * - * @noinspection ALL - */ - private void $$$setupUI$$$() { - createUIComponents(); - panel = new JPanel(); - panel.setLayout(new GridLayoutManager(3, 2, new Insets(0, 0, 0, 0), -1, -1)); - enable = new JCheckBox(); - enable.setText("Enable google-java-format"); - panel.add( - enable, - new GridConstraints( - 0, - 0, - 1, - 2, - GridConstraints.ANCHOR_WEST, - GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, - null, - null, - null, - 0, - false)); - final Spacer spacer1 = new Spacer(); - panel.add( - spacer1, - new GridConstraints( - 2, - 0, - 1, - 2, - GridConstraints.ANCHOR_CENTER, - GridConstraints.FILL_VERTICAL, - 1, - GridConstraints.SIZEPOLICY_WANT_GROW, - null, - null, - null, - 0, - false)); - final JLabel label1 = new JLabel(); - label1.setText("Code style"); - panel.add( - label1, - new GridConstraints( - 1, - 0, - 1, - 1, - GridConstraints.ANCHOR_WEST, - GridConstraints.FILL_NONE, - GridConstraints.SIZEPOLICY_FIXED, - GridConstraints.SIZEPOLICY_FIXED, - null, - null, - null, - 0, - false)); - panel.add( - styleComboBox, - new GridConstraints( - 1, - 1, - 1, - 1, - GridConstraints.ANCHOR_WEST, - GridConstraints.FILL_HORIZONTAL, - GridConstraints.SIZEPOLICY_CAN_GROW, - GridConstraints.SIZEPOLICY_FIXED, - null, - null, - null, - 1, - false)); - } - - /** @noinspection ALL */ - public JComponent $$$getRootComponent$$$() { - return panel; - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingService.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingService.java deleted file mode 100644 index 9d2d7a595..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingService.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2023 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Range; -import com.google.googlejavaformat.java.Formatter; -import com.google.googlejavaformat.java.FormatterException; -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.google.googlejavaformat.java.JavaFormatterOptions.Style; -import com.intellij.formatting.service.AsyncDocumentFormattingService; -import com.intellij.formatting.service.AsyncFormattingRequest; -import com.intellij.ide.highlighter.JavaFileType; -import com.intellij.lang.ImportOptimizer; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.TextRange; -import com.intellij.psi.PsiFile; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -/** Uses {@code google-java-format} to reformat code. */ -public class GoogleJavaFormatFormattingService extends AsyncDocumentFormattingService { - - public static final ImmutableSet IMPORT_OPTIMIZERS = - ImmutableSet.of(new GoogleJavaFormatImportOptimizer()); - - @Override - protected FormattingTask createFormattingTask(AsyncFormattingRequest request) { - Project project = request.getContext().getProject(); - - if (!JreConfigurationChecker.checkJreConfiguration(project)) { - return null; - } - - Style style = GoogleJavaFormatSettings.getInstance(project).getStyle(); - Formatter formatter = createFormatter(style, request.canChangeWhitespaceOnly()); - return new GoogleJavaFormatFormattingTask(formatter, request); - } - - @Override - protected String getNotificationGroupId() { - return Notifications.PARSING_ERROR_NOTIFICATION_GROUP; - } - - @Override - protected String getName() { - return "google-java-format"; - } - - private static Formatter createFormatter(Style style, boolean canChangeWhiteSpaceOnly) { - JavaFormatterOptions.Builder optBuilder = JavaFormatterOptions.builder().style(style); - if (canChangeWhiteSpaceOnly) { - optBuilder.formatJavadoc(false).reorderModifiers(false); - } - return new Formatter(optBuilder.build()); - } - - @Override - public @NotNull Set getFeatures() { - return Set.of(Feature.FORMAT_FRAGMENTS, Feature.OPTIMIZE_IMPORTS); - } - - @Override - public boolean canFormat(@NotNull PsiFile file) { - return JavaFileType.INSTANCE.equals(file.getFileType()) - && GoogleJavaFormatSettings.getInstance(file.getProject()).isEnabled(); - } - - @Override - public @NotNull Set getImportOptimizers(@NotNull PsiFile file) { - return IMPORT_OPTIMIZERS; - } - - private static final class GoogleJavaFormatFormattingTask implements FormattingTask { - private final Formatter formatter; - private final AsyncFormattingRequest request; - - private GoogleJavaFormatFormattingTask(Formatter formatter, AsyncFormattingRequest request) { - this.formatter = formatter; - this.request = request; - } - - @Override - public void run() { - try { - String formattedText = formatter.formatSource(request.getDocumentText(), toRanges(request)); - request.onTextReady(formattedText); - } catch (FormatterException e) { - request.onError( - Notifications.PARSING_ERROR_TITLE, - Notifications.parsingErrorMessage(request.getContext().getContainingFile().getName())); - } - } - - private static Collection> toRanges(AsyncFormattingRequest request) { - if (isWholeFile(request)) { - // The IDE sometimes passes invalid ranges when the file is unsaved before invoking the - // formatter. So this is a workaround for that issue. - return ImmutableList.of(Range.closedOpen(0, request.getDocumentText().length())); - } - return request.getFormattingRanges().stream() - .map(textRange -> Range.closedOpen(textRange.getStartOffset(), textRange.getEndOffset())) - .collect(ImmutableList.toImmutableList()); - } - - private static boolean isWholeFile(AsyncFormattingRequest request) { - List ranges = request.getFormattingRanges(); - return ranges.size() == 1 - && ranges.get(0).getStartOffset() == 0 - // using greater than or equal because ranges are sometimes passed inaccurately - && ranges.get(0).getEndOffset() >= request.getDocumentText().length(); - } - - @Override - public boolean isRunUnderProgress() { - return true; - } - - @Override - public boolean cancel() { - return false; - } - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizer.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizer.java deleted file mode 100644 index 425124219..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizer.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2023 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.common.util.concurrent.Runnables; -import com.google.googlejavaformat.java.FormatterException; -import com.google.googlejavaformat.java.ImportOrderer; -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.google.googlejavaformat.java.RemoveUnusedImports; -import com.intellij.ide.highlighter.JavaFileType; -import com.intellij.lang.ImportOptimizer; -import com.intellij.openapi.editor.Document; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiDocumentManager; -import com.intellij.psi.PsiFile; -import org.jetbrains.annotations.NotNull; - -/** Uses {@code google-java-format} to optimize imports. */ -public class GoogleJavaFormatImportOptimizer implements ImportOptimizer { - - @Override - public boolean supports(@NotNull PsiFile file) { - return JavaFileType.INSTANCE.equals(file.getFileType()) - && GoogleJavaFormatSettings.getInstance(file.getProject()).isEnabled(); - } - - @Override - public @NotNull Runnable processFile(@NotNull PsiFile file) { - Project project = file.getProject(); - - if (!JreConfigurationChecker.checkJreConfiguration(file.getProject())) { - return Runnables.doNothing(); - } - - PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); - Document document = documentManager.getDocument(file); - - if (document == null) { - return Runnables.doNothing(); - } - - JavaFormatterOptions.Style style = GoogleJavaFormatSettings.getInstance(project).getStyle(); - - final String origText = document.getText(); - String text; - try { - text = ImportOrderer.reorderImports(RemoveUnusedImports.removeUnusedImports(origText), style); - } catch (FormatterException e) { - Notifications.displayParsingErrorNotification(project, file.getName()); - return Runnables.doNothing(); - } - - // pointless to change document text if it hasn't changed, plus this can interfere with - // e.g. GoogleJavaFormattingService's output, i.e. it can overwrite the results from the main - // formatter. - if (text.equals(origText)) { - return Runnables.doNothing(); - } - - return () -> { - if (documentManager.isDocumentBlockedByPsi(document)) { - documentManager.doPostponedOperationsAndUnblockDocument(document); - } - - // similarly to above, don't overwrite new document text if it has changed - we use - // getCharsSequence() as we should have `writeAction()` (which I think means effectively a - // write-lock) and it saves calling getText(), which apparently is expensive. - CharSequence newText = document.getCharsSequence(); - if (CharSequence.compare(origText, newText) != 0) { - return; - } - - document.setText(text); - }; - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java deleted file mode 100644 index 4546f68a3..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.intellij.openapi.components.PersistentStateComponent; -import com.intellij.openapi.components.State; -import com.intellij.openapi.components.Storage; -import com.intellij.openapi.project.Project; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -@State( - name = "GoogleJavaFormatSettings", - storages = {@Storage("google-java-format.xml")}) -class GoogleJavaFormatSettings implements PersistentStateComponent { - - private final Project project; - - private State state = new State(); - - GoogleJavaFormatSettings(Project project) { - this.project = project; - } - - static GoogleJavaFormatSettings getInstance(Project project) { - return project.getService(GoogleJavaFormatSettings.class); - } - - @Nullable - @Override - public State getState() { - return state; - } - - @Override - public void loadState(@NotNull State state) { - this.state = state; - } - - boolean isEnabled() { - return state.enabled.equals(EnabledState.ENABLED); - } - - void setEnabled(boolean enabled) { - setEnabled(enabled ? EnabledState.ENABLED : EnabledState.DISABLED); - } - - void setEnabled(EnabledState enabled) { - if (enabled.equals(EnabledState.ENABLED)) { - JreConfigurationChecker.checkJreConfiguration(project); - } - state.enabled = enabled; - } - - boolean isUninitialized() { - return state.enabled.equals(EnabledState.UNKNOWN); - } - - JavaFormatterOptions.Style getStyle() { - return state.style; - } - - void setStyle(JavaFormatterOptions.Style style) { - state.style = style; - } - - enum EnabledState { - UNKNOWN, - ENABLED, - DISABLED - } - - static class State { - - private EnabledState enabled = EnabledState.UNKNOWN; - public JavaFormatterOptions.Style style = JavaFormatterOptions.Style.GOOGLE; - - // enabled used to be a boolean so we use bean property methods for backwards compatibility - public void setEnabled(@Nullable String enabledStr) { - if (enabledStr == null) { - enabled = EnabledState.UNKNOWN; - } else if (Boolean.parseBoolean(enabledStr)) { - enabled = EnabledState.ENABLED; - } else { - enabled = EnabledState.DISABLED; - } - } - - public String getEnabled() { - switch (enabled) { - case ENABLED: - return "true"; - case DISABLED: - return "false"; - default: - return null; - } - } - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/InitialConfigurationStartupActivity.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/InitialConfigurationStartupActivity.java deleted file mode 100644 index 940def655..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/InitialConfigurationStartupActivity.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.intellij.notification.Notification; -import com.intellij.notification.NotificationGroup; -import com.intellij.notification.NotificationGroupManager; -import com.intellij.notification.NotificationType; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.startup.StartupActivity; -import org.jetbrains.annotations.NotNull; - -final class InitialConfigurationStartupActivity implements StartupActivity.Background { - - private static final String NOTIFICATION_TITLE = "Enable google-java-format"; - private static final NotificationGroup NOTIFICATION_GROUP = - NotificationGroupManager.getInstance().getNotificationGroup(NOTIFICATION_TITLE); - - @Override - public void runActivity(@NotNull Project project) { - GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - - if (settings.isUninitialized()) { - settings.setEnabled(false); - displayNewUserNotification(project, settings); - } else if (settings.isEnabled()) { - JreConfigurationChecker.checkJreConfiguration(project); - } - } - - private void displayNewUserNotification(Project project, GoogleJavaFormatSettings settings) { - Notification notification = - new Notification( - NOTIFICATION_GROUP.getDisplayId(), - NOTIFICATION_TITLE, - "The google-java-format plugin is disabled by default. " - + "Enable for this project.", - NotificationType.INFORMATION); - notification.setListener( - (n, e) -> { - settings.setEnabled(true); - n.expire(); - }); - notification.notify(project); - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/JreConfigurationChecker.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/JreConfigurationChecker.java deleted file mode 100644 index 5084b6a39..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/JreConfigurationChecker.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2023 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.common.base.Suppliers; -import com.intellij.ide.ui.IdeUiService; -import com.intellij.notification.Notification; -import com.intellij.notification.NotificationType; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.project.Project; -import java.util.function.Supplier; - -class JreConfigurationChecker { - - private static final Supplier hasAccess = - Suppliers.memoize(JreConfigurationChecker::checkJreConfiguration); - private static final Logger logger = Logger.getInstance(JreConfigurationChecker.class); - - private final Project project; - - public JreConfigurationChecker(Project project) { - this.project = project; - } - - static boolean checkJreConfiguration(Project project) { - var success = hasAccess.get(); - if (!success) { - project.getService(JreConfigurationChecker.class).displayConfigurationErrorNotification(); - } - return success; - } - - /** - * Determine whether the JRE is configured to work with the google-java-format plugin. If not, - * display a notification with instructions and return false. - */ - private static boolean checkJreConfiguration() { - try { - return testClassAccess( - "com.sun.tools.javac.api.JavacTrees", - "com.sun.tools.javac.code.Flags", - "com.sun.tools.javac.file.JavacFileManager", - "com.sun.tools.javac.parser.JavacParser", - "com.sun.tools.javac.tree.JCTree", - "com.sun.tools.javac.util.Log"); - } catch (ClassNotFoundException e) { - logger.error("Error checking jre configuration for google-java-format", e); - return false; - } - } - - private static boolean testClassAccess(String... classNames) throws ClassNotFoundException { - for (String className : classNames) { - if (!testClassAccess(className)) { - return false; - } - } - return true; - } - - private static boolean testClassAccess(String className) throws ClassNotFoundException { - Class klass = Class.forName(className); - return klass - .getModule() - // isExported returns true if the package is either open or exported. Either one is - // sufficient - // to run the google-java-format code (even though the documentation specifies --add-opens). - .isExported( - klass.getPackageName(), - JreConfigurationChecker.class.getClassLoader().getUnnamedModule()); - } - - private void displayConfigurationErrorNotification() { - Notification notification = - new Notification( - "Configure JRE for google-java-format", - "Configure the JRE for google-java-format", - "The google-java-format plugin needs additional configuration before it can be used. " - + "Follow the instructions here.", - NotificationType.INFORMATION); - notification.setListener( - (n, e) -> { - IdeUiService.getInstance() - .browse( - "https://github.com/google/google-java-format/blob/master/README.md#intellij-jre-config"); - n.expire(); - }); - notification.notify(project); - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/Notifications.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/Notifications.java deleted file mode 100644 index d32aa98b9..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/Notifications.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2023 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.intellij.formatting.service.FormattingNotificationService; -import com.intellij.openapi.project.Project; - -class Notifications { - - static final String PARSING_ERROR_NOTIFICATION_GROUP = "google-java-format parsing error"; - static final String PARSING_ERROR_TITLE = PARSING_ERROR_NOTIFICATION_GROUP; - - static String parsingErrorMessage(String filename) { - return "google-java-format failed. Does " + filename + " have syntax errors?"; - } - - static void displayParsingErrorNotification(Project project, String filename) { - FormattingNotificationService.getInstance(project) - .reportError( - Notifications.PARSING_ERROR_NOTIFICATION_GROUP, - Notifications.PARSING_ERROR_TITLE, - Notifications.parsingErrorMessage(filename)); - } -} diff --git a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/UiFormatterStyle.java b/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/UiFormatterStyle.java deleted file mode 100644 index 24ed6f62c..000000000 --- a/idea_plugin/src/main/java/com/google/googlejavaformat/intellij/UiFormatterStyle.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.google.googlejavaformat.java.JavaFormatterOptions.Style; -import java.util.Arrays; -import java.util.Objects; - -/** Configuration options for the formatting style. */ -enum UiFormatterStyle { - GOOGLE("Default Google Java style", Style.GOOGLE), - AOSP("Android Open Source Project (AOSP) style", Style.AOSP); - - private final String description; - private final JavaFormatterOptions.Style style; - - UiFormatterStyle(String description, JavaFormatterOptions.Style style) { - this.description = description; - this.style = style; - } - - @Override - public String toString() { - return description; - } - - public JavaFormatterOptions.Style convert() { - return style; - } - - static UiFormatterStyle convert(JavaFormatterOptions.Style style) { - return Arrays.stream(UiFormatterStyle.values()) - .filter(value -> Objects.equals(value.style, style)) - .findFirst() - .get(); - } -} diff --git a/idea_plugin/src/main/resources/META-INF/plugin.xml b/idea_plugin/src/main/resources/META-INF/plugin.xml deleted file mode 100644 index 378c2529c..000000000 --- a/idea_plugin/src/main/resources/META-INF/plugin.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - google-java-format - google-java-format - - Google - - - com.intellij.modules.java - com.intellij.modules.lang - com.intellij.modules.platform - - - - This plugin requires additional IDE configuration. For more information, - read - the documentation. - ]]> - -
    1.22.0.0
    -
    Updated to use google-java-format 1.22.0.
    -
    1.21.0.0
    -
    Updated to use google-java-format 1.21.0.
    -
    1.20.0.0
    -
    Updated to use google-java-format 1.20.0.
    -
    1.19.2.0
    -
    Updated to use google-java-format 1.19.2.
    -
    1.17.0.0
    -
    Updated to use google-java-format 1.17.0.
    -
    Fixed "Document is locked" errors (Thanks, @facboy!)
    -
    1.16.0.2
    -
    Disable AD_HOC_FORMATTING, which should stop the formatter from running so often when it wasn't specifically requested. -
    1.16.0.1
    -
    When the plugin isn't configured correctly, show the error on every - format command. Previously it was only being shown at startup and going - unnoticed. -
    1.16.0.0
    -
    Updated to use google-java-format 1.16.0.
    -
    Use the new IDE formatting APIs for a simplified plugin.
    -
    Optimize Imports now uses google-java-format.
    -
    1.15.0.0
    -
    Updated to use google-java-format 1.15.0.
    -
    1.14.0.0
    -
    Updated to use google-java-format 1.14.
    -
    1.13.0.0
    -
    Updated to use google-java-format 1.13.
    -
    1.12.0.0
    -
    Updated to use google-java-format 1.12.
    -
    1.11.0.0
    -
    Updated to use google-java-format 1.11.
    -
    1.10.0.0
    -
    Updated to use google-java-format 1.10.
    -
    1.9.0.0
    -
    Updated to use google-java-format 1.9.
    -
    1.8.0.1
    -
    Fixed support for 2020.2 IDEs.
    -
    1.8.0.0
    -
    Updated to use google-java-format 1.8.
    -
    1.7.0.5
    -
    Added a version for 2020.1+ IDEs.
    -
    1.7.0.4
    -
    Marked the plugin as being incompatible with 2020.1+ IDEs.
    -
    1.7.0.3
    -
    Fixed the plugin on 2019.3 IDEs.
    -
    1.7.0.2
    -
    Added support for all IDEs after 2017.3.
    -
    1.7.0.1
    -
    Added support for 2019.1 IDEs.
    -
    1.7.0.0
    -
    Upgraded to google-java-format 1.7.
    - - ]]>
    - - - - - - - - - - - - -
    diff --git a/idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingServiceTest.java b/idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingServiceTest.java deleted file mode 100644 index fec086c68..000000000 --- a/idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatFormattingServiceTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright 2023 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.common.collect.ImmutableList; -import com.google.googlejavaformat.intellij.GoogleJavaFormatSettings.State; -import com.google.googlejavaformat.java.Formatter; -import com.google.googlejavaformat.java.JavaFormatterOptions; -import com.google.googlejavaformat.java.JavaFormatterOptions.Style; -import com.intellij.formatting.service.AsyncFormattingRequest; -import com.intellij.formatting.service.FormattingService; -import com.intellij.formatting.service.FormattingServiceUtil; -import com.intellij.openapi.command.WriteCommandAction; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiFile; -import com.intellij.psi.codeStyle.CodeStyleManager; -import com.intellij.testFramework.ExtensionTestUtil; -import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; -import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; -import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; -import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; -import com.intellij.testFramework.fixtures.TestFixtureBuilder; -import java.io.IOException; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class GoogleJavaFormatFormattingServiceTest { - private JavaCodeInsightTestFixture fixture; - private GoogleJavaFormatSettings settings; - private DelegatingFormatter delegatingFormatter; - - @Before - public void setUp() throws Exception { - TestFixtureBuilder projectBuilder = - IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getClass().getName()); - fixture = - JavaTestFixtureFactory.getFixtureFactory() - .createCodeInsightFixture(projectBuilder.getFixture()); - fixture.setUp(); - - delegatingFormatter = new DelegatingFormatter(); - ExtensionTestUtil.maskExtensions( - FormattingService.EP_NAME, - ImmutableList.of(delegatingFormatter), - fixture.getProjectDisposable()); - - settings = GoogleJavaFormatSettings.getInstance(fixture.getProject()); - State resetState = new State(); - resetState.setEnabled("true"); - settings.loadState(resetState); - } - - @After - public void tearDown() throws Exception { - fixture.tearDown(); - } - - @Test - public void defaultFormatSettings() throws Exception { - PsiFile file = - createPsiFile( - "com/foo/FormatTest.java", - "package com.foo;", - "public class FormatTest {", - "static final String CONST_STR = \"Hello\";", - "}"); - String origText = file.getText(); - CodeStyleManager manager = CodeStyleManager.getInstance(file.getProject()); - WriteCommandAction.runWriteCommandAction( - file.getProject(), () -> manager.reformatText(file, 0, file.getTextLength())); - - assertThat(file.getText()).isEqualTo(new Formatter().formatSource(origText)); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - @Test - public void aospStyle() throws Exception { - settings.setStyle(Style.AOSP); - PsiFile file = - createPsiFile( - "com/foo/FormatTest.java", - "package com.foo;", - "public class FormatTest {", - "static final String CONST_STR = \"Hello\";", - "}"); - String origText = file.getText(); - CodeStyleManager manager = CodeStyleManager.getInstance(file.getProject()); - WriteCommandAction.runWriteCommandAction( - file.getProject(), () -> manager.reformatText(file, 0, file.getTextLength())); - - assertThat(file.getText()) - .isEqualTo( - new Formatter(JavaFormatterOptions.builder().style(Style.AOSP).build()) - .formatSource(origText)); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - @Test - public void canChangeWhitespaceOnlyDoesNotReorderModifiers() throws Exception { - settings.setStyle(Style.GOOGLE); - PsiFile file = - createPsiFile( - "com/foo/FormatTest.java", - "package com.foo;", - "public class FormatTest {", - "final static String CONST_STR = \"Hello\";", - "}"); - CodeStyleManager manager = CodeStyleManager.getInstance(file.getProject()); - var offset = file.getText().indexOf("final static"); - WriteCommandAction.runWriteCommandAction( - file.getProject(), - () -> - FormattingServiceUtil.formatElement( - file.findElementAt(offset), /* canChangeWhitespaceOnly= */ true)); - - // In non-whitespace mode, this would flip the order of these modifiers. (Also check for leading - // spaces to make sure the formatter actually ran. - assertThat(file.getText()).containsMatch(" final static"); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - @Test - public void canChangeWhitespaceOnlyDoesNotReformatJavadoc() throws Exception { - settings.setStyle(Style.GOOGLE); - PsiFile file = - createPsiFile( - "com/foo/FormatTest.java", - "package com.foo;", - "public class FormatTest {", - "/**", - " * hello", - " */", - "static final String CONST_STR = \"Hello\";", - "}"); - CodeStyleManager manager = CodeStyleManager.getInstance(file.getProject()); - var offset = file.getText().indexOf("hello"); - WriteCommandAction.runWriteCommandAction( - file.getProject(), - () -> - FormattingServiceUtil.formatElement( - file.findElementAt(offset), /* canChangeWhitespaceOnly= */ true)); - - // In non-whitespace mode, this would join the Javadoc into a single line. - assertThat(file.getText()).containsMatch(" \\* hello"); - // Also check for leading spaces to make sure the formatter actually ran. (Technically, this is - // outside the range that we asked to be formatted, but gjf will still format it.) - assertThat(file.getText()).containsMatch(" static final"); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - @Test - public void canChangeNonWhitespaceReordersModifiers() throws Exception { - settings.setStyle(Style.GOOGLE); - PsiFile file = - createPsiFile( - "com/foo/FormatTest.java", - "package com.foo;", - "public class FormatTest {", - "final static String CONST_STR = \"Hello\";", - "}"); - CodeStyleManager manager = CodeStyleManager.getInstance(file.getProject()); - var offset = file.getText().indexOf("final static"); - WriteCommandAction.runWriteCommandAction( - file.getProject(), - () -> - FormattingServiceUtil.formatElement( - file.findElementAt(offset), /* canChangeWhitespaceOnly= */ false)); - - assertThat(file.getText()).containsMatch("static final"); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - @Test - public void canChangeNonWhitespaceReformatsJavadoc() throws Exception { - settings.setStyle(Style.GOOGLE); - PsiFile file = - createPsiFile( - "com/foo/FormatTest.java", - "package com.foo;", - "public class FormatTest {", - "/**", - " * hello", - " */", - "static final String CONST_STR = \"Hello\";", - "}"); - CodeStyleManager manager = CodeStyleManager.getInstance(file.getProject()); - var offset = file.getText().indexOf("hello"); - WriteCommandAction.runWriteCommandAction( - file.getProject(), - () -> - FormattingServiceUtil.formatElement( - file.findElementAt(offset), /* canChangeWhitespaceOnly= */ false)); - - assertThat(file.getText()).containsMatch("/\\*\\* hello \\*/"); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - private PsiFile createPsiFile(String path, String... contents) throws IOException { - VirtualFile virtualFile = - fixture.getTempDirFixture().createFile(path, String.join("\n", contents)); - fixture.configureFromExistingVirtualFile(virtualFile); - PsiFile psiFile = fixture.getFile(); - assertThat(psiFile).isNotNull(); - return psiFile; - } - - private static final class DelegatingFormatter extends GoogleJavaFormatFormattingService { - - private boolean invoked = false; - - private boolean wasInvoked() { - return invoked; - } - - @Override - protected FormattingTask createFormattingTask(AsyncFormattingRequest request) { - FormattingTask delegateTask = super.createFormattingTask(request); - return new FormattingTask() { - @Override - public boolean cancel() { - return delegateTask.cancel(); - } - - @Override - public void run() { - invoked = true; - delegateTask.run(); - } - }; - } - } -} diff --git a/idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizerTest.java b/idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizerTest.java deleted file mode 100644 index ad9fe2744..000000000 --- a/idea_plugin/src/test/java/com/google/googlejavaformat/intellij/GoogleJavaFormatImportOptimizerTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2023 Google Inc. All Rights Reserved. - * - * 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.intellij; - -import static com.google.common.collect.ImmutableSet.toImmutableSet; -import static com.google.common.truth.Truth.assertThat; - -import com.google.common.collect.ImmutableList; -import com.google.googlejavaformat.intellij.GoogleJavaFormatSettings.State; -import com.intellij.codeInsight.actions.OptimizeImportsProcessor; -import com.intellij.formatting.service.FormattingService; -import com.intellij.lang.ImportOptimizer; -import com.intellij.openapi.command.WriteCommandAction; -import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.psi.PsiDocumentManager; -import com.intellij.psi.PsiFile; -import com.intellij.testFramework.ExtensionTestUtil; -import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; -import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; -import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture; -import com.intellij.testFramework.fixtures.JavaTestFixtureFactory; -import com.intellij.testFramework.fixtures.TestFixtureBuilder; -import java.io.IOException; -import java.util.Set; -import org.jetbrains.annotations.NotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class GoogleJavaFormatImportOptimizerTest { - private JavaCodeInsightTestFixture fixture; - private DelegatingFormatter delegatingFormatter; - - @Before - public void setUp() throws Exception { - TestFixtureBuilder projectBuilder = - IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getClass().getName()); - fixture = - JavaTestFixtureFactory.getFixtureFactory() - .createCodeInsightFixture(projectBuilder.getFixture()); - fixture.setUp(); - - delegatingFormatter = new DelegatingFormatter(); - ExtensionTestUtil.maskExtensions( - FormattingService.EP_NAME, - ImmutableList.of(delegatingFormatter), - fixture.getProjectDisposable()); - - var settings = GoogleJavaFormatSettings.getInstance(fixture.getProject()); - State resetState = new State(); - resetState.setEnabled("true"); - settings.loadState(resetState); - } - - @After - public void tearDown() throws Exception { - fixture.tearDown(); - } - - @Test - public void removesUnusedImports() throws Exception { - PsiFile file = - createPsiFile( - "com/foo/ImportTest.java", - "package com.foo;", - "import java.util.List;", - "import java.util.ArrayList;", - "import java.util.Map;", - "public class ImportTest {", - "static final Map map;", - "}"); - OptimizeImportsProcessor processor = new OptimizeImportsProcessor(file.getProject(), file); - WriteCommandAction.runWriteCommandAction( - file.getProject(), - () -> { - processor.run(); - PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); - }); - - assertThat(file.getText()).doesNotContain("List"); - assertThat(file.getText()).contains("import java.util.Map;"); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - @Test - public void reordersImports() throws Exception { - PsiFile file = - createPsiFile( - "com/foo/ImportTest.java", - "package com.foo;", - "import java.util.List;", - "import java.util.ArrayList;", - "import java.util.Map;", - "public class ImportTest {", - "static final ArrayList arrayList;", - "static final List list;", - "static final Map map;", - "}"); - OptimizeImportsProcessor processor = new OptimizeImportsProcessor(file.getProject(), file); - WriteCommandAction.runWriteCommandAction( - file.getProject(), - () -> { - processor.run(); - PsiDocumentManager.getInstance(file.getProject()).commitAllDocuments(); - }); - - assertThat(file.getText()) - .contains( - "import java.util.ArrayList;\n" - + "import java.util.List;\n" - + "import java.util.Map;\n"); - assertThat(delegatingFormatter.wasInvoked()).isTrue(); - } - - private PsiFile createPsiFile(String path, String... contents) throws IOException { - VirtualFile virtualFile = - fixture.getTempDirFixture().createFile(path, String.join("\n", contents)); - fixture.configureFromExistingVirtualFile(virtualFile); - PsiFile psiFile = fixture.getFile(); - assertThat(psiFile).isNotNull(); - return psiFile; - } - - private static final class DelegatingFormatter extends GoogleJavaFormatFormattingService { - - private boolean invoked = false; - - private boolean wasInvoked() { - return invoked; - } - - @Override - public @NotNull Set getImportOptimizers(@NotNull PsiFile file) { - return super.getImportOptimizers(file).stream().map(this::wrap).collect(toImmutableSet()); - } - - private ImportOptimizer wrap(ImportOptimizer delegate) { - return new ImportOptimizer() { - @Override - public boolean supports(@NotNull PsiFile file) { - return delegate.supports(file); - } - - @Override - public @NotNull Runnable processFile(@NotNull PsiFile file) { - return () -> { - invoked = true; - delegate.processFile(file).run(); - }; - } - }; - } - } -} diff --git a/pom.xml b/pom.xml index 152fdfde2..8bce5539a 100644 --- a/pom.xml +++ b/pom.xml @@ -358,14 +358,5 @@ - - eclipse - - [17,) - - - eclipse_plugin - - From c7c77c6358abe0ce5cc986f1a12801db2ecf8f70 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 21:36:39 +0200 Subject: [PATCH 010/107] Setup workflows --- .github/workflows/cgjf-release.yml | 19 +++++++++++++++++++ ...late.yml => cgjf-update-from-upstream.yml} | 0 cgjf-release.md | 3 +++ 3 files changed, 22 insertions(+) create mode 100644 .github/workflows/cgjf-release.yml rename .github/workflows/{update-from-template.yml => cgjf-update-from-upstream.yml} (100%) create mode 100644 cgjf-release.md diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml new file mode 100644 index 000000000..b35aeba84 --- /dev/null +++ b/.github/workflows/cgjf-release.yml @@ -0,0 +1,19 @@ +name: Releases + +on: + push: + tags: + - '*' + +jobs: + + build: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@v3 + - uses: ncipollo/release-action@v1 + with: + artifacts: "core/target/google-java-format-*.jar" + bodyFile: "cgjf-release.md" \ No newline at end of file diff --git a/.github/workflows/update-from-template.yml b/.github/workflows/cgjf-update-from-upstream.yml similarity index 100% rename from .github/workflows/update-from-template.yml rename to .github/workflows/cgjf-update-from-upstream.yml diff --git a/cgjf-release.md b/cgjf-release.md new file mode 100644 index 000000000..f6b94d034 --- /dev/null +++ b/cgjf-release.md @@ -0,0 +1,3 @@ +# configurable google java format + +automatic release \ No newline at end of file From 7bf9d88ea0af1d3d533fcb4ac18a1d403d340779 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 21:55:23 +0200 Subject: [PATCH 011/107] merge upstream --- pom.xml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/pom.xml b/pom.xml index 10888ccc3..69d399039 100644 --- a/pom.xml +++ b/pom.xml @@ -67,18 +67,6 @@ - - http://github.com/google/google-java-format/ - scm:git:git://github.com/google/google-java-format.git - scm:git:ssh://git@github.com/google/google-java-format.git - HEAD - - - - GitHub Issues - http://github.com/google/google-java-format/issues - - 3.0.3 From acf3d188eee31c67115dcaad7ef9b87794f671f5 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:03:58 +0200 Subject: [PATCH 012/107] prepare release --- core/pom.xml | 2 +- pom.xml | 2 +- scripts/google-java-format-diff.py | 162 ----------------------------- util/publish-snapshot-on-commit.sh | 26 ----- util/settings.xml | 25 ----- util/test-native.sh | 30 ------ 6 files changed, 2 insertions(+), 245 deletions(-) delete mode 100755 scripts/google-java-format-diff.py delete mode 100755 util/publish-snapshot-on-commit.sh delete mode 100644 util/settings.xml delete mode 100755 util/test-native.sh diff --git a/core/pom.xml b/core/pom.xml index 5dc226078..61c4bfc18 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent - 2024.21.0 + 2024.21.1 configurable-google-java-format diff --git a/pom.xml b/pom.xml index 69d399039..87f1138a4 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent pom - 2024.21.0 + 2024.21.1 core diff --git a/scripts/google-java-format-diff.py b/scripts/google-java-format-diff.py deleted file mode 100755 index 7f52ed1ec..000000000 --- a/scripts/google-java-format-diff.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python3 -# -# ===- google-java-format-diff.py - google-java-format Diff Reformatter -----===# -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open Source -# License. See LICENSE.TXT for details. -# -# ===------------------------------------------------------------------------===# - -""" -google-java-format Diff Reformatter -============================ - -This script reads input from a unified diff and reformats all the changed -lines. This is useful to reformat all the lines touched by a specific patch. -Example usage for git/svn users: - - git diff -U0 HEAD^ | google-java-format-diff.py -p1 -i - svn diff --diff-cmd=diff -x-U0 | google-java-format-diff.py -i - -For perforce users: - - P4DIFF="git --no-pager diff --no-index" p4 diff | ./google-java-format-diff.py -i -p7 - -""" - -import argparse -import difflib -import re -import string -import subprocess -import io -import sys -from concurrent.futures import ThreadPoolExecutor,wait,FIRST_EXCEPTION -from shutil import which - -def _apply_format(filename, lines, base_command, args): - """Apply format on filename.""" - if args.i and args.verbose: - print('Formatting', filename) - - command = base_command[:] - command.extend(lines) - command.append(filename) - p = subprocess.Popen(command, stdout=subprocess.PIPE, - stderr=None, stdin=subprocess.PIPE) - stdout, _ = p.communicate() - if p.returncode != 0: - sys.exit(p.returncode) - - if not args.i: - with open(filename) as f: - code = f.readlines() - formatted_code = io.StringIO(stdout.decode('utf-8')).readlines() - diff = difflib.unified_diff(code, formatted_code, - filename, filename, - '(before formatting)', '(after formatting)') - diff_string = ''.join(diff) - if len(diff_string) > 0: - sys.stdout.write(diff_string) - -def main(): - parser = argparse.ArgumentParser(description= - 'Reformat changed lines in diff. Without -i ' - 'option just output the diff that would be ' - 'introduced.') - parser.add_argument('-i', action='store_true', default=False, - help='apply edits to files instead of displaying a diff') - - parser.add_argument('-p', metavar='NUM', default=0, - help='strip the smallest prefix containing P slashes') - parser.add_argument('-regex', metavar='PATTERN', default=None, - help='custom pattern selecting file paths to reformat ' - '(case sensitive, overrides -iregex)') - parser.add_argument('-iregex', metavar='PATTERN', default=r'.*\.java', - help='custom pattern selecting file paths to reformat ' - '(case insensitive, overridden by -regex)') - parser.add_argument('-v', '--verbose', action='store_true', - help='be more verbose, ineffective without -i') - parser.add_argument('-a', '--aosp', action='store_true', - help='use AOSP style instead of Google Style (4-space indentation)') - parser.add_argument('--skip-sorting-imports', action='store_true', - help='do not fix the import order') - parser.add_argument('--skip-removing-unused-imports', action='store_true', - help='do not remove ununsed imports') - parser.add_argument( - '--skip-javadoc-formatting', - action='store_true', - default=False, - help='do not reformat javadoc') - parser.add_argument('-b', '--binary', help='path to google-java-format binary') - parser.add_argument('--google-java-format-jar', metavar='ABSOLUTE_PATH', default=None, - help='use a custom google-java-format jar') - - args = parser.parse_args() - - # Extract changed lines for each file. - filename = None - lines_by_file = {} - - for line in sys.stdin: - match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line) - if match: - filename = match.group(2) - if filename == None: - continue - - if args.regex is not None: - if not re.match('^%s$' % args.regex, filename): - continue - else: - if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE): - continue - - match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line) - if match: - start_line = int(match.group(1)) - line_count = 1 - if match.group(3): - line_count = int(match.group(3)) - if line_count == 0: - continue - end_line = start_line + line_count - 1; - lines_by_file.setdefault(filename, []).extend( - ['-lines', str(start_line) + ':' + str(end_line)]) - - if args.binary: - base_command = [args.binary] - elif args.google_java_format_jar: - base_command = ['java', '-jar', args.google_java_format_jar] - else: - binary = which('google-java-format') or '/usr/bin/google-java-format' - base_command = [binary] - - if args.i: - base_command.append('-i') - if args.aosp: - base_command.append('--aosp') - if args.skip_sorting_imports: - base_command.append('--skip-sorting-imports') - if args.skip_removing_unused_imports: - base_command.append('--skip-removing-unused-imports') - if args.skip_javadoc_formatting: - base_command.append('--skip-javadoc-formatting') - - with ThreadPoolExecutor() as executor: - format_futures = [] - for filename, lines in lines_by_file.items(): - format_futures.append( - executor.submit(_apply_format, filename, lines, base_command, args) - ) - - done, _ = wait(format_futures, return_when=FIRST_EXCEPTION) - for future in done: - if exception := future.exception(): - executor.shutdown(wait=True, cancel_futures=True) - sys.exit(exception.args[0]) - -if __name__ == '__main__': - main() diff --git a/util/publish-snapshot-on-commit.sh b/util/publish-snapshot-on-commit.sh deleted file mode 100755 index c14368da1..000000000 --- a/util/publish-snapshot-on-commit.sh +++ /dev/null @@ -1,26 +0,0 @@ -# Copyright 2020 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. - -# https://github.com/google/dagger/blob/master/util/publish-snapshot-on-commit.sh - -if [ "$TRAVIS_REPO_SLUG" == "google/google-java-format" ] && \ - [ "$TRAVIS_JDK_VERSION" == "oraclejdk8" ] && \ - [ "$TRAVIS_PULL_REQUEST" == "false" ] && \ - [ "$TRAVIS_BRANCH" == "master" ]; then - echo -e "Publishing maven snapshot...\n" - - mvn clean source:jar deploy --settings="util/settings.xml" -DskipTests=true -Dinvoker.skip=true -Dmaven.javadoc.skip=true - - echo -e "Published maven snapshot" -fi diff --git a/util/settings.xml b/util/settings.xml deleted file mode 100644 index aea3d4ef7..000000000 --- a/util/settings.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - sonatype-nexus-snapshots - ${env.CI_DEPLOY_USERNAME} - ${env.CI_DEPLOY_PASSWORD} - - - diff --git a/util/test-native.sh b/util/test-native.sh deleted file mode 100755 index a8643baf2..000000000 --- a/util/test-native.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2024 The Google Java Format Authors -# -# 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. - -set -euox pipefail - -time java -jar core/target/google-java-format-*-all-deps.jar || true - -status=-1 -chmod +x core/target/google-java-format -if time core/target/google-java-format; then - status=0 -else - status=$? -fi -if [[ $status -ne 2 ]]; then - echo "google-java-format_linux (native) without arguments should have printed usage help and exited with 2, but did not :(" - exit 1 -fi From e0dc2657d99bc5a31b2e3fae4ff8ea2a9073ea21 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:14:23 +0200 Subject: [PATCH 013/107] remove unused workflows --- .github/workflows/ci.yml | 57 ---------------------------------------- 1 file changed, 57 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c623efe38..718da43bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,60 +71,3 @@ jobs: - name: "Test" shell: bash run: mvn test -B - - test-GraalVM: - name: "GraalVM on ${{ matrix.os }}" - strategy: - fail-fast: false - matrix: - # Use "oldest" available ubuntu-* instead of -latest, - # see https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories; - # due to https://github.com/google/google-java-format/issues/1072. - os: [ubuntu-20.04, macos-latest, windows-latest] - runs-on: ${{ matrix.os }} - continue-on-error: true - steps: - - name: Cancel previous - uses: styfle/cancel-workflow-action@0.9.1 - with: - access_token: ${{ github.token }} - - name: "Check out repository" - uses: actions/checkout@v4 - - name: "Set up GraalVM ${{ matrix.java }}" - uses: graalvm/setup-graalvm@v1 - with: - java-version: "21" - distribution: "graalvm-community" - github-token: ${{ secrets.GITHUB_TOKEN }} - native-image-job-reports: "true" - cache: "maven" - - name: "Native Build" - run: mvn -Pnative -DskipTests package -pl core -am - - name: "Native Test" - # Bash script for testing won't work on Windows - # TODO: Anyone reading this wants to write a *.bat or *.ps1 equivalent? - if: ${{ matrix.os != 'windows-latest' }} - run: util/test-native.sh - - publish_snapshot: - name: "Publish snapshot" - needs: test-OpenJDK - if: github.event_name == 'push' && github.repository == 'google/google-java-format' && github.ref == 'refs/heads/master' - runs-on: ubuntu-latest - steps: - - name: "Check out repository" - uses: actions/checkout@v4 - - name: "Set up JDK 17" - uses: actions/setup-java@v4 - with: - java-version: 17 - distribution: "zulu" - cache: "maven" - server-id: sonatype-nexus-snapshots - server-username: CI_DEPLOY_USERNAME - server-password: CI_DEPLOY_PASSWORD - - name: "Publish" - env: - CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} - CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} - run: mvn -pl '!eclipse_plugin' source:jar deploy -B -DskipTests=true -Dinvoker.skip=true -Dmaven.javadoc.skip=true From fda6c795ef86d01bb5d0a0117378c84332a0c930 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:16:17 +0200 Subject: [PATCH 014/107] setup workflows --- .github/workflows/{ci.yml => cgjf-ci.yml} | 1 + 1 file changed, 1 insertion(+) rename .github/workflows/{ci.yml => cgjf-ci.yml} (99%) diff --git a/.github/workflows/ci.yml b/.github/workflows/cgjf-ci.yml similarity index 99% rename from .github/workflows/ci.yml rename to .github/workflows/cgjf-ci.yml index 718da43bf..7120efe8d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/cgjf-ci.yml @@ -1,4 +1,5 @@ # Copyright 2020 The Google Java Format Authors +# changed by MrDolch # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 94de218b66841356a116d6691db046a096bf2d28 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:28:07 +0200 Subject: [PATCH 015/107] setup workflows --- .github/workflows/cgjf-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index b35aeba84..02131a2dc 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -15,5 +15,5 @@ jobs: - uses: actions/checkout@v3 - uses: ncipollo/release-action@v1 with: - artifacts: "core/target/google-java-format-*.jar" + artifacts: "core/target/configurable-google-java-format-*.jar" bodyFile: "cgjf-release.md" \ No newline at end of file From cd34eb7799e5963531b37d8c0bca4c0ee13a2352 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:32:49 +0200 Subject: [PATCH 016/107] setup workflows --- .github/workflows/cgjf-release.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index 02131a2dc..335afa2dd 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -13,6 +13,9 @@ jobs: contents: write steps: - uses: actions/checkout@v3 + - name: Build with Maven + uses: actions/setup-java@v4 + run: mvn -B package --file pom.xml - uses: ncipollo/release-action@v1 with: artifacts: "core/target/configurable-google-java-format-*.jar" From 86eb2b0014da21fa0bd362bf4efc580a100b3a38 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:36:21 +0200 Subject: [PATCH 017/107] setup workflows --- .github/workflows/cgjf-release.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index 335afa2dd..f06e31d28 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -14,7 +14,6 @@ jobs: steps: - uses: actions/checkout@v3 - name: Build with Maven - uses: actions/setup-java@v4 run: mvn -B package --file pom.xml - uses: ncipollo/release-action@v1 with: From 8e66c32bf4bd52eb488f8ab47495911883ecbb1b Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sat, 20 Apr 2024 22:38:52 +0200 Subject: [PATCH 018/107] setup workflows --- .github/workflows/cgjf-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index f06e31d28..7828d6b7f 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -14,7 +14,7 @@ jobs: steps: - uses: actions/checkout@v3 - name: Build with Maven - run: mvn -B package --file pom.xml + run: mvn verify -DskipTests=true -Dmaven.javadoc.skip=true -B -V - uses: ncipollo/release-action@v1 with: artifacts: "core/target/configurable-google-java-format-*.jar" From bbe415574dafdfcad0f5f086677cafd56f54a765 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Sun, 21 Apr 2024 07:16:23 +0200 Subject: [PATCH 019/107] Update cgjf-release.yml --- .github/workflows/cgjf-release.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index 7828d6b7f..9e2410b9b 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -13,9 +13,14 @@ jobs: contents: write steps: - uses: actions/checkout@v3 + - name: "Set up JDK 21 from Zulu" + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: "zulu" - name: Build with Maven run: mvn verify -DskipTests=true -Dmaven.javadoc.skip=true -B -V - uses: ncipollo/release-action@v1 with: artifacts: "core/target/configurable-google-java-format-*.jar" - bodyFile: "cgjf-release.md" \ No newline at end of file + bodyFile: "cgjf-release.md" From 59d10633fcec0a76cef54d448f2399b4e0ffc50f Mon Sep 17 00:00:00 2001 From: chris Date: Fri, 31 Jan 2025 18:39:44 +0000 Subject: [PATCH 020/107] Prepare Release --- core/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index d4f53df3b..0dd1fa3b3 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent - 2024.21.1 + 2025.21.1 configurable-google-java-format diff --git a/pom.xml b/pom.xml index c939f469e..99edd6ca7 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent pom - 2024.21.1 + 2025.21.1 core From 2364e1e02655cc328b8380d7e3a3c7957a2daa44 Mon Sep 17 00:00:00 2001 From: chris Date: Fri, 31 Jan 2025 18:59:53 +0000 Subject: [PATCH 021/107] Upgrade to JDK 17 --- .github/workflows/maven-publish.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index dab69fef7..d91a9b134 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -17,10 +17,10 @@ jobs: steps: - uses: actions/checkout@v3 - - name: Set up JDK 11 + - name: Set up JDK 17 uses: actions/setup-java@v3 with: - java-version: '11' + java-version: '17' distribution: 'temurin' server-id: github # Value of the distributionManagement/repository/id field of the pom.xml settings-path: ${{ github.workspace }} # location for the settings.xml file From dcd1900f5681a57491b31f633cd9d29a54e1385f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 19:14:53 +0000 Subject: [PATCH 022/107] Add renovate.json --- renovate.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 renovate.json diff --git a/renovate.json b/renovate.json new file mode 100644 index 000000000..5db72dd6a --- /dev/null +++ b/renovate.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:recommended" + ] +} From 473d83a7f6c8c2bce067f69d6210f76a89fec8d0 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 19:17:26 +0000 Subject: [PATCH 023/107] Update dependency org.apache.felix:maven-bundle-plugin to v5.1.9 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 99edd6ca7..c086654d5 100644 --- a/pom.xml +++ b/pom.xml @@ -169,7 +169,7 @@ org.apache.felix maven-bundle-plugin - 5.1.4 + 5.1.9 From 496525cfec606593c3dd8759d4eb2f29528c0591 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 19:17:29 +0000 Subject: [PATCH 024/107] Update dependency org.graalvm.buildtools:native-maven-plugin to v0.10.4 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index 0dd1fa3b3..ec27e6092 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -255,7 +255,7 @@ org.graalvm.buildtools native-maven-plugin - 0.10.0 + 0.10.4 true From ad9cb9b2cd0d6b84da0fed385cf0aa09b8e4d7c8 Mon Sep 17 00:00:00 2001 From: chris Date: Fri, 31 Jan 2025 20:55:54 +0000 Subject: [PATCH 025/107] Update documentation, enable args by environment --- CONTRIBUTING.md | 29 --- README.adoc | 27 +++ README.md | 180 ------------------ core/pom.xml | 2 +- .../java/CommandLineOptionsParser.java | 21 +- .../java/CommandLineOptionsParserTest.java | 19 ++ pom.xml | 2 +- 7 files changed, 68 insertions(+), 212 deletions(-) delete mode 100644 CONTRIBUTING.md create mode 100644 README.adoc delete mode 100644 README.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 0f5b8cf48..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,29 +0,0 @@ -Want to contribute? Great! First, read this page (including the small print at -the end). - -### Before you contribute - -Before we can use your code, you must sign the [Google Individual Contributor -License -Agreement](https://developers.google.com/open-source/cla/individual?csw=1) -(CLA), which you can do online. The CLA is necessary mainly because you own the -copyright to your changes, even after your contribution becomes part of our -codebase, so we need your permission to use and distribute your code. We also -need to be sure of various other things—for instance that you'll tell us if you -know that your code infringes on other people's patents. You don't have to sign -the CLA until after you've submitted your code for review and a member has -approved it, but you must do it before we can put your code into our codebase. -Before you start working on a larger contribution, you should get in touch with -us first through the issue tracker with your idea so that we can help out and -possibly guide you. Coordinating up front makes it much easier to avoid -frustration later on. - -### Code reviews - -All submissions, including submissions by project members, require review. We -use GitHub pull requests for this purpose. - -### The small print - -Contributions made by corporations are covered by a different agreement than the -one above, the Software Grant and Corporate Contributor License Agreement. diff --git a/README.adoc b/README.adoc new file mode 100644 index 000000000..2cfea15c3 --- /dev/null +++ b/README.adoc @@ -0,0 +1,27 @@ += Configurable Google Java Format + +This project is a fork of `google-java-format`, an automatic code formatter for Java. + +== Changes from the Original + +- Removed all plugins – this fork contains only the core formatter. +- Added the `--width` option to specify a custom page width. +- Supports setting options via environment variables. + +== Usage + +```sh +java -jar configurable-google-java-format.jar --width=120 File.java +``` + +Alternatively, options can be passed as environment variables: + +```sh +export JAVA_FORMAT_WIDTH=120 +java -jar configurable-google-java-format.jar File.java +``` + +== License + +This project is based on `google-java-format` and follows the same licensing terms. + diff --git a/README.md b/README.md deleted file mode 100644 index 83a524bbd..000000000 --- a/README.md +++ /dev/null @@ -1,180 +0,0 @@ -# google-java-format - -`google-java-format` is a program that reformats Java source code to comply with -[Google Java Style][]. - -[Google Java Style]: https://google.github.io/styleguide/javaguide.html - -## Using the formatter - -### From the command-line - -[Download the formatter](https://github.com/google/google-java-format/releases) -and run it with: - -``` -java -jar /path/to/google-java-format-${GJF_VERSION?}-all-deps.jar [files...] -``` - -The formatter can act on whole files, on limited lines (`--lines`), on specific -offsets (`--offset`), passing through to standard-out (default) or altered -in-place (`--replace`). - -To reformat changed lines in a specific patch, use -[`google-java-format-diff.py`](https://github.com/google/google-java-format/blob/master/scripts/google-java-format-diff.py). - -***Note:*** *There is no configurability as to the formatter's algorithm for -formatting. This is a deliberate design decision to unify our code formatting on -a single format.* - -### IntelliJ, Android Studio, and other JetBrains IDEs - -A -[google-java-format IntelliJ plugin](https://plugins.jetbrains.com/plugin/8527) -is available from the plugin repository. To install it, go to your IDE's -settings and select the `Plugins` category. Click the `Marketplace` tab, search -for the `google-java-format` plugin, and click the `Install` button. - -The plugin will be disabled by default. To enable, -[open the Project settings](https://www.jetbrains.com/help/idea/configure-project-settings.html), -then click "google-java-format Settings" and check the "Enable -google-java-format" checkbox. - -To enable it by default in new projects, -[open the default settings for new projects](https://www.jetbrains.com/help/idea/configure-project-settings.html#new-default-settings) -and configure it under "Other Settings/google-java-format Settings". - -When enabled, it will replace the normal `Reformat Code` and `Optimize Imports` -actions. - -#### IntelliJ JRE Config - -The google-java-format plugin uses some internal classes that aren't available -without extra configuration. To use the plugin, you need to -[add some options to your IDE's Java runtime](https://www.jetbrains.com/help/idea/tuning-the-ide.html#procedure-jvm-options). -To do that, go to `Help→Edit Custom VM Options...` and paste in these lines: - -``` ---add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED -``` - -Once you've done that, restart the IDE. - -### Eclipse - -The latest version of the `google-java-format` Eclipse plugin can be downloaded -from the [releases page](https://github.com/google/google-java-format/releases). -Drop it into the Eclipse -[drop-ins folder](http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fp2_dropins_format.html) -to activate the plugin. - -The plugin adds a `google-java-format` formatter implementation that can be -configured in `Window > Preferences > Java > Code Style > Formatter > Formatter -Implementation`. - -### Third-party integrations - -* Visual Studio Code - * [google-java-format-for-vs-code](https://marketplace.visualstudio.com/items?itemName=JoseVSeb.google-java-format-for-vs-code) -* Gradle plugins - * [spotless](https://github.com/diffplug/spotless/tree/main/plugin-gradle#google-java-format) - * [sherter/google-java-format-gradle-plugin](https://github.com/sherter/google-java-format-gradle-plugin) -* Apache Maven plugins - * [spotless](https://github.com/diffplug/spotless/tree/main/plugin-maven#google-java-format) - * [spotify/fmt-maven-plugin](https://github.com/spotify/fmt-maven-plugin) - * [talios/googleformatter-maven-plugin](https://github.com/talios/googleformatter-maven-plugin) - * [Cosium/maven-git-code-format](https://github.com/Cosium/maven-git-code-format): - A maven plugin that automatically deploys google-java-format as a - pre-commit git hook. -* SBT plugins - * [sbt/sbt-java-formatter](https://github.com/sbt/sbt-java-formatter) -* [Github Actions](https://github.com/features/actions) - * [googlejavaformat-action](https://github.com/axel-op/googlejavaformat-action): - Automatically format your Java files when you push on github - -### as a library - -The formatter can be used in software which generates java to output more -legible java code. Just include the library in your maven/gradle/etc. -configuration. - -`google-java-format` uses internal javac APIs for parsing Java source. The -following JVM flags are required when running on JDK 16 and newer, due to -[JEP 396: Strongly Encapsulate JDK Internals by Default](https://openjdk.java.net/jeps/396): - -``` ---add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED ---add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED -``` - -#### Maven - -```xml - - com.google.googlejavaformat - google-java-format - ${google-java-format.version} - -``` - -#### Gradle - -```groovy -dependencies { - implementation 'com.google.googlejavaformat:google-java-format:$googleJavaFormatVersion' -} -``` - -You can then use the formatter through the `formatSource` methods. E.g. - -```java -String formattedSource = new Formatter().formatSource(sourceString); -``` - -or - -```java -CharSource source = ... -CharSink output = ... -new Formatter().formatSource(source, output); -``` - -Your starting point should be the instance methods of -`com.google.googlejavaformat.java.Formatter`. - -## Building from source - -``` -mvn install -``` - -## Contributing - -Please see [the contributors guide](CONTRIBUTING.md) for details. - -## License - -```text -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. -``` diff --git a/core/pom.xml b/core/pom.xml index 0dd1fa3b3..cf83dc740 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent - 2025.21.1 + 2025.21.2 configurable-google-java-format diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java index 4d4970d17..cc6ccb97e 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java @@ -28,6 +28,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Map; /** A parser for {@link CommandLineOptions}. */ final class CommandLineOptionsParser { @@ -42,6 +43,7 @@ static CommandLineOptions parse(final Iterable options) { final CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder(); final List expandedOptions = new ArrayList<>(); expandParamsFiles(options, expandedOptions); + expandEnvironmentParams(System.getenv(), expandedOptions); final Iterator it = expandedOptions.iterator(); while (it.hasNext()) { final String option = it.next(); @@ -137,7 +139,7 @@ static CommandLineOptions parse(final Iterable options) { return optionsBuilder.build(); } - private static Integer parseInteger(final Iterator it, final String flag, final String value) { + private static Integer parseInteger(Iterator it, String flag, String value) { try { return Integer.valueOf(getValue(flag, it, value)); } catch (final NumberFormatException e) { @@ -211,4 +213,21 @@ private static void expandParamsFiles(final Iterable args, final List environment, List expandedOptions) { + String prefix = "JAVA_FORMAT_"; + environment.forEach( + (key, value) -> { + if (key.startsWith(prefix)) { + if (!"FALSE".equalsIgnoreCase(value)) { + expandedOptions.add( + "-" + key.substring(prefix.length()).toLowerCase().replace('_', '-')); + if (!"TRUE".equalsIgnoreCase(value)) { + expandedOptions.add(value); + } + } + } + }); + } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java index 93dfb79c2..27f6e8efb 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java @@ -22,7 +22,9 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -81,6 +83,23 @@ public void help() { assertThat(CommandLineOptionsParser.parse(Arrays.asList("-help")).help()).isTrue(); } + @Test + public void help_fromEnvironment() { + Map environement = + Map.of( + "JAVA_FORMAT_HELP", + "TRUE", + "JAVA_FORMAT_V", + "FALSE", + "OTHER_SETTING", + "TRUE", + "JAVA_FORMAT_WIDTH", + "100"); + ArrayList expandedOptions = new ArrayList<>(); + CommandLineOptionsParser.expandEnvironmentParams(environement, expandedOptions); + assertThat(expandedOptions).containsExactly("-help", "-width", "100"); + } + @Test public void lengths() { assertThat( diff --git a/pom.xml b/pom.xml index 99edd6ca7..e31782214 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent pom - 2025.21.1 + 2025.21.2 core From 42e344a6e7798c0a4e436fa8ea98d24e1e0d9189 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:01:28 +0000 Subject: [PATCH 026/107] Update softprops/action-gh-release action to v0.1.15 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d2ce2beae..02fc0fbd5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,7 +70,7 @@ jobs: git push origin "v${{ github.event.inputs.version }}" - name: Add Artifacts to Release Entry - uses: softprops/action-gh-release@v0.1.14 + uses: softprops/action-gh-release@v0.1.15 with: draft: true name: ${{ github.event.input.version }} From b03d308845005009c9ae2f0accba9f1adcf98366 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:01:31 +0000 Subject: [PATCH 027/107] Update truth.version to v1.4.4 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5720abd4a..7ee62bb70 100644 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ UTF-8 1.8 32.1.3-jre - 1.4.0 + 1.4.4 1.0.0 2.36.0 1.9 From 95813e683c20c125dfc64caf419728a543918cac Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:04:53 +0000 Subject: [PATCH 028/107] Update auto-service.version to v1.1.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..46047c63b 100644 --- a/pom.xml +++ b/pom.xml @@ -79,7 +79,7 @@ 1.0.0 2.36.0 1.9 - 1.0.1 + 1.1.1 3.6.3 3.2.1 From aeb265decd5c2e7b249c88fc8dcab3bb05504f38 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:00 +0000 Subject: [PATCH 029/107] Update dependency com.google.testing.compile:compile-testing to v0.21.0 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index ee7b1388e..1cb82334b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -83,7 +83,7 @@ com.google.testing.compile compile-testing - 0.19 + 0.21.0 test From f1369677cdc2acb9b6ff6b68d04f2510f6e6a96f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:04 +0000 Subject: [PATCH 030/107] Update dependency org.apache.maven.plugins:maven-compiler-plugin to v3.13.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..0dabb67b1 100644 --- a/pom.xml +++ b/pom.xml @@ -148,7 +148,7 @@ maven-compiler-plugin - 3.9.0 + 3.13.0 maven-jar-plugin From 94d227a469a0faba89ed323acc9565674c5745a7 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:08 +0000 Subject: [PATCH 031/107] Update dependency org.apache.maven.plugins:maven-gpg-plugin to v3.2.7 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..044b4f73c 100644 --- a/pom.xml +++ b/pom.xml @@ -164,7 +164,7 @@ maven-gpg-plugin - 3.0.1 + 3.2.7 org.apache.felix @@ -320,7 +320,7 @@ org.apache.maven.plugins maven-gpg-plugin - 3.0.1 + 3.2.7 sign-artifacts From d5c28b96c7f5ef6fe040d8aaefa59d2e256c6e26 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:11 +0000 Subject: [PATCH 032/107] Update dependency org.apache.maven.plugins:maven-jar-plugin to v3.4.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..8c970fdd7 100644 --- a/pom.xml +++ b/pom.xml @@ -152,7 +152,7 @@ maven-jar-plugin - 3.2.2 + 3.4.2 maven-source-plugin From 1da99f9d3243e657bf9407c78253086e4fad496a Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:17 +0000 Subject: [PATCH 033/107] Update dependency org.apache.maven.plugins:maven-shade-plugin to v3.6.0 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index ee7b1388e..c0b09709c 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -123,7 +123,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.2.4 + 3.6.0 shade-all-deps From 0a591cf7f3aa4000735414d6ef59944902ce3459 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:20 +0000 Subject: [PATCH 034/107] Update dependency org.apache.maven.plugins:maven-source-plugin to v3.3.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..2497eec74 100644 --- a/pom.xml +++ b/pom.xml @@ -156,7 +156,7 @@ maven-source-plugin - 3.2.1 + 3.3.1 maven-javadoc-plugin From 29387ef996c19d8cc1cbb629edbce9e2855b7481 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:23 +0000 Subject: [PATCH 035/107] Update dependency org.apache.maven.plugins:maven-source-plugin to v3.3.1 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..79ad94087 100644 --- a/pom.xml +++ b/pom.xml @@ -81,7 +81,7 @@ 1.9 1.0.1 3.6.3 - 3.2.1 + 3.3.1 From 69a6d87a5f83b913febcec920546f95192525168 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:26 +0000 Subject: [PATCH 036/107] Update dependency org.codehaus.mojo:build-helper-maven-plugin to v3.6.0 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index ee7b1388e..c6954299b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -195,7 +195,7 @@ org.codehaus.mojo build-helper-maven-plugin - 3.3.0 + 3.6.0 add-source From 9c132d3b670ffbb99cab2d2ce55d3836dabdd75d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:29 +0000 Subject: [PATCH 037/107] Update styfle/cancel-workflow-action action to v0.12.1 --- .github/workflows/cgjf-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cgjf-ci.yml b/.github/workflows/cgjf-ci.yml index 42b6743df..dd92c3280 100644 --- a/.github/workflows/cgjf-ci.yml +++ b/.github/workflows/cgjf-ci.yml @@ -47,7 +47,7 @@ jobs: continue-on-error: ${{ matrix.experimental }} steps: - name: Cancel previous - uses: styfle/cancel-workflow-action@0.9.1 + uses: styfle/cancel-workflow-action@0.12.1 with: access_token: ${{ github.token }} - name: "Check out repository" From 36eeba1406ae658944b1033b3a16387d0492f809 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:32 +0000 Subject: [PATCH 038/107] Update actions/checkout action to v4 --- .github/workflows/cgjf-release.yml | 2 +- .github/workflows/maven-publish.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index 9e2410b9b..a9a6f03f8 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -12,7 +12,7 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: "Set up JDK 21 from Zulu" uses: actions/setup-java@v4 with: diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index d91a9b134..5386bfdbe 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -16,7 +16,7 @@ jobs: packages: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up JDK 17 uses: actions/setup-java@v3 with: From d73b133ab3a40e9214986100037caecabad186a0 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:35 +0000 Subject: [PATCH 039/107] Update actions/setup-java action to v4 --- .github/workflows/maven-publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index d91a9b134..a964ab9ed 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -18,7 +18,7 @@ jobs: steps: - uses: actions/checkout@v3 - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' From bbdf000d99f67e2226a93419865adcca84684fd6 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:38 +0000 Subject: [PATCH 040/107] Update dependency org.apache.felix:maven-bundle-plugin to v6 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..2891a6899 100644 --- a/pom.xml +++ b/pom.xml @@ -169,7 +169,7 @@ org.apache.felix maven-bundle-plugin - 5.1.9 + 6.0.0 From 957755eaf288c12fd3382c1bfe30b2e93c86f05d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:41 +0000 Subject: [PATCH 041/107] Update dependency org.apache.maven.plugins:maven-surefire-plugin to v3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..5c647220c 100644 --- a/pom.xml +++ b/pom.xml @@ -265,7 +265,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.2 + 3.5.2 From 61bccdf9f7dd36b9ef4fb5ba4893ff505c6ad726 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:43 +0000 Subject: [PATCH 042/107] Update guava monorepo to v33 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 7ee62bb70..74ef8c7f8 100644 --- a/pom.xml +++ b/pom.xml @@ -74,7 +74,7 @@ UTF-8 1.8 - 32.1.3-jre + 33.4.0-jre 1.4.4 1.0.0 2.36.0 From 91a3f015b9096936416a481555ad20d803789ec1 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:05:47 +0000 Subject: [PATCH 043/107] Update softprops/action-gh-release action to v2 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 02fc0fbd5..3a2541d2e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,7 +70,7 @@ jobs: git push origin "v${{ github.event.inputs.version }}" - name: Add Artifacts to Release Entry - uses: softprops/action-gh-release@v0.1.15 + uses: softprops/action-gh-release@v2.2.1 with: draft: true name: ${{ github.event.input.version }} From 69804de92f7deef7e5a208721abc61be75924336 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:07:42 +0000 Subject: [PATCH 044/107] Update auto-value.version to v1.11.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 46047c63b..e8daa9446 100644 --- a/pom.xml +++ b/pom.xml @@ -78,7 +78,7 @@ 1.4.4 1.0.0 2.36.0 - 1.9 + 1.11.0 1.1.1 3.6.3 3.2.1 From 91be013d6eb658254165266ad573737eec0a3f55 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 21:09:57 +0000 Subject: [PATCH 045/107] Update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.11.2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3eae67c84..379689b40 100644 --- a/pom.xml +++ b/pom.xml @@ -80,7 +80,7 @@ 2.36.0 1.11.0 1.1.1 - 3.6.3 + 3.11.2 3.3.1 From 43a98f3e3ee8631ceb0b6d29a8a9c4ee8a420bd6 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Mon, 3 Feb 2025 07:25:16 +0000 Subject: [PATCH 046/107] Add Coverity Scan --- README.adoc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.adoc b/README.adoc index 2cfea15c3..10b134737 100644 --- a/README.adoc +++ b/README.adoc @@ -1,5 +1,8 @@ = Configurable Google Java Format +link:https://scan.coverity.com/projects/mrdolch-configurable-google-java-format[image:https://scan.coverity.com/projects/31341/badge.svg[Coverity Scan Build Status]] + + This project is a fork of `google-java-format`, an automatic code formatter for Java. == Changes from the Original From 92b43b62b4fa726565d892a024e576b9f4d5d2fb Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 5 Feb 2025 05:47:34 +0000 Subject: [PATCH 047/107] Update dependency org.graalvm.buildtools:native-maven-plugin to v0.10.5 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index 9cc375c9a..690112c81 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -255,7 +255,7 @@ org.graalvm.buildtools native-maven-plugin - 0.10.4 + 0.10.5 true From 01c12973f7b99c5484339734caee53d9d2c58561 Mon Sep 17 00:00:00 2001 From: chris Date: Thu, 13 Feb 2025 15:48:24 +0000 Subject: [PATCH 048/107] Configure Coverity-Workflow --- .github/workflows/coverity-scan.yml | 43 +++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/workflows/coverity-scan.yml diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml new file mode 100644 index 000000000..2ec16a08e --- /dev/null +++ b/.github/workflows/coverity-scan.yml @@ -0,0 +1,43 @@ +name: Coverity Scan + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + coverity_scan: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Install dependencies + run: sudo apt-get install build-essential cmake -y + + - name: Download Coverity Build Tool + run: | + wget -q https://scan.coverity.com/download/linux64 \ + --post-data "token=${{ secrets.COVERITY_SCAN_TOKEN }}&project=MrDolch/configurable-google-java-format" \ + -O coverity_tool.tgz + tar xzf coverity_tool.tgz + mv cov-analysis* coverity + + - name: Run Coverity Analysis + run: | + export PATH="$(pwd)/coverity/bin:$PATH" + cov-build --dir cov-int mvn clean install + + - name: Upload results to Coverity + run: | + tar czf cov-int.tgz cov-int + curl --form token=${{ secrets.COVERITY_SCAN_TOKEN }} \ + --form email=${{ secrets.COVERITY_SCAN_EMAIL }} \ + --form file=@cov-int.tgz \ + --form version="$(git rev-parse --short HEAD)" \ + --form description="Coverity Scan for latest commit" \ + https://scan.coverity.com/builds From 58ef9d949063275c7db378743913e918e09fb8a5 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 13 Feb 2025 15:49:42 +0000 Subject: [PATCH 049/107] Update actions/checkout action to v4 --- .github/workflows/coverity-scan.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml index 2ec16a08e..1dd2411c6 100644 --- a/.github/workflows/coverity-scan.yml +++ b/.github/workflows/coverity-scan.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install dependencies run: sudo apt-get install build-essential cmake -y From d56d61892f8762a5c10dca4696076bfa354a86a5 Mon Sep 17 00:00:00 2001 From: chris Date: Thu, 13 Feb 2025 15:50:48 +0000 Subject: [PATCH 050/107] Configure Coverity-Workflow --- .github/workflows/coverity-scan.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml index 2ec16a08e..4f23ecd9c 100644 --- a/.github/workflows/coverity-scan.yml +++ b/.github/workflows/coverity-scan.yml @@ -3,10 +3,10 @@ name: Coverity Scan on: push: branches: - - main + - master pull_request: branches: - - main + - master jobs: coverity_scan: From 00f15d3487892778c25ba1ded11fa6a9a3fb4bac Mon Sep 17 00:00:00 2001 From: chris Date: Fri, 14 Feb 2025 16:48:15 +0000 Subject: [PATCH 051/107] Update Documentation --- README.adoc | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.adoc b/README.adoc index 10b134737..7b0fcd370 100644 --- a/README.adoc +++ b/README.adoc @@ -24,6 +24,17 @@ export JAVA_FORMAT_WIDTH=120 java -jar configurable-google-java-format.jar File.java ``` +== IntelliJ Plugin + +link:https://plugins.jetbrains.com/plugin/23827[image:https://img.shields.io/jetbrains/plugin/v/23827.svg[Version]] +link:https://plugins.jetbrains.com/plugin/23827[image:https://img.shields.io/jetbrains/plugin/d/23827.svg[Downloads]] + +The IntelliJ plugin is separate from the formatter and can be found here: + +Plugin page: https://plugins.jetbrains.com/plugin/23827-external-java-formatter + +Source code: https://github.com/MrDolch/external-java-formatter-intellij-plugin + == License This project is based on `google-java-format` and follows the same licensing terms. From 68b3d86d10a11d5cd6abcaf78776a120563ea2f5 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 12:24:18 +0000 Subject: [PATCH 052/107] Remove unused Code --- .../googlejavaformat/java/Formatter.java | 2 - .../java/GoogleJavaFormatTool.java | 53 ----- .../java/GoogleJavaFormatToolProvider.java | 39 ---- .../GoogleJavaFormatVersion.java.template | 4 + .../googlejavaformat/java/JavaOutput.java | 4 +- .../google/googlejavaformat/java/Main.java | 5 +- .../java/SnippetFormatter.java | 215 ------------------ .../googlejavaformat/java/UsageException.java | 2 +- .../java/filer/FormattingFiler.java | 88 ------- .../java/SnippetFormatterTest.java | 102 --------- .../java/filer/FormattingFilerTest.java | 150 ------------ 11 files changed, 8 insertions(+), 656 deletions(-) delete mode 100644 core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java delete mode 100644 core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java delete mode 100644 core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java delete mode 100644 core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java delete mode 100644 core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java delete mode 100644 core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index 4d621726a..b8e5308cc 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -72,8 +72,6 @@ @Immutable public final class Formatter { - static final Range EMPTY_RANGE = Range.closedOpen(-1, -1); - private final JavaFormatterOptions options; /** A new Formatter instance with default options. */ diff --git a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java deleted file mode 100644 index 3c315aaf1..000000000 --- a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatTool.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2021 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 com.google.common.collect.Sets.toImmutableEnumSet; - -import com.google.auto.service.AutoService; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.Arrays; -import java.util.Set; -import javax.lang.model.SourceVersion; -import javax.tools.Tool; - -/** Provide a way to be invoked without necessarily starting a new VM. */ -@AutoService(Tool.class) -public class GoogleJavaFormatTool implements Tool { - @Override - public String name() { - return "google-java-format"; - } - - @Override - public Set getSourceVersions() { - return Arrays.stream(SourceVersion.values()).collect(toImmutableEnumSet()); - } - - @Override - public int run(InputStream in, OutputStream out, OutputStream err, String... args) { - PrintStream outStream = new PrintStream(out); - PrintStream errStream = new PrintStream(err); - try { - return Main.main(in, outStream, errStream, args); - } catch (RuntimeException e) { - errStream.print(e.getMessage()); - errStream.flush(); - return 1; // pass non-zero value back indicating an error has happened - } - } -} diff --git a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java deleted file mode 100644 index 438eac596..000000000 --- a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProvider.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2021 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 com.google.auto.service.AutoService; -import java.io.PrintWriter; -import java.util.spi.ToolProvider; - -/** Provide a way to be invoked without necessarily starting a new VM. */ -@AutoService(ToolProvider.class) -public class GoogleJavaFormatToolProvider implements ToolProvider { - @Override - public String name() { - return "google-java-format"; - } - - @Override - public int run(PrintWriter out, PrintWriter err, String... args) { - try { - return Main.main(System.in, out, err, args); - } catch (RuntimeException e) { - err.print(e.getMessage()); - err.flush(); - return 1; // pass non-zero value back indicating an error has happened - } - } -} diff --git a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java.template b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java.template index 88706fbf1..7e1b1dbcf 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java.template +++ b/core/src/main/java/com/google/googlejavaformat/java/GoogleJavaFormatVersion.java.template @@ -19,4 +19,8 @@ class GoogleJavaFormatVersion { static String version() { return "%VERSION%"; } + + static String versionString() { + return "google-java-format: Version " + version(); + } } diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java index ea3731131..4e92b17ea 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java @@ -163,7 +163,7 @@ public void append(String text, Range range) { if (!range.isEmpty()) { if (!rangesSet) { while (ranges.size() <= mutableLines.size()) { - ranges.add(Formatter.EMPTY_RANGE); + ranges.add(EMPTY_RANGE); } ranges.set(mutableLines.size(), union(ranges.get(mutableLines.size()), range)); rangesSet = true; @@ -191,7 +191,7 @@ public void flush() { int jN = mutableLines.size(); Range eofRange = Range.closedOpen(kN, kN + 1); while (ranges.size() < jN) { - ranges.add(Formatter.EMPTY_RANGE); + ranges.add(EMPTY_RANGE); } ranges.add(eofRange); setLines(ImmutableList.copyOf(mutableLines)); diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index de477420a..55f865ce8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -46,9 +46,6 @@ public final class Main { private static final int MAX_THREADS = 20; private static final String STDIN_FILENAME = ""; - static String versionString() { - return "google-java-format: Version " + GoogleJavaFormatVersion.version(); - } private final PrintWriter outWriter; private final PrintWriter errWriter; @@ -110,7 +107,7 @@ static int main(InputStream in, PrintWriter out, PrintWriter err, String... args public int format(String... args) throws UsageException { CommandLineOptions parameters = processArgs(args); if (parameters.version()) { - errWriter.println(versionString()); + errWriter.println(GoogleJavaFormatVersion.versionString()); return 0; } if (parameters.help()) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java b/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java deleted file mode 100644 index 8d426b65d..000000000 --- a/core/src/main/java/com/google/googlejavaformat/java/SnippetFormatter.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright 2017 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 com.google.common.collect.ImmutableList.toImmutableList; - -import com.google.common.base.CharMatcher; -import com.google.common.base.Preconditions; -import com.google.common.collect.DiscreteDomain; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Range; -import com.google.common.collect.RangeSet; -import com.google.common.collect.TreeRangeSet; -import java.util.ArrayList; -import java.util.List; - -/** Formats a subset of a compilation unit. */ -public class SnippetFormatter { - - /** The kind of snippet to format. */ - public enum SnippetKind { - COMPILATION_UNIT, - CLASS_BODY_DECLARATIONS, - STATEMENTS, - EXPRESSION - } - - private class SnippetWrapper { - int offset; - final StringBuilder contents = new StringBuilder(); - - public SnippetWrapper append(String str) { - contents.append(str); - return this; - } - - public SnippetWrapper appendSource(String source) { - this.offset = contents.length(); - contents.append(source); - return this; - } - - public void closeBraces(int initialIndent) { - for (int i = initialIndent; --i >= 0; ) { - contents.append("\n").append(createIndentationString(i)).append("}"); - } - } - } - - private static final int INDENTATION_SIZE = 2; - private final Formatter formatter = new Formatter(); - private static final CharMatcher NOT_WHITESPACE = CharMatcher.whitespace().negate(); - - public String createIndentationString(int indentationLevel) { - Preconditions.checkArgument( - indentationLevel >= 0, - "Indentation level cannot be less than zero. Given: %s", - indentationLevel); - int spaces = indentationLevel * INDENTATION_SIZE; - StringBuilder buf = new StringBuilder(spaces); - for (int i = 0; i < spaces; i++) { - buf.append(' '); - } - return buf.toString(); - } - - private static Range offsetRange(Range range, int offset) { - range = range.canonical(DiscreteDomain.integers()); - return Range.closedOpen(range.lowerEndpoint() + offset, range.upperEndpoint() + offset); - } - - private static List> offsetRanges(List> ranges, int offset) { - List> result = new ArrayList<>(); - for (Range range : ranges) { - result.add(offsetRange(range, offset)); - } - return result; - } - - /** Runs the Google Java formatter on the given source, with only the given ranges specified. */ - public ImmutableList format( - SnippetKind kind, - String source, - List> ranges, - int initialIndent, - boolean includeComments) - throws FormatterException { - RangeSet rangeSet = TreeRangeSet.create(); - for (Range range : ranges) { - rangeSet.add(range); - } - if (includeComments) { - if (kind != SnippetKind.COMPILATION_UNIT) { - throw new IllegalArgumentException( - "comment formatting is only supported for compilation units"); - } - return formatter.getFormatReplacements(source, ranges); - } - SnippetWrapper wrapper = snippetWrapper(kind, source, initialIndent); - ranges = offsetRanges(ranges, wrapper.offset); - - String replacement = formatter.formatSource(wrapper.contents.toString(), ranges); - replacement = - replacement.substring( - wrapper.offset, - replacement.length() - (wrapper.contents.length() - wrapper.offset - source.length())); - - return toReplacements(source, replacement).stream() - .filter(r -> rangeSet.encloses(r.getReplaceRange())) - .collect(toImmutableList()); - } - - /** - * Generates {@code Replacement}s rewriting {@code source} to {@code replacement}, under the - * assumption that they differ in whitespace alone. - */ - private static List toReplacements(String source, String replacement) { - if (!NOT_WHITESPACE.retainFrom(source).equals(NOT_WHITESPACE.retainFrom(replacement))) { - throw new IllegalArgumentException( - "source = \"" + source + "\", replacement = \"" + replacement + "\""); - } - /* - * In the past we seemed to have problems touching non-whitespace text in the formatter, even - * just replacing some code with itself. Retrospective attempts to reproduce this have failed, - * but this may be an issue for future changes. - */ - List replacements = new ArrayList<>(); - int i = NOT_WHITESPACE.indexIn(source); - int j = NOT_WHITESPACE.indexIn(replacement); - if (i != 0 || j != 0) { - replacements.add(Replacement.create(0, i, replacement.substring(0, j))); - } - while (i != -1 && j != -1) { - int i2 = NOT_WHITESPACE.indexIn(source, i + 1); - int j2 = NOT_WHITESPACE.indexIn(replacement, j + 1); - if (i2 == -1 || j2 == -1) { - break; - } - if ((i2 - i) != (j2 - j) - || !source.substring(i + 1, i2).equals(replacement.substring(j + 1, j2))) { - replacements.add(Replacement.create(i + 1, i2, replacement.substring(j + 1, j2))); - } - i = i2; - j = j2; - } - return replacements; - } - - private SnippetWrapper snippetWrapper(SnippetKind kind, String source, int initialIndent) { - /* - * Synthesize a dummy class around the code snippet provided by Eclipse. The dummy class is - * correctly formatted -- the blocks use correct indentation, etc. - */ - switch (kind) { - case COMPILATION_UNIT: - { - SnippetWrapper wrapper = new SnippetWrapper(); - for (int i = 1; i <= initialIndent; i++) { - wrapper.append("class Dummy {\n").append(createIndentationString(i)); - } - wrapper.appendSource(source); - wrapper.closeBraces(initialIndent); - return wrapper; - } - case CLASS_BODY_DECLARATIONS: - { - SnippetWrapper wrapper = new SnippetWrapper(); - for (int i = 1; i <= initialIndent; i++) { - wrapper.append("class Dummy {\n").append(createIndentationString(i)); - } - wrapper.appendSource(source); - wrapper.closeBraces(initialIndent); - return wrapper; - } - case STATEMENTS: - { - SnippetWrapper wrapper = new SnippetWrapper(); - wrapper.append("class Dummy {\n").append(createIndentationString(1)); - for (int i = 2; i <= initialIndent; i++) { - wrapper.append("{\n").append(createIndentationString(i)); - } - wrapper.appendSource(source); - wrapper.closeBraces(initialIndent); - return wrapper; - } - case EXPRESSION: - { - SnippetWrapper wrapper = new SnippetWrapper(); - wrapper.append("class Dummy {\n").append(createIndentationString(1)); - for (int i = 2; i <= initialIndent; i++) { - wrapper.append("{\n").append(createIndentationString(i)); - } - wrapper.append("Object o = "); - wrapper.appendSource(source); - wrapper.append(";"); - wrapper.closeBraces(initialIndent); - return wrapper; - } - default: - throw new IllegalArgumentException("Unknown snippet kind: " + kind); - } - } -} diff --git a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java index 50d55d4d4..1897d8167 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java @@ -93,7 +93,7 @@ private static String buildMessage(String message) { appendLines(builder, USAGE); appendLines(builder, ADDITIONAL_USAGE); appendLines(builder, new String[] {""}); - appendLine(builder, Main.versionString()); + appendLine(builder, GoogleJavaFormatVersion.versionString()); appendLines(builder, DOCS_LINK); return builder.toString(); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java deleted file mode 100644 index 2f2e33cbe..000000000 --- a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2016 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.filer; - -import static com.google.common.base.Preconditions.checkNotNull; - -import com.google.googlejavaformat.java.Formatter; -import java.io.IOException; -import javax.annotation.processing.Filer; -import javax.annotation.processing.Messager; -import javax.lang.model.element.Element; -import javax.tools.FileObject; -import javax.tools.JavaFileManager; -import javax.tools.JavaFileObject; -import org.jspecify.annotations.Nullable; - -/** - * A decorating {@link Filer} implementation which formats Java source files with a {@link - * Formatter}. - */ -public final class FormattingFiler implements Filer { - - private final Filer delegate; - // TODO(ronshapiro): consider allowing users to create their own Formatter instance - private final Formatter formatter = new Formatter(); - private final Messager messager; - - /** - * @param delegate filer to decorate - */ - public FormattingFiler(Filer delegate) { - this(delegate, null); - } - - /** - * Create a new {@link FormattingFiler}. An optional {@link Messager} may be specified to make - * logs more visible. - * - * @param delegate filer to decorate - * @param messager to log warnings to - */ - public FormattingFiler(Filer delegate, @Nullable Messager messager) { - this.delegate = checkNotNull(delegate); - this.messager = messager; - } - - @Override - public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) - throws IOException { - return new FormattingJavaFileObject( - delegate.createSourceFile(name, originatingElements), formatter, messager); - } - - @Override - public JavaFileObject createClassFile(CharSequence name, Element... originatingElements) - throws IOException { - return delegate.createClassFile(name, originatingElements); - } - - @Override - public FileObject createResource( - JavaFileManager.Location location, - CharSequence pkg, - CharSequence relativeName, - Element... originatingElements) - throws IOException { - return delegate.createResource(location, pkg, relativeName, originatingElements); - } - - @Override - public FileObject getResource( - JavaFileManager.Location location, CharSequence pkg, CharSequence relativeName) - throws IOException { - return delegate.getResource(location, pkg, relativeName); - } -} diff --git a/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java deleted file mode 100644 index f763dd524..000000000 --- a/core/src/test/java/com/google/googlejavaformat/java/SnippetFormatterTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2017 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 com.google.common.truth.Truth.assertThat; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Range; -import com.google.googlejavaformat.java.SnippetFormatter.SnippetKind; -import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** {@link SnippetFormatter}Test */ -@RunWith(JUnit4.class) -public class SnippetFormatterTest { - @Test - public void expression() throws FormatterException { - String input = "x\n=42"; - List replacements = - new SnippetFormatter() - .format( - SnippetKind.EXPRESSION, - input, - ImmutableList.of(Range.closedOpen(0, input.length())), - 4, - false); - assertThat(replacements) - .containsExactly(Replacement.create(1, 2, " "), Replacement.create(3, 3, " ")); - } - - @Test - public void statement() throws FormatterException { - String input = "int x\n=42;"; - List replacements = - new SnippetFormatter() - .format( - SnippetKind.STATEMENTS, - input, - ImmutableList.of(Range.closedOpen(0, input.length())), - 4, - false); - assertThat(replacements) - .containsExactly(Replacement.create(5, 6, " "), Replacement.create(7, 7, " ")); - } - - @Test - public void classMember() throws FormatterException { - String input = "void f() {\n}"; - List replacements = - new SnippetFormatter() - .format( - SnippetKind.CLASS_BODY_DECLARATIONS, - input, - ImmutableList.of(Range.closedOpen(0, input.length())), - 4, - false); - assertThat(replacements).containsExactly(Replacement.create(10, 11, "")); - } - - @Test - public void compilation() throws FormatterException { - String input = "/** a\nb*/\nclass Test {\n}"; - List replacements = - new SnippetFormatter() - .format( - SnippetKind.COMPILATION_UNIT, - input, - ImmutableList.of(Range.closedOpen(input.indexOf("class"), input.length())), - 4, - false); - assertThat(replacements).containsExactly(Replacement.create(22, 23, "")); - } - - @Test - public void compilationWithComments() throws FormatterException { - String input = "/** a\nb*/\nclass Test {\n}"; - List replacements = - new SnippetFormatter() - .format( - SnippetKind.COMPILATION_UNIT, - input, - ImmutableList.of(Range.closedOpen(0, input.length())), - 4, - true); - assertThat(replacements) - .containsExactly(Replacement.create(0, 24, "/** a b */\nclass Test {}\n")); - } -} diff --git a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java deleted file mode 100644 index 38cac3550..000000000 --- a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2016 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.filer; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.common.base.Joiner; -import com.google.testing.compile.CompilationRule; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.processing.Filer; -import javax.annotation.processing.Messager; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.AnnotationValue; -import javax.lang.model.element.Element; -import javax.tools.FileObject; -import javax.tools.JavaFileManager.Location; -import javax.tools.JavaFileObject; -import javax.tools.JavaFileObject.Kind; -import javax.tools.SimpleJavaFileObject; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link com.google.googlejavaformat.java.filer.FormattingFiler}. */ -@RunWith(JUnit4.class) -public class FormattingFilerTest { - - @Rule public CompilationRule compilationRule = new CompilationRule(); - - @Test - public void invalidSyntaxDoesNotThrowError() throws IOException { - List logMessages = new ArrayList<>(); - Messager messager = - new Messager() { - @Override - public void printMessage(javax.tools.Diagnostic.Kind kind, CharSequence msg) { - logMessages.add(kind + ";" + msg); - } - - @Override - public void printMessage(javax.tools.Diagnostic.Kind kind, CharSequence msg, Element e) {} - - @Override - public void printMessage( - javax.tools.Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a) {} - - @Override - public void printMessage( - javax.tools.Diagnostic.Kind kind, - CharSequence msg, - Element e, - AnnotationMirror a, - AnnotationValue v) {} - }; - - String file = Joiner.on('\n').join("package foo;", "public class Bar {"); - FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler(), messager); - try (Writer writer = formattingFiler.createSourceFile("foo.Bar").openWriter()) { - writer.write(file); - } - - assertThat(logMessages).containsExactly("NOTE;Error formatting foo.Bar"); - } - - @Test - public void formatsFile() throws IOException { - FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler()); - JavaFileObject sourceFile = formattingFiler.createSourceFile("foo.Bar"); - try (Writer writer = sourceFile.openWriter()) { - writer.write("package foo;class Bar{private String baz;\n\n\n\n}"); - } - - assertThat(sourceFile.getCharContent(false).toString()) - .isEqualTo( - Joiner.on('\n') - .join( - "package foo;", - "", - "class Bar {", - " private String baz;", - "}", - "")); // trailing newline - } - - private static class FakeFiler implements Filer { - @Override - public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) - throws IOException { - return new ObservingJavaFileObject(name.toString(), Kind.SOURCE); - } - - @Override - public JavaFileObject createClassFile(CharSequence name, Element... originatingElements) - throws IOException { - return new ObservingJavaFileObject(name.toString(), Kind.CLASS); - } - - @Override - public FileObject createResource( - Location location, - CharSequence pkg, - CharSequence relativeName, - Element... originatingElements) - throws IOException { - return new ObservingJavaFileObject(pkg.toString() + relativeName, Kind.OTHER); - } - - @Override - public FileObject getResource(Location location, CharSequence pkg, CharSequence relativeName) - throws IOException { - return new ObservingJavaFileObject(pkg.toString() + relativeName, Kind.OTHER); - } - } - - private static class ObservingJavaFileObject extends SimpleJavaFileObject { - private final StringWriter output = new StringWriter(); - - ObservingJavaFileObject(String name, Kind kind) { - super(URI.create(name), kind); - } - - @Override - public Writer openWriter() throws IOException { - return output; - } - - @Override - public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { - return output.toString(); - } - } -} From 8d6613e3d0f5387da798c34b6505a88b71754a15 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 12:27:52 +0000 Subject: [PATCH 053/107] Remove unused Code --- .../GoogleJavaFormatToolProviderTest.java | 56 ---------------- .../java/GoogleJavaFormatToolTest.java | 64 ------------------- 2 files changed, 120 deletions(-) delete mode 100644 core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java delete mode 100644 core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java diff --git a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java deleted file mode 100644 index 461bd6793..000000000 --- a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolProviderTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2021 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 com.google.common.truth.Truth.assertThat; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.ServiceLoader; -import java.util.spi.ToolProvider; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link GoogleJavaFormatToolProvider}. */ -@RunWith(JUnit4.class) -public class GoogleJavaFormatToolProviderTest { - - @Test - public void testUsageOutputAfterLoadingViaToolName() { - String name = "google-java-format"; - - assertThat( - ServiceLoader.load(ToolProvider.class).stream() - .map(ServiceLoader.Provider::get) - .map(ToolProvider::name)) - .contains(name); - - ToolProvider format = ToolProvider.findFirst(name).get(); - - StringWriter out = new StringWriter(); - StringWriter err = new StringWriter(); - - int result = format.run(new PrintWriter(out, true), new PrintWriter(err, true), "--help"); - - assertThat(result).isNotEqualTo(0); - - String usage = err.toString(); - - // Check that doc links are included. - assertThat(usage).containsMatch("http.*/google-java-format"); - assertThat(usage).contains("Usage: google-java-format"); - } -} diff --git a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java b/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java deleted file mode 100644 index e3a7573a7..000000000 --- a/core/src/test/java/com/google/googlejavaformat/java/GoogleJavaFormatToolTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2021 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 com.google.common.truth.Truth.assertThat; -import static java.nio.charset.StandardCharsets.UTF_8; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.util.ServiceLoader; -import javax.tools.Tool; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for {@link GoogleJavaFormatToolProvider}. */ -@RunWith(JUnit4.class) -public class GoogleJavaFormatToolTest { - - @Test - public void testUsageOutputAfterLoadingViaToolName() { - String name = "google-java-format"; - - assertThat( - ServiceLoader.load(Tool.class).stream() - .map(ServiceLoader.Provider::get) - .map(Tool::name)) - .contains(name); - - Tool format = - ServiceLoader.load(Tool.class).stream() - .filter(provider -> name.equals(provider.get().name())) - .findFirst() - .get() - .get(); - - InputStream in = new ByteArrayInputStream(new byte[0]); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - - int result = format.run(in, out, err, "--help"); - - assertThat(result).isNotEqualTo(0); - - String usage = new String(err.toByteArray(), UTF_8); - - // Check that doc links are included. - assertThat(usage).containsMatch("http.*/google-java-format"); - assertThat(usage).contains("Usage: google-java-format"); - } -} From d1f59786ecea6d6cbeaebdff367c7f0c2fdfa505 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 17:30:20 +0000 Subject: [PATCH 054/107] try fix release-workflow --- .github/workflows/cgjf-release.yml | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index a9a6f03f8..ce45cacef 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -6,21 +6,31 @@ on: - '*' jobs: - - build: + release: runs-on: ubuntu-latest permissions: contents: write + packages: write + steps: - - uses: actions/checkout@v4 - - name: "Set up JDK 21 from Zulu" + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Set up JDK 21 from Zulu uses: actions/setup-java@v4 with: java-version: 21 distribution: "zulu" + - name: Build with Maven - run: mvn verify -DskipTests=true -Dmaven.javadoc.skip=true -B -V - - uses: ncipollo/release-action@v1 + run: mvn clean package -DskipTests=true -Dmaven.javadoc.skip=true -B -V + + - name: Create Release on GitHub + uses: ncipollo/release-action@v1 with: - artifacts: "core/target/configurable-google-java-format-*.jar" + tag: ${{ github.ref_name }} + artifacts: | + core/target/configurable-google-java-format-maven-plugin-*.jar + core/target/configurable-google-java-format-maven-plugin-*.pom bodyFile: "cgjf-release.md" + token: ${{ secrets.GITHUB_TOKEN }} From d764bc0a19bd0307df6476362316a67db4799850 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 17:31:25 +0000 Subject: [PATCH 055/107] try fix release-workflow --- core/pom.xml | 15 --------------- pom.xml | 2 +- 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 690112c81..1fdf6466d 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -67,25 +67,10 @@ junit junit - - com.google.guava - guava-testlib - com.google.truth truth - - com.google.truth.extensions - truth-java8-extension - test - - - com.google.testing.compile - compile-testing - 0.21.0 - test - diff --git a/pom.xml b/pom.xml index 2e831512a..4bc350b5d 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent pom - 2025.21.2 + 2025.21.3 core From b60b0f8cacb4cb25ef6bd7447c9d708cfd0293e4 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 17:33:33 +0000 Subject: [PATCH 056/107] try fix release-workflow --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index 1fdf6466d..b5645ece5 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.github.mrdolch.googlejavaformat configurable-google-java-format-parent - 2025.21.2 + 2025.21.3 configurable-google-java-format From 7111e4e0fdb3a0b58774ae285e63bd7355ddd03f Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 17:48:18 +0000 Subject: [PATCH 057/107] try fix release-workflow --- .github/workflows/cgjf-release.yml | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index ce45cacef..b6d0250a7 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -6,31 +6,27 @@ on: - '*' jobs: - release: + build: runs-on: ubuntu-latest permissions: contents: write packages: write steps: - - name: Checkout Repository - uses: actions/checkout@v4 + - uses: actions/checkout@v4 - - name: Set up JDK 21 from Zulu + - name: "Set up JDK 21 from Zulu" uses: actions/setup-java@v4 with: java-version: 21 distribution: "zulu" - name: Build with Maven - run: mvn clean package -DskipTests=true -Dmaven.javadoc.skip=true -B -V + run: mvn verify -DskipTests=true -Dmaven.javadoc.skip=true -B -V - - name: Create Release on GitHub - uses: ncipollo/release-action@v1 + - uses: ncipollo/release-action@v1 with: - tag: ${{ github.ref_name }} - artifacts: | - core/target/configurable-google-java-format-maven-plugin-*.jar - core/target/configurable-google-java-format-maven-plugin-*.pom + artifacts: "core/target/configurable-google-java-format-*.jar" bodyFile: "cgjf-release.md" token: ${{ secrets.GITHUB_TOKEN }} + tag: ${{ github.ref_name }} \ No newline at end of file From bb1344b70de2c52a9fd624389f23378c8a4b3e9e Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 18:17:23 +0000 Subject: [PATCH 058/107] try fix release-workflow --- .github/workflows/cgjf-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cgjf-release.yml index b6d0250a7..fadab657c 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cgjf-release.yml @@ -26,7 +26,7 @@ jobs: - uses: ncipollo/release-action@v1 with: - artifacts: "core/target/configurable-google-java-format-*.jar" + artifacts: "core/target/configurable-google-java-format-*.*" bodyFile: "cgjf-release.md" token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ github.ref_name }} \ No newline at end of file From c8df4b8fcd12c10b6e55ae989b9232892f2e5e34 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 18:58:46 +0000 Subject: [PATCH 059/107] try to publish on jitpack --- jitpack.yml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 jitpack.yml diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 000000000..759876852 --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,3 @@ +before_install: + - sdk install java 21-open + - sdk use java 21-open From e72b51c981132da028c4c3fda3b5cf6640d1aca8 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 19:02:55 +0000 Subject: [PATCH 060/107] try to publish on jitpack --- jitpack.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jitpack.yml b/jitpack.yml index 759876852..c7b708da5 100644 --- a/jitpack.yml +++ b/jitpack.yml @@ -1,3 +1,3 @@ before_install: - - sdk install java 21-open - - sdk use java 21-open + - sdk install java 21.0.6-tem + - sdk use java 21.0.6-tem From 8fdca17b4b50881b2938a8ac57c0e268e12e8a04 Mon Sep 17 00:00:00 2001 From: chris Date: Sun, 16 Feb 2025 19:19:24 +0000 Subject: [PATCH 061/107] try to publish on jitpack --- jitpack.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/jitpack.yml b/jitpack.yml index c7b708da5..00bbed331 100644 --- a/jitpack.yml +++ b/jitpack.yml @@ -1,3 +1,5 @@ before_install: - sdk install java 21.0.6-tem - sdk use java 21.0.6-tem + - sdk install maven 3.9.9 + - sdk use maven 3.9.9 From 4ecb3b83c8ce205730e984041a3b2be9f2dc9a7f Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 11:52:58 +0000 Subject: [PATCH 062/107] rename to configurable-java-format --- .github/workflows/{cgjf-ci.yml => cjf-ci.yml} | 0 .../{cgjf-release.yml => cjf-release.yml} | 2 +- ...tream.yml => cjf-update-from-upstream.yml} | 0 .github/workflows/coverity-scan.yml | 2 +- README.adoc | 28 ++++++++++++------- cgjf-release.md | 2 +- core/pom.xml | 8 +++--- pom.xml | 6 ++-- 8 files changed, 28 insertions(+), 20 deletions(-) rename .github/workflows/{cgjf-ci.yml => cjf-ci.yml} (100%) rename .github/workflows/{cgjf-release.yml => cjf-release.yml} (89%) rename .github/workflows/{cgjf-update-from-upstream.yml => cjf-update-from-upstream.yml} (100%) diff --git a/.github/workflows/cgjf-ci.yml b/.github/workflows/cjf-ci.yml similarity index 100% rename from .github/workflows/cgjf-ci.yml rename to .github/workflows/cjf-ci.yml diff --git a/.github/workflows/cgjf-release.yml b/.github/workflows/cjf-release.yml similarity index 89% rename from .github/workflows/cgjf-release.yml rename to .github/workflows/cjf-release.yml index fadab657c..9ed6a52e7 100644 --- a/.github/workflows/cgjf-release.yml +++ b/.github/workflows/cjf-release.yml @@ -26,7 +26,7 @@ jobs: - uses: ncipollo/release-action@v1 with: - artifacts: "core/target/configurable-google-java-format-*.*" + artifacts: "core/target/configurable-java-format-*.*" bodyFile: "cgjf-release.md" token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ github.ref_name }} \ No newline at end of file diff --git a/.github/workflows/cgjf-update-from-upstream.yml b/.github/workflows/cjf-update-from-upstream.yml similarity index 100% rename from .github/workflows/cgjf-update-from-upstream.yml rename to .github/workflows/cjf-update-from-upstream.yml diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml index f08148105..416ef8639 100644 --- a/.github/workflows/coverity-scan.yml +++ b/.github/workflows/coverity-scan.yml @@ -22,7 +22,7 @@ jobs: - name: Download Coverity Build Tool run: | wget -q https://scan.coverity.com/download/linux64 \ - --post-data "token=${{ secrets.COVERITY_SCAN_TOKEN }}&project=MrDolch/configurable-google-java-format" \ + --post-data "token=${{ secrets.COVERITY_SCAN_TOKEN }}&project=MrDolch/configurable-java-format" \ -O coverity_tool.tgz tar xzf coverity_tool.tgz mv cov-analysis* coverity diff --git a/README.adoc b/README.adoc index 7b0fcd370..cd8a483f6 100644 --- a/README.adoc +++ b/README.adoc @@ -1,9 +1,8 @@ -= Configurable Google Java Format += Configurable Java Format -link:https://scan.coverity.com/projects/mrdolch-configurable-google-java-format[image:https://scan.coverity.com/projects/31341/badge.svg[Coverity Scan Build Status]] +link:https://scan.coverity.com/projects/mrdolch-configurable-java-format[image:https://scan.coverity.com/projects/31341/badge.svg[Coverity Scan Build Status]] - -This project is a fork of `google-java-format`, an automatic code formatter for Java. +This is a fork of `google-java-format` with extended configurability. This project is not affiliated with Google. == Changes from the Original @@ -13,16 +12,25 @@ This project is a fork of `google-java-format`, an automatic code formatter for == Usage -```sh -java -jar configurable-google-java-format.jar --width=120 File.java -``` +[source,sh] +---- +# Help +java -jar configurable-java-format.jar --help + +# Format +java -jar configurable-java-format.jar --width=120 File.java + +# Format in place +java -jar configurable-java-format.jar --width=120 -i File.java +---- Alternatively, options can be passed as environment variables: -```sh +[source,sh] +---- export JAVA_FORMAT_WIDTH=120 -java -jar configurable-google-java-format.jar File.java -``` +java -jar configurable-java-format.jar File.java +---- == IntelliJ Plugin diff --git a/cgjf-release.md b/cgjf-release.md index f6b94d034..46b4ce4dd 100644 --- a/cgjf-release.md +++ b/cgjf-release.md @@ -1,3 +1,3 @@ -# configurable google java format +# configurable java format automatic release \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml index b5645ece5..5ee7cfbbf 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,14 +20,14 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.github.mrdolch.googlejavaformat - configurable-google-java-format-parent + com.github.mrdolch.formatter + configurable-java-format-parent 2025.21.3 - configurable-google-java-format + configurable-java-format - Google Java Format + Configurable Java Format A Java source code formatter that follows Google Java Style. diff --git a/pom.xml b/pom.xml index 4bc350b5d..9cd04538a 100644 --- a/pom.xml +++ b/pom.xml @@ -20,16 +20,16 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.github.mrdolch.googlejavaformat - configurable-google-java-format-parent + com.github.mrdolch.formatter + configurable-java-format-parent pom 2025.21.3 + Java Format Parent core - Google Java Format Parent A Java source code formatter that follows Google Java Style. From 347f1325b53da7e6e7cc705958c8c393dd0b6c48 Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 11:59:06 +0000 Subject: [PATCH 063/107] rename to configurable-java-format --- README.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.adoc b/README.adoc index cd8a483f6..f0f776b27 100644 --- a/README.adoc +++ b/README.adoc @@ -1,6 +1,6 @@ = Configurable Java Format -link:https://scan.coverity.com/projects/mrdolch-configurable-java-format[image:https://scan.coverity.com/projects/31341/badge.svg[Coverity Scan Build Status]] +link:https://scan.coverity.com/projects/mrdolch-configurable-java-format[image:https://scan.coverity.com/projects/31383/badge.svg[Coverity Scan Build Status]] This is a fork of `google-java-format` with extended configurability. This project is not affiliated with Google. From ba1ed437d78f896b5bde0a5a60268dcb2099ecae Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 12:55:33 +0000 Subject: [PATCH 064/107] prepare publishing on maven central --- core/pom.xml | 2 +- pom.xml | 52 ++++++++++++++++++++++------------------------------ 2 files changed, 23 insertions(+), 31 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 5ee7cfbbf..eeacda452 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.github.mrdolch.formatter + io.github.mrdolch.formatter configurable-java-format-parent 2025.21.3 diff --git a/pom.xml b/pom.xml index 9cd04538a..e313b5689 100644 --- a/pom.xml +++ b/pom.xml @@ -20,11 +20,18 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.github.mrdolch.formatter - configurable-java-format-parent - pom - 2025.21.3 - Java Format Parent + io.github.mrdolch.formatter + configurable-java-format-parent + pom + 2025.21.3 + Java Format Parent + + + https://github.com/mrdolch/configurable-java-format + scm:git:https://github.com/mrdolch/configurable-java-format.git + scm:git:git@github.com:mrdolch/configurable-java-format.git + HEAD + core @@ -241,7 +248,7 @@ attach-sources - jar + jar-no-fork @@ -292,30 +299,15 @@ - org.apache.maven.plugins - maven-source-plugin - ${maven-source-plugin.version} - - - attach-sources - - jar-no-fork - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - ${maven-javadoc-plugin.version} - - - attach-javadocs - - jar - - - + org.sonatype.central + central-publishing-maven-plugin + 0.5.0 + true + + false + ${project.artifactId}:${project.version} + validated + org.apache.maven.plugins From 13cd467a6e04366cdb8f2c6247618ca606cee948 Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 13:14:28 +0000 Subject: [PATCH 065/107] prepare publishing on maven central --- ...cjf-release.yml => cjf-github-release.yml} | 4 +-- .github/workflows/cjf-maven-release.yml | 33 +++++++++++++++++++ cgjf-release.md => cjf-release.md | 0 pom.xml | 10 ++++++ 4 files changed, 45 insertions(+), 2 deletions(-) rename .github/workflows/{cjf-release.yml => cjf-github-release.yml} (91%) create mode 100644 .github/workflows/cjf-maven-release.yml rename cgjf-release.md => cjf-release.md (100%) diff --git a/.github/workflows/cjf-release.yml b/.github/workflows/cjf-github-release.yml similarity index 91% rename from .github/workflows/cjf-release.yml rename to .github/workflows/cjf-github-release.yml index 9ed6a52e7..73d13c375 100644 --- a/.github/workflows/cjf-release.yml +++ b/.github/workflows/cjf-github-release.yml @@ -1,4 +1,4 @@ -name: Releases +name: Release on GitHub on: push: @@ -27,6 +27,6 @@ jobs: - uses: ncipollo/release-action@v1 with: artifacts: "core/target/configurable-java-format-*.*" - bodyFile: "cgjf-release.md" + bodyFile: "cjf-release.md" token: ${{ secrets.GITHUB_TOKEN }} tag: ${{ github.ref_name }} \ No newline at end of file diff --git a/.github/workflows/cjf-maven-release.yml b/.github/workflows/cjf-maven-release.yml new file mode 100644 index 000000000..803481b11 --- /dev/null +++ b/.github/workflows/cjf-maven-release.yml @@ -0,0 +1,33 @@ +name: Release +on: + workflow_dispatch: +jobs: + release: + permissions: + contents: write # to manage the POM's version + runs-on: ubuntu-latest + steps: + - name: Check-out + uses: actions/checkout@v4 + - name: Set up JDK + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + cache: maven + gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} + server-id: central + server-username: SONATYPE_USERNAME + server-password: SONATYPE_TOKEN + - name: Release with Maven + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + mvn -B -ntp -Dstyle.color=always release:prepare + VERSION=`cat release.properties | grep scm.tag= | cut -d'=' -f2` + mvn -B -ntp -Dstyle.color=always release:perform + echo "Released ${VERSION}" >> $GITHUB_STEP_SUMMARY + env: + GPG_PASSPHRASE: '' + SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} + SONATYPE_TOKEN: ${{ secrets.SONATYPE_TOKEN }} \ No newline at end of file diff --git a/cgjf-release.md b/cjf-release.md similarity index 100% rename from cgjf-release.md rename to cjf-release.md diff --git a/pom.xml b/pom.xml index e313b5689..757f539a7 100644 --- a/pom.xml +++ b/pom.xml @@ -178,6 +178,16 @@ maven-bundle-plugin 6.0.0 + + org.apache.maven.plugins + maven-release-plugin + 3.1.1 + + -ntp + + @{project.version} + + From 02d8c904d825f29b32c397061f17b10337b23bfe Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 13:18:39 +0000 Subject: [PATCH 066/107] prepare publishing on maven central --- .github/workflows/cjf-maven-release.yml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/cjf-maven-release.yml b/.github/workflows/cjf-maven-release.yml index 803481b11..63a303e61 100644 --- a/.github/workflows/cjf-maven-release.yml +++ b/.github/workflows/cjf-maven-release.yml @@ -1,4 +1,4 @@ -name: Release +name: Release on Maven Central on: workflow_dispatch: jobs: diff --git a/pom.xml b/pom.xml index 757f539a7..65bc6192e 100644 --- a/pom.xml +++ b/pom.xml @@ -311,7 +311,7 @@ org.sonatype.central central-publishing-maven-plugin - 0.5.0 + 0.7.0 true false From 39c7b6b2a54347de78737ea6bd78a8845d122795 Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 13:24:10 +0000 Subject: [PATCH 067/107] prepare publishing on maven central --- core/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index eeacda452..15d9acecd 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.3 + 2025.21.4-SNAPSHOT configurable-java-format diff --git a/pom.xml b/pom.xml index 65bc6192e..d84abb8bf 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.3 + 2025.21.4-SNAPSHOT Java Format Parent From eab9bdea8571226434c6b8ce9fc8de8446205453 Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 13:33:25 +0000 Subject: [PATCH 068/107] prepare publishing on maven central --- pom.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/pom.xml b/pom.xml index d84abb8bf..6f4336905 100644 --- a/pom.xml +++ b/pom.xml @@ -27,10 +27,7 @@ Java Format Parent - https://github.com/mrdolch/configurable-java-format scm:git:https://github.com/mrdolch/configurable-java-format.git - scm:git:git@github.com:mrdolch/configurable-java-format.git - HEAD From d3f26c7920f319ba5a3b7e27ede1a751da558ea0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 13:34:48 +0000 Subject: [PATCH 069/107] [maven-release-plugin] prepare release 2025.21.4 --- core/pom.xml | 6 ++---- pom.xml | 7 +++---- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 15d9acecd..edd8619d9 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -15,14 +15,12 @@ ~ limitations under the License. --> - + 4.0.0 io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.4-SNAPSHOT + 2025.21.4 configurable-java-format diff --git a/pom.xml b/pom.xml index 6f4336905..bc7a4d7ac 100644 --- a/pom.xml +++ b/pom.xml @@ -15,19 +15,18 @@ ~ limitations under the License. --> - + 4.0.0 io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.4-SNAPSHOT + 2025.21.4 Java Format Parent scm:git:https://github.com/mrdolch/configurable-java-format.git + 2025.21.4 From 11bdb6b8236e8830dd7d2ef0a568827bad114a5a Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 13:47:54 +0000 Subject: [PATCH 070/107] prepare publishing on maven central --- .github/workflows/cjf-maven-release.yml | 4 ++-- core/pom.xml | 2 +- pom.xml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/cjf-maven-release.yml b/.github/workflows/cjf-maven-release.yml index 63a303e61..72688a38b 100644 --- a/.github/workflows/cjf-maven-release.yml +++ b/.github/workflows/cjf-maven-release.yml @@ -23,9 +23,9 @@ jobs: run: | git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - mvn -B -ntp -Dstyle.color=always release:prepare + mvn -B -ntp -Dstyle.color=always -Psonatype-oss-release release:prepare VERSION=`cat release.properties | grep scm.tag= | cut -d'=' -f2` - mvn -B -ntp -Dstyle.color=always release:perform + mvn -B -ntp -Dstyle.color=always -Psonatype-oss-release release:perform echo "Released ${VERSION}" >> $GITHUB_STEP_SUMMARY env: GPG_PASSPHRASE: '' diff --git a/core/pom.xml b/core/pom.xml index edd8619d9..931452d93 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.4 + 2025.21.5-SNAPSHOT configurable-java-format diff --git a/pom.xml b/pom.xml index bc7a4d7ac..2ebb7f30a 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.4 + 2025.21.5-SNAPSHOT Java Format Parent From 8bb2fabaf6464e04cd8524da6dcf426a0de7836a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 13:59:33 +0000 Subject: [PATCH 071/107] [maven-release-plugin] prepare release 2025.21.5 --- core/pom.xml | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 931452d93..088a69791 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.5-SNAPSHOT + 2025.21.5 configurable-java-format diff --git a/pom.xml b/pom.xml index 2ebb7f30a..b363c16d6 100644 --- a/pom.xml +++ b/pom.xml @@ -21,12 +21,12 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.5-SNAPSHOT + 2025.21.5 Java Format Parent scm:git:https://github.com/mrdolch/configurable-java-format.git - 2025.21.4 + 2025.21.5 From 09b5aee9453d782a98272f5eb8ec618eb66638d3 Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 14:01:35 +0000 Subject: [PATCH 072/107] prepare publishing on maven central --- core/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 088a69791..d0a9ba35f 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.5 + 2025.21.10-SNAPSHOT configurable-java-format diff --git a/pom.xml b/pom.xml index b363c16d6..7be3116b0 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.5 + 2025.21.10-SNAPSHOT Java Format Parent From 377656f7ad28c4417b00312ac66fea4c7106da01 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 14:02:40 +0000 Subject: [PATCH 073/107] [maven-release-plugin] prepare release 2025.21.10 --- core/pom.xml | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index d0a9ba35f..1b8771eee 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.10-SNAPSHOT + 2025.21.10 configurable-java-format diff --git a/pom.xml b/pom.xml index 7be3116b0..67a7dca7e 100644 --- a/pom.xml +++ b/pom.xml @@ -21,12 +21,12 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.10-SNAPSHOT + 2025.21.10 Java Format Parent scm:git:https://github.com/mrdolch/configurable-java-format.git - 2025.21.5 + 2025.21.10 From 971ec01c477b32a2845885ec2249c36f91d74d55 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 14:02:41 +0000 Subject: [PATCH 074/107] [maven-release-plugin] prepare for next development iteration --- core/pom.xml | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 1b8771eee..4acca407e 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.10 + 2025.21.11-SNAPSHOT configurable-java-format diff --git a/pom.xml b/pom.xml index 67a7dca7e..9fab7d7ae 100644 --- a/pom.xml +++ b/pom.xml @@ -21,12 +21,12 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.10 + 2025.21.11-SNAPSHOT Java Format Parent scm:git:https://github.com/mrdolch/configurable-java-format.git - 2025.21.10 + 2025.21.5 From b066fa0cb7fd2c68f1086ea834c3ce7e95a948ec Mon Sep 17 00:00:00 2001 From: chris Date: Mon, 17 Feb 2025 14:07:20 +0000 Subject: [PATCH 075/107] prepare publishing on maven central --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9fab7d7ae..545f26c31 100644 --- a/pom.xml +++ b/pom.xml @@ -25,8 +25,9 @@ Java Format Parent + https://github.com/mrdolch/configurable-java-format scm:git:https://github.com/mrdolch/configurable-java-format.git - 2025.21.5 + HEAD From f14ca283283a122110e0b218b8fa8aa042bccdb1 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 14:08:16 +0000 Subject: [PATCH 076/107] [maven-release-plugin] prepare release 2025.21.11 --- core/pom.xml | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 4acca407e..6631b8e20 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.11-SNAPSHOT + 2025.21.11 configurable-java-format diff --git a/pom.xml b/pom.xml index 545f26c31..92dcb42d6 100644 --- a/pom.xml +++ b/pom.xml @@ -21,13 +21,13 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.11-SNAPSHOT + 2025.21.11 Java Format Parent https://github.com/mrdolch/configurable-java-format scm:git:https://github.com/mrdolch/configurable-java-format.git - HEAD + 2025.21.11 From 94a5e01c601e18e1765deec2a7117f2de0ebde69 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 14:08:20 +0000 Subject: [PATCH 077/107] [maven-release-plugin] prepare for next development iteration --- core/pom.xml | 2 +- pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 6631b8e20..2f3773797 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.11 + 2025.21.12-SNAPSHOT configurable-java-format diff --git a/pom.xml b/pom.xml index 92dcb42d6..394626244 100644 --- a/pom.xml +++ b/pom.xml @@ -21,13 +21,13 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.11 + 2025.21.12-SNAPSHOT Java Format Parent https://github.com/mrdolch/configurable-java-format scm:git:https://github.com/mrdolch/configurable-java-format.git - 2025.21.11 + HEAD From 72c8b90168780c88285fc9de6ccd22780c9ac01d Mon Sep 17 00:00:00 2001 From: chris Date: Tue, 18 Feb 2025 05:01:04 +0000 Subject: [PATCH 078/107] fix coverity link --- README.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.adoc b/README.adoc index f0f776b27..57bcca9ef 100644 --- a/README.adoc +++ b/README.adoc @@ -1,6 +1,6 @@ = Configurable Java Format -link:https://scan.coverity.com/projects/mrdolch-configurable-java-format[image:https://scan.coverity.com/projects/31383/badge.svg[Coverity Scan Build Status]] +link:https://scan.coverity.com/projects/configurable-java-format[image:https://scan.coverity.com/projects/31383/badge.svg[Coverity Scan Build Status]] This is a fork of `google-java-format` with extended configurability. This project is not affiliated with Google. From d70550d9c489d6b0f69889569febfaef50bd6e59 Mon Sep 17 00:00:00 2001 From: chris Date: Tue, 18 Feb 2025 05:36:57 +0000 Subject: [PATCH 079/107] fix coverity link --- .github/workflows/coverity-scan.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml index 416ef8639..da849c2cc 100644 --- a/.github/workflows/coverity-scan.yml +++ b/.github/workflows/coverity-scan.yml @@ -22,7 +22,7 @@ jobs: - name: Download Coverity Build Tool run: | wget -q https://scan.coverity.com/download/linux64 \ - --post-data "token=${{ secrets.COVERITY_SCAN_TOKEN }}&project=MrDolch/configurable-java-format" \ + --post-data "token=${{ secrets.COVERITY_SCAN_TOKEN }}&project=Configurable+Java+Format" \ -O coverity_tool.tgz tar xzf coverity_tool.tgz mv cov-analysis* coverity From cd189808ef267299cfdf5747b21061f17acc4c38 Mon Sep 17 00:00:00 2001 From: Christoph Dolch Date: Thu, 20 Feb 2025 18:05:27 +0100 Subject: [PATCH 080/107] Update LICENSE --- LICENSE | 3 --- 1 file changed, 3 deletions(-) diff --git a/LICENSE b/LICENSE index 6c4ca5a2c..27cce7e4f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,3 @@ -The following Apache 2.0 license applies to all code in this package except -google-java-format-diff.py. - Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ From 76da3cc6df1558faf76d5a600eac329325008f4e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 21 Feb 2025 11:15:38 +0000 Subject: [PATCH 081/107] Update dependency org.apache.maven.plugins:maven-compiler-plugin to v3.14.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 394626244..2689be381 100644 --- a/pom.xml +++ b/pom.xml @@ -152,7 +152,7 @@ maven-compiler-plugin - 3.13.0 + 3.14.0 maven-jar-plugin From 6db17b23be7e504c93fb5f3a2637aee21fa1aa8f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 12 Mar 2025 12:20:11 +0000 Subject: [PATCH 082/107] Update dependency org.graalvm.buildtools:native-maven-plugin to v0.10.6 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index 2f3773797..9b4fd1f0c 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -238,7 +238,7 @@ org.graalvm.buildtools native-maven-plugin - 0.10.5 + 0.10.6 true From 43cf83610a75b1650e816e91899edfbe582c1c6c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 18:44:50 +0000 Subject: [PATCH 083/107] Update errorprone.version to v2.37.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2689be381..6cf092b67 100644 --- a/pom.xml +++ b/pom.xml @@ -81,7 +81,7 @@ 33.4.0-jre 1.4.4 1.0.0 - 2.36.0 + 2.37.0 1.11.0 1.1.1 3.11.2 From a458baf0a50ce808447361f08048dd476a0dfef3 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 25 Mar 2025 19:24:02 +0000 Subject: [PATCH 084/107] Update guava monorepo to v33.4.6-jre --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2689be381..94011b1a3 100644 --- a/pom.xml +++ b/pom.xml @@ -78,7 +78,7 @@ UTF-8 1.8 - 33.4.0-jre + 33.4.6-jre 1.4.4 1.0.0 2.36.0 From 8b4a2f54ec9c238d8ec0babaf3c8fb9729d24724 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 31 Mar 2025 03:25:14 +0000 Subject: [PATCH 085/107] Update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.5.3 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bf507adae..47bd40a06 100644 --- a/pom.xml +++ b/pom.xml @@ -279,7 +279,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.2 + 3.5.3 From 66765c2f1e8f855bc25b96f53b2b5f838f2a08dd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 9 Apr 2025 17:02:26 +0000 Subject: [PATCH 086/107] Update guava monorepo to v33.4.7-jre --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 47bd40a06..3bafcb3d6 100644 --- a/pom.xml +++ b/pom.xml @@ -78,7 +78,7 @@ UTF-8 1.8 - 33.4.6-jre + 33.4.7-jre 1.4.4 1.0.0 2.37.0 From fff7f7325e9c26e4da5ac0d04710b816a7318043 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 19:57:09 +0000 Subject: [PATCH 087/107] Update guava monorepo to v33.4.8-jre --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 3bafcb3d6..93a9ebc53 100644 --- a/pom.xml +++ b/pom.xml @@ -78,7 +78,7 @@ UTF-8 1.8 - 33.4.7-jre + 33.4.8-jre 1.4.4 1.0.0 2.37.0 From 892ad724fd034b61808aa4e1586c13749c12e3cb Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 4 Jun 2025 22:27:35 +0000 Subject: [PATCH 088/107] chore(deps): update dependency org.codehaus.mojo:build-helper-maven-plugin to v3.6.1 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index 9b4fd1f0c..c55d8f7d3 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -178,7 +178,7 @@ org.codehaus.mojo build-helper-maven-plugin - 3.6.0 + 3.6.1 add-source From 045afb194e3be22095c35c8707430b8b8b2c9041 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 10 Jun 2025 02:05:39 +0000 Subject: [PATCH 089/107] chore(deps): update softprops/action-gh-release action to v2.3.0 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ebdb2d9d9..f255106b1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,7 +70,7 @@ jobs: git push origin "v${{ github.event.inputs.version }}" - name: Add Artifacts to Release Entry - uses: softprops/action-gh-release@v2.2.1 + uses: softprops/action-gh-release@v2.3.0 with: draft: true name: ${{ github.event.input.version }} From 2b58e8eea2a64caea8166cc2a4cc2bc7daaa076d Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 11 Jun 2025 03:26:32 +0000 Subject: [PATCH 090/107] chore(deps): update softprops/action-gh-release action to v2.3.2 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f255106b1..7906eee7a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,7 +70,7 @@ jobs: git push origin "v${{ github.event.inputs.version }}" - name: Add Artifacts to Release Entry - uses: softprops/action-gh-release@v2.3.0 + uses: softprops/action-gh-release@v2.3.2 with: draft: true name: ${{ github.event.input.version }} From 2e4f23f55a0107b0868ad9be66a5f2fa1f7e5fcd Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 17 Jun 2025 22:49:02 +0000 Subject: [PATCH 091/107] chore(deps): update dependency org.sonatype.central:central-publishing-maven-plugin to v0.8.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 93a9ebc53..cf6ee7da6 100644 --- a/pom.xml +++ b/pom.xml @@ -308,7 +308,7 @@ org.sonatype.central central-publishing-maven-plugin - 0.7.0 + 0.8.0 true false From baecf78b140022274317e73d720ec18629a12517 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 2 Jul 2025 11:48:21 +0000 Subject: [PATCH 092/107] chore(deps): update dependency org.apache.maven.plugins:maven-gpg-plugin to v3.2.8 --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 93a9ebc53..72b93e9cd 100644 --- a/pom.xml +++ b/pom.xml @@ -168,7 +168,7 @@ maven-gpg-plugin - 3.2.7 + 3.2.8 org.apache.felix @@ -319,7 +319,7 @@ org.apache.maven.plugins maven-gpg-plugin - 3.2.7 + 3.2.8 sign-artifacts From cf904b153d0050c25fc14e0b9d1037102210e838 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 9 Jul 2025 19:50:56 +0000 Subject: [PATCH 093/107] fix(deps): update errorprone.version to v2.40.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 93a9ebc53..113505322 100644 --- a/pom.xml +++ b/pom.xml @@ -81,7 +81,7 @@ 33.4.8-jre 1.4.4 1.0.0 - 2.37.0 + 2.40.0 1.11.0 1.1.1 3.11.2 From dd769bca057e7257f9eb25a954a7e85b0314d3ef Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 18 Jul 2025 15:14:13 +0000 Subject: [PATCH 094/107] chore(deps): update dependency org.graalvm.buildtools:native-maven-plugin to v0.11.0 --- core/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/pom.xml b/core/pom.xml index c55d8f7d3..8489adc7a 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -238,7 +238,7 @@ org.graalvm.buildtools native-maven-plugin - 0.10.6 + 0.11.0 true From e442367d6e353f2222c0b533584dd6a5f7ddfa91 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 11 Aug 2025 13:38:02 +0000 Subject: [PATCH 095/107] chore(deps): update actions/checkout action to v5 --- .github/workflows/cjf-ci.yml | 2 +- .github/workflows/cjf-github-release.yml | 2 +- .github/workflows/cjf-maven-release.yml | 2 +- .github/workflows/cjf-update-from-upstream.yml | 2 +- .github/workflows/coverity-scan.yml | 2 +- .github/workflows/maven-publish.yml | 2 +- .github/workflows/release.yml | 4 ++-- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/cjf-ci.yml b/.github/workflows/cjf-ci.yml index dd92c3280..66ec9ae8f 100644 --- a/.github/workflows/cjf-ci.yml +++ b/.github/workflows/cjf-ci.yml @@ -51,7 +51,7 @@ jobs: with: access_token: ${{ github.token }} - name: "Check out repository" - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: "Set up JDK ${{ matrix.java }} from jdk.java.net" if: ${{ matrix.java == 'EA' }} uses: oracle-actions/setup-java@v1 diff --git a/.github/workflows/cjf-github-release.yml b/.github/workflows/cjf-github-release.yml index 73d13c375..bfe33c5cb 100644 --- a/.github/workflows/cjf-github-release.yml +++ b/.github/workflows/cjf-github-release.yml @@ -13,7 +13,7 @@ jobs: packages: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: "Set up JDK 21 from Zulu" uses: actions/setup-java@v4 diff --git a/.github/workflows/cjf-maven-release.yml b/.github/workflows/cjf-maven-release.yml index 72688a38b..a080771ac 100644 --- a/.github/workflows/cjf-maven-release.yml +++ b/.github/workflows/cjf-maven-release.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check-out - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up JDK uses: actions/setup-java@v4 with: diff --git a/.github/workflows/cjf-update-from-upstream.yml b/.github/workflows/cjf-update-from-upstream.yml index d354dfeb6..f5f2edefd 100644 --- a/.github/workflows/cjf-update-from-upstream.yml +++ b/.github/workflows/cjf-update-from-upstream.yml @@ -26,7 +26,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: # Required because otherwise there are always changes detected when executing diff/rev-list fetch-depth: 0 diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml index da849c2cc..0f5aba9b8 100644 --- a/.github/workflows/coverity-scan.yml +++ b/.github/workflows/coverity-scan.yml @@ -14,7 +14,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install dependencies run: sudo apt-get install build-essential cmake -y diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index 9216a7e58..226c0c05c 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -16,7 +16,7 @@ jobs: packages: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set up JDK 17 uses: actions/setup-java@v4 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7906eee7a..d6da23b56 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,7 +28,7 @@ jobs: contents: write steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Set up JDK uses: actions/setup-java@v4 @@ -98,7 +98,7 @@ jobs: EXTENSION: ${{ matrix.os == 'windows-latest' && '.exe' || '' }} steps: - name: "Check out repository" - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: "Set up GraalVM" uses: graalvm/setup-graalvm@v1 with: From f508d95122b30028ef6427372acf84a924b36b22 Mon Sep 17 00:00:00 2001 From: trick77 Date: Fri, 16 Jan 2026 20:31:08 +0100 Subject: [PATCH 096/107] ci: use Java 25, remove Coverity scan --- .github/workflows/cjf-ci.yml | 6 ++-- .github/workflows/cjf-github-release.yml | 4 +-- .github/workflows/cjf-maven-release.yml | 2 +- .github/workflows/coverity-scan.yml | 43 ------------------------ .github/workflows/maven-publish.yml | 4 +-- .github/workflows/release.yml | 2 +- 6 files changed, 9 insertions(+), 52 deletions(-) delete mode 100644 .github/workflows/coverity-scan.yml diff --git a/.github/workflows/cjf-ci.yml b/.github/workflows/cjf-ci.yml index 66ec9ae8f..cc1e136eb 100644 --- a/.github/workflows/cjf-ci.yml +++ b/.github/workflows/cjf-ci.yml @@ -29,16 +29,16 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest] - java: [21, 17] + java: [25] experimental: [false] include: # Only test on MacOS and Windows with a single recent JDK to avoid a # combinatorial explosion of test configurations. - os: macos-latest - java: 21 + java: 25 experimental: false - os: windows-latest - java: 21 + java: 25 experimental: false - os: ubuntu-latest java: EA diff --git a/.github/workflows/cjf-github-release.yml b/.github/workflows/cjf-github-release.yml index bfe33c5cb..fef9b9c9e 100644 --- a/.github/workflows/cjf-github-release.yml +++ b/.github/workflows/cjf-github-release.yml @@ -15,10 +15,10 @@ jobs: steps: - uses: actions/checkout@v5 - - name: "Set up JDK 21 from Zulu" + - name: "Set up JDK 25 from Zulu" uses: actions/setup-java@v4 with: - java-version: 21 + java-version: 25 distribution: "zulu" - name: Build with Maven diff --git a/.github/workflows/cjf-maven-release.yml b/.github/workflows/cjf-maven-release.yml index a080771ac..0d98f77a8 100644 --- a/.github/workflows/cjf-maven-release.yml +++ b/.github/workflows/cjf-maven-release.yml @@ -13,7 +13,7 @@ jobs: uses: actions/setup-java@v4 with: distribution: 'temurin' - java-version: '21' + java-version: '25' cache: maven gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} server-id: central diff --git a/.github/workflows/coverity-scan.yml b/.github/workflows/coverity-scan.yml deleted file mode 100644 index 0f5aba9b8..000000000 --- a/.github/workflows/coverity-scan.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Coverity Scan - -on: - push: - branches: - - master - pull_request: - branches: - - master - -jobs: - coverity_scan: - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@v5 - - - name: Install dependencies - run: sudo apt-get install build-essential cmake -y - - - name: Download Coverity Build Tool - run: | - wget -q https://scan.coverity.com/download/linux64 \ - --post-data "token=${{ secrets.COVERITY_SCAN_TOKEN }}&project=Configurable+Java+Format" \ - -O coverity_tool.tgz - tar xzf coverity_tool.tgz - mv cov-analysis* coverity - - - name: Run Coverity Analysis - run: | - export PATH="$(pwd)/coverity/bin:$PATH" - cov-build --dir cov-int mvn clean install - - - name: Upload results to Coverity - run: | - tar czf cov-int.tgz cov-int - curl --form token=${{ secrets.COVERITY_SCAN_TOKEN }} \ - --form email=${{ secrets.COVERITY_SCAN_EMAIL }} \ - --form file=@cov-int.tgz \ - --form version="$(git rev-parse --short HEAD)" \ - --form description="Coverity Scan for latest commit" \ - https://scan.coverity.com/builds diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index 226c0c05c..8d24b8587 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -17,10 +17,10 @@ jobs: steps: - uses: actions/checkout@v5 - - name: Set up JDK 17 + - name: Set up JDK 25 uses: actions/setup-java@v4 with: - java-version: '17' + java-version: '25' distribution: 'temurin' server-id: github # Value of the distributionManagement/repository/id field of the pom.xml settings-path: ${{ github.workspace }} # location for the settings.xml file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a7279550f..f9c86c8bd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: - name: Set up JDK uses: actions/setup-java@v4 with: - java-version: 21 + java-version: 25 distribution: "zulu" cache: "maven" server-id: central From bf0c7c42b71f457cbe2a02a14e710ab695948ac4 Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 08:06:21 +0100 Subject: [PATCH 097/107] Update pipeline --- .github/workflows/{cjf-ci.yml => ci.yaml} | 0 .../workflows/cjf-update-from-upstream.yml | 93 ------------ ...github-release.yml => github-release.yaml} | 0 .github/workflows/maven-publish.yml | 34 ----- ...f-maven-release.yml => maven-release.yaml} | 0 .github/workflows/release.yml | 120 --------------- .github/workflows/update-from-upstream.yaml | 139 ++++++++++++++++++ core/pom.xml | 2 +- pom.xml | 6 +- 9 files changed, 143 insertions(+), 251 deletions(-) rename .github/workflows/{cjf-ci.yml => ci.yaml} (100%) delete mode 100644 .github/workflows/cjf-update-from-upstream.yml rename .github/workflows/{cjf-github-release.yml => github-release.yaml} (100%) delete mode 100644 .github/workflows/maven-publish.yml rename .github/workflows/{cjf-maven-release.yml => maven-release.yaml} (100%) delete mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/update-from-upstream.yaml diff --git a/.github/workflows/cjf-ci.yml b/.github/workflows/ci.yaml similarity index 100% rename from .github/workflows/cjf-ci.yml rename to .github/workflows/ci.yaml diff --git a/.github/workflows/cjf-update-from-upstream.yml b/.github/workflows/cjf-update-from-upstream.yml deleted file mode 100644 index f5f2edefd..000000000 --- a/.github/workflows/cjf-update-from-upstream.yml +++ /dev/null @@ -1,93 +0,0 @@ -name: Update from Template - -# This workflow keeps the repo up to date with changes from the template repo (REMOTE_URL) -# It duplicates the REMOTE_BRANCH (into UPDATE_BRANCH) and tries to merge it into -# this repos default branch (which is checked out here) -# Note that this requires a PAT (Personal Access Token) - at best from a servicing account -# Also note that you should have at least once merged the template repo into the current -# repo manually otherwise a "refusing to merge unrelated histories" error might occur. - -on: - schedule: - - cron: '55 2 * * 1' - workflow_dispatch: - -env: - UPDATE_BRANCH: update-from-template - REMOTE_URL: https://github.com/google/google-java-format.git - REMOTE_BRANCH: master - -permissions: - contents: write - pull-requests: write - -jobs: - update: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v5 - with: - # Required because otherwise there are always changes detected when executing diff/rev-list - fetch-depth: 0 - # If no PAT is used the following error occurs on a push: - # refusing to allow a GitHub App to create or update workflow `.github/workflows/xxx.yml` without `workflows` permission - token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} - - - name: Init Git - run: | - git config --global user.email "actions@github.com" - git config --global user.name "GitHub Actions" - - - name: Main workflow - id: main - run: | - echo "Adding remote template-repo" - git remote add template ${{ env.REMOTE_URL }} - - echo "Fetching remote template repo" - git fetch template - - echo "Deleting local branch that will contain the updates - if present" - git branch -D ${{ env.UPDATE_BRANCH }} || true - - echo "Checking if the remote template repo has new commits" - git rev-list ..template/${{ env.REMOTE_BRANCH }} - - if [ $(git rev-list --count ..template/${{ env.REMOTE_BRANCH }}) -eq 0 ]; then - echo "There are no commits new commits on the template repo" - - echo "Deleting origin branch that contains the updates - if present" - git push -f origin --delete ${{ env.UPDATE_BRANCH }} || true - - echo "abort=1" >> $GITHUB_OUTPUT - exit 0 - fi - - echo "Found new commits on the template repo" - - echo "Creating update branch" - git branch ${{ env.UPDATE_BRANCH }} template/${{ env.REMOTE_BRANCH }} - git branch --unset-upstream ${{ env.UPDATE_BRANCH }} - - echo "Pushing update branch" - git push -f -u origin ${{ env.UPDATE_BRANCH }} - - echo "Getting current branch" - current_branch=$(git branch --show-current) - echo "Current branch is $current_branch" - echo "current_branch=$current_branch" >> $GITHUB_OUTPUT - - echo "abort=0" >> $GITHUB_OUTPUT - - - name: pull-request - if: steps.main.outputs.abort == 0 - env: - GH_TOKEN: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} - run: | - gh_pr_up() { - gh pr create -H "${{ env.UPDATE_BRANCH }}" "$@" || (git checkout "${{ env.UPDATE_BRANCH }}" && gh pr edit "$@") - } - gh_pr_up -B "${{ steps.main.outputs.current_branch }}" \ - --title "Update from template" \ - --body "An automated PR to sync changes from the template into this repo" diff --git a/.github/workflows/cjf-github-release.yml b/.github/workflows/github-release.yaml similarity index 100% rename from .github/workflows/cjf-github-release.yml rename to .github/workflows/github-release.yaml diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml deleted file mode 100644 index 8d24b8587..000000000 --- a/.github/workflows/maven-publish.yml +++ /dev/null @@ -1,34 +0,0 @@ -# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created -# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path - -name: Maven Package - -on: - release: - types: [created] - -jobs: - build: - - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - - steps: - - uses: actions/checkout@v5 - - name: Set up JDK 25 - uses: actions/setup-java@v4 - with: - java-version: '25' - distribution: 'temurin' - server-id: github # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Build with Maven - run: mvn -B package --file pom.xml - - - name: Publish to GitHub Packages Apache Maven - run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml - env: - GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/cjf-maven-release.yml b/.github/workflows/maven-release.yaml similarity index 100% rename from .github/workflows/cjf-maven-release.yml rename to .github/workflows/maven-release.yaml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index f9c86c8bd..000000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,120 +0,0 @@ -# Copyright 2020 The Google Java Format Authors -# -# 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. - -name: Release google-java-format - -on: - workflow_dispatch: - inputs: - version: - description: "version number for this release." - required: true - -jobs: - build-maven-jars: - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - name: Checkout - uses: actions/checkout@v5 - - - name: Set up JDK - uses: actions/setup-java@v4 - with: - java-version: 25 - distribution: "zulu" - cache: "maven" - server-id: central - server-username: CI_DEPLOY_USERNAME - server-password: CI_DEPLOY_PASSWORD - gpg-private-key: ${{ secrets.GPG_SIGNING_KEY }} - gpg-passphrase: MAVEN_GPG_PASSPHRASE - - - name: Bump Version Number - run: | - mvn --no-transfer-progress versions:set versions:commit -DnewVersion="${{ github.event.inputs.version }}" - mvn --no-transfer-progress versions:set versions:commit -DnewVersion="${{ github.event.inputs.version }}" -pl eclipse_plugin - mvn tycho-versions:update-eclipse-metadata -pl eclipse_plugin - git ls-files | grep -E '(pom.xml|MANIFEST.MF)$' | xargs git add - git config --global user.email "${{ github.actor }}@users.noreply.github.com" - git config --global user.name "${{ github.actor }}" - git commit -m "Release google-java-format ${{ github.event.inputs.version }}" - git tag "v${{ github.event.inputs.version }}" - echo "TARGET_COMMITISH=$(git rev-parse HEAD)" >> $GITHUB_ENV - git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/google/google-java-format.git - - - name: Deploy to Sonatype staging - env: - CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} - CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} - GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} - run: mvn --no-transfer-progress -pl '!eclipse_plugin' -P sonatype-oss-release clean deploy -Dgpg.passphrase="${{ secrets.GPG_PASSPHRASE }}" - - - name: Build Eclipse plugin - run: mvn --no-transfer-progress -pl 'eclipse_plugin' verify gpg:sign -DskipTests=true -Dgpg.passphrase="${{ secrets.GPG_PASSPHRASE }}" - - - name: Push tag - run: | - git push origin "v${{ github.event.inputs.version }}" - - - name: Add Artifacts to Release Entry - uses: softprops/action-gh-release@v2.3.2 - with: - draft: true - name: ${{ github.event.input.version }} - tag_name: "v${{ github.event.inputs.version }}" - target_commitish: ${{ env.TARGET_COMMITISH }} - files: | - core/target/google-java-format-*.jar - eclipse_plugin/target/google-java-format-eclipse-plugin-*.jar - - build-native-image: - name: "Build GraalVM native-image on ${{ matrix.os }}" - runs-on: ${{ matrix.os }} - permissions: - contents: write - needs: build-maven-jars - strategy: - matrix: - # Use "oldest" available ubuntu-* instead of -latest, - # see https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories; - # due to https://github.com/google/google-java-format/issues/1072. - os: [ubuntu-22.04, ubuntu-22.04-arm, macos-latest, windows-latest] - env: - # NB: Must keep the keys in this inline JSON below in line with the os: above! - SUFFIX: ${{fromJson('{"ubuntu-22.04":"linux-x86-64", "ubuntu-22.04-arm":"linux-arm64", "macos-latest":"darwin-arm64", "windows-latest":"windows-x86-64"}')[matrix.os]}} - EXTENSION: ${{ matrix.os == 'windows-latest' && '.exe' || '' }} - steps: - - name: "Check out repository" - uses: actions/checkout@v5 - - name: "Set up GraalVM" - uses: graalvm/setup-graalvm@v1 - with: - java-version: "25" - distribution: "graalvm-community" - github-token: ${{ secrets.GITHUB_TOKEN }} - native-image-job-reports: "true" - cache: "maven" - - name: Bump Version Number - run: mvn --no-transfer-progress versions:set versions:commit -DnewVersion="${{ github.event.inputs.version }}" - - name: "Native" - run: mvn -Pnative -DskipTests package -pl core -am - - name: "Move outputs" - run: cp core/target/google-java-format${{ env.EXTENSION }} google-java-format_${{ env.SUFFIX }}${{ env.EXTENSION }} - - name: "Upload native-image" - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - run: gh release upload "v${{ github.event.inputs.version }}" "google-java-format_${{ env.SUFFIX }}${{ env.EXTENSION }}" diff --git a/.github/workflows/update-from-upstream.yaml b/.github/workflows/update-from-upstream.yaml new file mode 100644 index 000000000..61667737e --- /dev/null +++ b/.github/workflows/update-from-upstream.yaml @@ -0,0 +1,139 @@ +name: Sync from Upstream Release + +# This workflow syncs from upstream google/google-java-format when a new release is published. +# It checks daily for new releases, creates a PR to sync the changes, and after merge, +# creates a tag that triggers the GitHub release workflow. + +on: + schedule: + - cron: '0 6 * * *' # Daily at 6 AM UTC + workflow_dispatch: + pull_request: + types: [closed] + branches: [master] + +env: + UPDATE_BRANCH: update-from-upstream + REMOTE_URL: https://github.com/google/google-java-format.git + +permissions: + contents: write + pull-requests: write + +jobs: + check-and-sync: + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + + - name: Init Git + run: | + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + - name: Check for new upstream release + id: check-release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + echo "Fetching latest release from google/google-java-format..." + LATEST_RELEASE=$(gh api repos/google/google-java-format/releases/latest --jq '.tag_name') + echo "Latest upstream release: $LATEST_RELEASE" + echo "latest_release=$LATEST_RELEASE" >> $GITHUB_OUTPUT + + # Check if we already have this release synced (look for matching tag) + if git tag --list | grep -q "^${LATEST_RELEASE}$"; then + echo "Release $LATEST_RELEASE already synced (tag exists)" + echo "needs_sync=false" >> $GITHUB_OUTPUT + else + echo "New release $LATEST_RELEASE needs to be synced" + echo "needs_sync=true" >> $GITHUB_OUTPUT + fi + + - name: Sync upstream release + if: steps.check-release.outputs.needs_sync == 'true' + id: sync + run: | + RELEASE_TAG="${{ steps.check-release.outputs.latest_release }}" + echo "Syncing upstream release $RELEASE_TAG" + + echo "Adding remote upstream" + git remote add upstream ${{ env.REMOTE_URL }} + + echo "Fetching upstream tags" + git fetch upstream --tags + + echo "Deleting local update branch if present" + git branch -D ${{ env.UPDATE_BRANCH }} || true + + echo "Creating update branch from upstream release tag" + git checkout -b ${{ env.UPDATE_BRANCH }} "$RELEASE_TAG" + + echo "Pushing update branch" + git push -f -u origin ${{ env.UPDATE_BRANCH }} + + echo "Getting current default branch" + git checkout master + current_branch=$(git branch --show-current) + echo "Current branch is $current_branch" + echo "current_branch=$current_branch" >> $GITHUB_OUTPUT + echo "release_tag=$RELEASE_TAG" >> $GITHUB_OUTPUT + + - name: Create or update pull request + if: steps.check-release.outputs.needs_sync == 'true' + env: + GH_TOKEN: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + run: | + RELEASE_TAG="${{ steps.sync.outputs.release_tag }}" + + # Close any existing sync PRs + existing_prs=$(gh pr list --head "${{ env.UPDATE_BRANCH }}" --json number --jq '.[].number') + for pr in $existing_prs; do + echo "Closing existing PR #$pr" + gh pr close "$pr" || true + done + + # Create new PR + gh pr create \ + --head "${{ env.UPDATE_BRANCH }}" \ + --base "${{ steps.sync.outputs.current_branch }}" \ + --title "Sync upstream release $RELEASE_TAG" \ + --body "Automated PR to sync changes from upstream google-java-format release $RELEASE_TAG. + +After this PR is merged, a tag will be automatically created which triggers a GitHub release. + +**Upstream release:** https://github.com/google/google-java-format/releases/tag/$RELEASE_TAG" + + create-tag-on-merge: + if: | + github.event_name == 'pull_request' && + github.event.pull_request.merged == true && + startsWith(github.event.pull_request.title, 'Sync upstream release ') + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + + - name: Extract version and create tag + run: | + # Extract version from PR title "Sync upstream release v1.25.0" + PR_TITLE="${{ github.event.pull_request.title }}" + RELEASE_TAG=$(echo "$PR_TITLE" | sed 's/Sync upstream release //') + echo "Creating tag: $RELEASE_TAG" + + git config --global user.email "actions@github.com" + git config --global user.name "GitHub Actions" + + # Create and push the tag (this triggers cjf-github-release.yml) + git tag "$RELEASE_TAG" + git push origin "$RELEASE_TAG" + + echo "Tag $RELEASE_TAG created and pushed" \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml index 44a149e0c..caf198d04 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2025.21.12-SNAPSHOT + 2026.1.0-SNAPSHOT configurable-java-format diff --git a/pom.xml b/pom.xml index 2406613ea..46a6d56b6 100644 --- a/pom.xml +++ b/pom.xml @@ -21,12 +21,12 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2025.21.12-SNAPSHOT + 2026.1.0-SNAPSHOT Java Format Parent - https://github.com/mrdolch/configurable-java-format - scm:git:https://github.com/mrdolch/configurable-java-format.git + https://github.com/trick77/configurable-google-java-format + scm:git:https://github.com/trick77/configurable-google-java-format.git HEAD From 1bfb34d266c518cb756ee60010286a16e8ef8a8a Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 08:19:33 +0100 Subject: [PATCH 098/107] Update pipeline --- .github/workflows/github-release.yaml | 14 +- .github/workflows/maven-release.yaml | 33 ----- .github/workflows/sync-from-upstream.yaml | 64 +++++++++ .github/workflows/update-from-upstream.yaml | 139 -------------------- 4 files changed, 72 insertions(+), 178 deletions(-) delete mode 100644 .github/workflows/maven-release.yaml create mode 100644 .github/workflows/sync-from-upstream.yaml delete mode 100644 .github/workflows/update-from-upstream.yaml diff --git a/.github/workflows/github-release.yaml b/.github/workflows/github-release.yaml index fef9b9c9e..d2be2b19e 100644 --- a/.github/workflows/github-release.yaml +++ b/.github/workflows/github-release.yaml @@ -24,9 +24,11 @@ jobs: - name: Build with Maven run: mvn verify -DskipTests=true -Dmaven.javadoc.skip=true -B -V - - uses: ncipollo/release-action@v1 - with: - artifacts: "core/target/configurable-java-format-*.*" - bodyFile: "cjf-release.md" - token: ${{ secrets.GITHUB_TOKEN }} - tag: ${{ github.ref_name }} \ No newline at end of file + - name: Create GitHub Release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh release create "${{ github.ref_name }}" \ + --title "${{ github.ref_name }}" \ + --notes-file "cjf-release.md" \ + core/target/configurable-java-format-*.* \ No newline at end of file diff --git a/.github/workflows/maven-release.yaml b/.github/workflows/maven-release.yaml deleted file mode 100644 index 0d98f77a8..000000000 --- a/.github/workflows/maven-release.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: Release on Maven Central -on: - workflow_dispatch: -jobs: - release: - permissions: - contents: write # to manage the POM's version - runs-on: ubuntu-latest - steps: - - name: Check-out - uses: actions/checkout@v5 - - name: Set up JDK - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: '25' - cache: maven - gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} - server-id: central - server-username: SONATYPE_USERNAME - server-password: SONATYPE_TOKEN - - name: Release with Maven - run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - mvn -B -ntp -Dstyle.color=always -Psonatype-oss-release release:prepare - VERSION=`cat release.properties | grep scm.tag= | cut -d'=' -f2` - mvn -B -ntp -Dstyle.color=always -Psonatype-oss-release release:perform - echo "Released ${VERSION}" >> $GITHUB_STEP_SUMMARY - env: - GPG_PASSPHRASE: '' - SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} - SONATYPE_TOKEN: ${{ secrets.SONATYPE_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/sync-from-upstream.yaml b/.github/workflows/sync-from-upstream.yaml new file mode 100644 index 000000000..641f99d0f --- /dev/null +++ b/.github/workflows/sync-from-upstream.yaml @@ -0,0 +1,64 @@ +name: Sync from Upstream Release + +on: + schedule: + - cron: '0 6 * * *' + workflow_dispatch: + pull_request: + types: [closed] + branches: [master] + +permissions: + contents: write + pull-requests: write + +jobs: + sync: + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + + - name: Check and sync upstream release + env: + GH_TOKEN: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + run: | + LATEST=$(gh api repos/google/google-java-format/releases/latest --jq '.tag_name') + + if git tag -l | grep -qx "$LATEST"; then + echo "Already synced $LATEST" + exit 0 + fi + + git config user.email "actions@github.com" + git config user.name "GitHub Actions" + + git remote add upstream https://github.com/google/google-java-format.git + git fetch upstream --tags + git checkout -B sync-upstream "$LATEST" + git push -fu origin sync-upstream + + gh pr create --head sync-upstream --base master \ + --title "Sync upstream release $LATEST" \ + --body "Sync [upstream $LATEST](https://github.com/google/google-java-format/releases/tag/$LATEST)" \ + || gh pr edit --title "Sync upstream release $LATEST" + + tag: + if: github.event.pull_request.merged && startsWith(github.event.pull_request.title, 'Sync upstream release ') + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + + - name: Create tag + run: | + TAG="${{ github.event.pull_request.title }}" + TAG="${TAG#Sync upstream release }" + git config user.email "actions@github.com" + git config user.name "GitHub Actions" + git tag "$TAG" + git push origin "$TAG" \ No newline at end of file diff --git a/.github/workflows/update-from-upstream.yaml b/.github/workflows/update-from-upstream.yaml deleted file mode 100644 index 61667737e..000000000 --- a/.github/workflows/update-from-upstream.yaml +++ /dev/null @@ -1,139 +0,0 @@ -name: Sync from Upstream Release - -# This workflow syncs from upstream google/google-java-format when a new release is published. -# It checks daily for new releases, creates a PR to sync the changes, and after merge, -# creates a tag that triggers the GitHub release workflow. - -on: - schedule: - - cron: '0 6 * * *' # Daily at 6 AM UTC - workflow_dispatch: - pull_request: - types: [closed] - branches: [master] - -env: - UPDATE_BRANCH: update-from-upstream - REMOTE_URL: https://github.com/google/google-java-format.git - -permissions: - contents: write - pull-requests: write - -jobs: - check-and-sync: - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v5 - with: - fetch-depth: 0 - token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} - - - name: Init Git - run: | - git config --global user.email "actions@github.com" - git config --global user.name "GitHub Actions" - - - name: Check for new upstream release - id: check-release - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - echo "Fetching latest release from google/google-java-format..." - LATEST_RELEASE=$(gh api repos/google/google-java-format/releases/latest --jq '.tag_name') - echo "Latest upstream release: $LATEST_RELEASE" - echo "latest_release=$LATEST_RELEASE" >> $GITHUB_OUTPUT - - # Check if we already have this release synced (look for matching tag) - if git tag --list | grep -q "^${LATEST_RELEASE}$"; then - echo "Release $LATEST_RELEASE already synced (tag exists)" - echo "needs_sync=false" >> $GITHUB_OUTPUT - else - echo "New release $LATEST_RELEASE needs to be synced" - echo "needs_sync=true" >> $GITHUB_OUTPUT - fi - - - name: Sync upstream release - if: steps.check-release.outputs.needs_sync == 'true' - id: sync - run: | - RELEASE_TAG="${{ steps.check-release.outputs.latest_release }}" - echo "Syncing upstream release $RELEASE_TAG" - - echo "Adding remote upstream" - git remote add upstream ${{ env.REMOTE_URL }} - - echo "Fetching upstream tags" - git fetch upstream --tags - - echo "Deleting local update branch if present" - git branch -D ${{ env.UPDATE_BRANCH }} || true - - echo "Creating update branch from upstream release tag" - git checkout -b ${{ env.UPDATE_BRANCH }} "$RELEASE_TAG" - - echo "Pushing update branch" - git push -f -u origin ${{ env.UPDATE_BRANCH }} - - echo "Getting current default branch" - git checkout master - current_branch=$(git branch --show-current) - echo "Current branch is $current_branch" - echo "current_branch=$current_branch" >> $GITHUB_OUTPUT - echo "release_tag=$RELEASE_TAG" >> $GITHUB_OUTPUT - - - name: Create or update pull request - if: steps.check-release.outputs.needs_sync == 'true' - env: - GH_TOKEN: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} - run: | - RELEASE_TAG="${{ steps.sync.outputs.release_tag }}" - - # Close any existing sync PRs - existing_prs=$(gh pr list --head "${{ env.UPDATE_BRANCH }}" --json number --jq '.[].number') - for pr in $existing_prs; do - echo "Closing existing PR #$pr" - gh pr close "$pr" || true - done - - # Create new PR - gh pr create \ - --head "${{ env.UPDATE_BRANCH }}" \ - --base "${{ steps.sync.outputs.current_branch }}" \ - --title "Sync upstream release $RELEASE_TAG" \ - --body "Automated PR to sync changes from upstream google-java-format release $RELEASE_TAG. - -After this PR is merged, a tag will be automatically created which triggers a GitHub release. - -**Upstream release:** https://github.com/google/google-java-format/releases/tag/$RELEASE_TAG" - - create-tag-on-merge: - if: | - github.event_name == 'pull_request' && - github.event.pull_request.merged == true && - startsWith(github.event.pull_request.title, 'Sync upstream release ') - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v5 - with: - fetch-depth: 0 - token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} - - - name: Extract version and create tag - run: | - # Extract version from PR title "Sync upstream release v1.25.0" - PR_TITLE="${{ github.event.pull_request.title }}" - RELEASE_TAG=$(echo "$PR_TITLE" | sed 's/Sync upstream release //') - echo "Creating tag: $RELEASE_TAG" - - git config --global user.email "actions@github.com" - git config --global user.name "GitHub Actions" - - # Create and push the tag (this triggers cjf-github-release.yml) - git tag "$RELEASE_TAG" - git push origin "$RELEASE_TAG" - - echo "Tag $RELEASE_TAG created and pushed" \ No newline at end of file From f2a1f44bc89dada69a9dac421d02d42601e2dcce Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 08:36:23 +0100 Subject: [PATCH 099/107] Remove stuff not present in base repo --- .github/workflows/github-release.yaml | 2 +- cjf-release.md | 3 --- jitpack.yml | 5 ----- renovate.json | 6 ------ 4 files changed, 1 insertion(+), 15 deletions(-) delete mode 100644 cjf-release.md delete mode 100644 jitpack.yml delete mode 100644 renovate.json diff --git a/.github/workflows/github-release.yaml b/.github/workflows/github-release.yaml index d2be2b19e..3bbc76b2d 100644 --- a/.github/workflows/github-release.yaml +++ b/.github/workflows/github-release.yaml @@ -30,5 +30,5 @@ jobs: run: | gh release create "${{ github.ref_name }}" \ --title "${{ github.ref_name }}" \ - --notes-file "cjf-release.md" \ + --generate-notes \ core/target/configurable-java-format-*.* \ No newline at end of file diff --git a/cjf-release.md b/cjf-release.md deleted file mode 100644 index 46b4ce4dd..000000000 --- a/cjf-release.md +++ /dev/null @@ -1,3 +0,0 @@ -# configurable java format - -automatic release \ No newline at end of file diff --git a/jitpack.yml b/jitpack.yml deleted file mode 100644 index 00bbed331..000000000 --- a/jitpack.yml +++ /dev/null @@ -1,5 +0,0 @@ -before_install: - - sdk install java 21.0.6-tem - - sdk use java 21.0.6-tem - - sdk install maven 3.9.9 - - sdk use maven 3.9.9 diff --git a/renovate.json b/renovate.json deleted file mode 100644 index 5db72dd6a..000000000 --- a/renovate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "extends": [ - "config:recommended" - ] -} From 3338d7fd6ea4be5d3ea4ca5cc039f751718a3eef Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 08:42:42 +0100 Subject: [PATCH 100/107] ci: release only all-deps jar --- .github/workflows/github-release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-release.yaml b/.github/workflows/github-release.yaml index 3bbc76b2d..9c9be8f2c 100644 --- a/.github/workflows/github-release.yaml +++ b/.github/workflows/github-release.yaml @@ -31,4 +31,4 @@ jobs: gh release create "${{ github.ref_name }}" \ --title "${{ github.ref_name }}" \ --generate-notes \ - core/target/configurable-java-format-*.* \ No newline at end of file + core/target/*-all-deps.jar \ No newline at end of file From f232b9692fb7c1688a57c278af97b3fb296101b4 Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 09:09:50 +0100 Subject: [PATCH 101/107] Release 2026.1.0 --- core/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index caf198d04..26cad2080 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -20,7 +20,7 @@ io.github.mrdolch.formatter configurable-java-format-parent - 2026.1.0-SNAPSHOT + 2026.1.0 configurable-java-format diff --git a/pom.xml b/pom.xml index 46a6d56b6..77fa2746c 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,7 @@ io.github.mrdolch.formatter configurable-java-format-parent pom - 2026.1.0-SNAPSHOT + 2026.1.0 Java Format Parent From d8154b44d3b9c87c0e357a9896e9d27448d553f4 Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 09:10:39 +0100 Subject: [PATCH 102/107] Remove fork-specific README.adoc --- README.adoc | 49 ------------------------------------------------- 1 file changed, 49 deletions(-) delete mode 100644 README.adoc diff --git a/README.adoc b/README.adoc deleted file mode 100644 index 57bcca9ef..000000000 --- a/README.adoc +++ /dev/null @@ -1,49 +0,0 @@ -= Configurable Java Format - -link:https://scan.coverity.com/projects/configurable-java-format[image:https://scan.coverity.com/projects/31383/badge.svg[Coverity Scan Build Status]] - -This is a fork of `google-java-format` with extended configurability. This project is not affiliated with Google. - -== Changes from the Original - -- Removed all plugins – this fork contains only the core formatter. -- Added the `--width` option to specify a custom page width. -- Supports setting options via environment variables. - -== Usage - -[source,sh] ----- -# Help -java -jar configurable-java-format.jar --help - -# Format -java -jar configurable-java-format.jar --width=120 File.java - -# Format in place -java -jar configurable-java-format.jar --width=120 -i File.java ----- - -Alternatively, options can be passed as environment variables: - -[source,sh] ----- -export JAVA_FORMAT_WIDTH=120 -java -jar configurable-java-format.jar File.java ----- - -== IntelliJ Plugin - -link:https://plugins.jetbrains.com/plugin/23827[image:https://img.shields.io/jetbrains/plugin/v/23827.svg[Version]] -link:https://plugins.jetbrains.com/plugin/23827[image:https://img.shields.io/jetbrains/plugin/d/23827.svg[Downloads]] - -The IntelliJ plugin is separate from the formatter and can be found here: - -Plugin page: https://plugins.jetbrains.com/plugin/23827-external-java-formatter - -Source code: https://github.com/MrDolch/external-java-formatter-intellij-plugin - -== License - -This project is based on `google-java-format` and follows the same licensing terms. - From 0c5478dba10012430ffa13642f780e43ea97ffe2 Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 09:39:21 +0100 Subject: [PATCH 103/107] Add README.md from upstream and FORK.md for fork-specific docs Restore the original google-java-format README and convert the previously removed fork-specific README.adoc to markdown. Co-Authored-By: Claude Opus 4.5 --- FORK.md | 46 ++++++++++++ README.md | 219 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 265 insertions(+) create mode 100644 FORK.md create mode 100644 README.md diff --git a/FORK.md b/FORK.md new file mode 100644 index 000000000..3d4c415ae --- /dev/null +++ b/FORK.md @@ -0,0 +1,46 @@ +# Configurable Java Format + +[![Coverity Scan Build Status](https://scan.coverity.com/projects/31383/badge.svg)](https://scan.coverity.com/projects/configurable-java-format) + +This is a fork of `google-java-format` with extended configurability. This project is not affiliated with Google. + +## Changes from the Original + +- Removed all plugins – this fork contains only the core formatter. +- Added the `--width` option to specify a custom page width. +- Supports setting options via environment variables. + +## Usage + +```sh +# Help +java -jar configurable-java-format.jar --help + +# Format +java -jar configurable-java-format.jar --width=120 File.java + +# Format in place +java -jar configurable-java-format.jar --width=120 -i File.java +``` + +Alternatively, options can be passed as environment variables: + +```sh +export JAVA_FORMAT_WIDTH=120 +java -jar configurable-java-format.jar File.java +``` + +## IntelliJ Plugin + +[![Version](https://img.shields.io/jetbrains/plugin/v/23827.svg)](https://plugins.jetbrains.com/plugin/23827) +[![Downloads](https://img.shields.io/jetbrains/plugin/d/23827.svg)](https://plugins.jetbrains.com/plugin/23827) + +The IntelliJ plugin is separate from the formatter and can be found here: + +Plugin page: https://plugins.jetbrains.com/plugin/23827-external-java-formatter + +Source code: https://github.com/MrDolch/external-java-formatter-intellij-plugin + +## License + +This project is based on `google-java-format` and follows the same licensing terms. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 000000000..a5c400122 --- /dev/null +++ b/README.md @@ -0,0 +1,219 @@ +# google-java-format + +`google-java-format` is a program that reformats Java source code to comply with +[Google Java Style][]. + +[Google Java Style]: https://google.github.io/styleguide/javaguide.html + +## Using the formatter + +### From the command-line + +[Download the formatter](https://github.com/google/google-java-format/releases) +and run it with: + +``` +java -jar /path/to/google-java-format-${GJF_VERSION?}-all-deps.jar [files...] +``` + +Note that it uses the `jdk.compiler` module to parse the Java source code. The +`java` binary version used must therefore be from a JDK (not JRE) with a version +equal to or newer than the Java language version of the files being formatted. +The minimum Java version can be found in `core/pom.xml` (currently Java 17). An +alternative is to use the available GraalVM based native binaries instead. + +The formatter can act on whole files, on limited lines (`--lines`), on specific +offsets (`--offset`), passing through to standard-out (default) or altered +in-place (`--replace`). + +Option `--help` will print full usage details; including built-in documentation +about other flags, such as `--aosp`, `--fix-imports-only`, +`--skip-sorting-imports`, `--skip-removing-unused-import`, +`--skip-reflowing-long-strings`, `--skip-javadoc-formatting`, or the `--dry-run` +and `--set-exit-if-changed`. + +Using `@` reads options and filenames from a file, instead of +arguments. + +To reformat changed lines in a specific patch, use +[`google-java-format-diff.py`](https://github.com/google/google-java-format/blob/master/scripts/google-java-format-diff.py). + +***Note:*** *There is no configurability as to the formatter's algorithm for +formatting. This is a deliberate design decision to unify our code formatting on +a single format.* + +### IntelliJ, Android Studio, and other JetBrains IDEs + +A +[google-java-format IntelliJ plugin](https://plugins.jetbrains.com/plugin/8527) +is available from the plugin repository. To install it, go to your IDE's +settings and select the `Plugins` category. Click the `Marketplace` tab, search +for the `google-java-format` plugin, and click the `Install` button. + +The plugin will be disabled by default. To enable, +[open the Project settings](https://www.jetbrains.com/help/idea/configure-project-settings.html), +then click "google-java-format Settings" and check the "Enable +google-java-format" checkbox. + +To enable it by default in new projects, +[open the default settings for new projects](https://www.jetbrains.com/help/idea/configure-project-settings.html#new-default-settings) +and configure it under "Other Settings/google-java-format Settings". + +When enabled, it will replace the normal `Reformat Code` and `Optimize Imports` +actions. + +#### IntelliJ JRE Config + +The google-java-format plugin uses some internal classes that aren't available +without extra configuration. To use the plugin, you need to +[add some options to your IDE's Java runtime](https://www.jetbrains.com/help/idea/tuning-the-ide.html#procedure-jvm-options). +To do that, go to `Help→Edit Custom VM Options...` and paste in these lines: + +``` +--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +``` + +Once you've done that, restart the IDE. + +### Eclipse + +The latest version of the `google-java-format` Eclipse plugin can be downloaded +from the [releases page](https://github.com/google/google-java-format/releases). +Drop it into the Eclipse +[drop-ins folder](http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fp2_dropins_format.html) +to activate the plugin. + +The plugin adds two formatter implementations: + +* `google-java-format`: using 2 spaces indent +* `aosp-java-format`: using 4 spaces indent + +These that can be selected in "Window" > "Preferences" > "Java" > "Code Style" > +"Formatter" > "Formatter Implementation". + +#### Eclipse JRE Config + +The plugin uses some internal classes that aren't available without extra +configuration. To use the plugin, you will need to edit the +[`eclipse.ini`](https://wiki.eclipse.org/Eclipse.ini) file. + +Open the `eclipse.ini` file in any editor and paste in these lines towards the +end (but anywhere after `-vmargs` will do): + +``` +--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +``` + +Once you've done that, restart the IDE. + +### Third-party integrations + +* Visual Studio Code + * [google-java-format-for-vs-code](https://marketplace.visualstudio.com/items?itemName=JoseVSeb.google-java-format-for-vs-code) +* Gradle plugins + * [spotless](https://github.com/diffplug/spotless/tree/main/plugin-gradle#google-java-format) + * [sherter/google-java-format-gradle-plugin](https://github.com/sherter/google-java-format-gradle-plugin) +* Apache Maven plugins + * [spotless](https://github.com/diffplug/spotless/tree/main/plugin-maven#google-java-format) + * [spotify/fmt-maven-plugin](https://github.com/spotify/fmt-maven-plugin) + * [talios/googleformatter-maven-plugin](https://github.com/talios/googleformatter-maven-plugin) + * [Cosium/maven-git-code-format](https://github.com/Cosium/maven-git-code-format): + A maven plugin that automatically deploys google-java-format as a + pre-commit git hook. +* SBT plugins + * [sbt/sbt-java-formatter](https://github.com/sbt/sbt-java-formatter) +* [Github Actions](https://github.com/features/actions) + * [googlejavaformat-action](https://github.com/axel-op/googlejavaformat-action): + Automatically format your Java files when you push on github + +### as a library + +The formatter can be used in software which generates java to output more +legible java code. Just include the library in your maven/gradle/etc. +configuration. + +`google-java-format` uses internal javac APIs for parsing Java source. The +following JVM flags are required when running on JDK 16 and newer, due to +[JEP 396: Strongly Encapsulate JDK Internals by Default](https://openjdk.java.net/jeps/396): + +``` +--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +``` + +#### Maven + +```xml + + com.google.googlejavaformat + google-java-format + ${google-java-format.version} + +``` + +#### Gradle + +```groovy +dependencies { + implementation 'com.google.googlejavaformat:google-java-format:$googleJavaFormatVersion' +} +``` + +You can then use the formatter through the `formatSource` methods. E.g. + +```java +String formattedSource = new Formatter().formatSource(sourceString); +``` + +or + +```java +CharSource source = ... +CharSink output = ... +new Formatter().formatSource(source, output); +``` + +Your starting point should be the instance methods of +`com.google.googlejavaformat.java.Formatter`. + +## Building from source + +``` +mvn install +``` + +## Contributing + +Please see [the contributors guide](CONTRIBUTING.md) for details. + +## License + +```text +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. +``` From 48a3af618bfc79557c503a90a8e4f49f1ccffe88 Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 09:41:10 +0100 Subject: [PATCH 104/107] Remove plugin reference from FORK.md, credit MrDolch Co-Authored-By: Claude Opus 4.5 --- FORK.md | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/FORK.md b/FORK.md index 3d4c415ae..f3967696b 100644 --- a/FORK.md +++ b/FORK.md @@ -30,16 +30,9 @@ export JAVA_FORMAT_WIDTH=120 java -jar configurable-java-format.jar File.java ``` -## IntelliJ Plugin +## Acknowledgments -[![Version](https://img.shields.io/jetbrains/plugin/v/23827.svg)](https://plugins.jetbrains.com/plugin/23827) -[![Downloads](https://img.shields.io/jetbrains/plugin/d/23827.svg)](https://plugins.jetbrains.com/plugin/23827) - -The IntelliJ plugin is separate from the formatter and can be found here: - -Plugin page: https://plugins.jetbrains.com/plugin/23827-external-java-formatter - -Source code: https://github.com/MrDolch/external-java-formatter-intellij-plugin +Thanks to [MrDolch](https://github.com/MrDolch) for his contributions. ## License From d14669f4a3945db84342d10c57ec5a2bb08f0f92 Mon Sep 17 00:00:00 2001 From: trick77 Date: Sat, 17 Jan 2026 10:39:11 +0100 Subject: [PATCH 105/107] Add dependabot.yaml --- .github/dependabot.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .github/dependabot.yaml diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml new file mode 100644 index 000000000..a851c94c5 --- /dev/null +++ b/.github/dependabot.yaml @@ -0,0 +1,11 @@ +version: 2 +updates: + - package-ecosystem: "maven" + directory: "/" + schedule: + interval: "weekly" + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" \ No newline at end of file From fc0ef4d8ed41de4341f5a8b7d8c07161cf05f043 Mon Sep 17 00:00:00 2001 From: trick77 Date: Mon, 26 Jan 2026 06:58:53 +0100 Subject: [PATCH 106/107] chore: configure dependabot weekly schedule and dependency groups --- .github/dependabot.yaml | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml index a851c94c5..1338cd77d 100644 --- a/.github/dependabot.yaml +++ b/.github/dependabot.yaml @@ -4,8 +4,31 @@ updates: directory: "/" schedule: interval: "weekly" + day: "sunday" + time: "07:00" + groups: + google-annotations: + patterns: + - "com.google.auto.value:*" + - "com.google.auto.service:*" + - "com.google.errorprone:*" + test-dependencies: + patterns: + - "junit:*" + - "com.google.truth:*" + - "com.google.guava:guava-testlib" + maven-plugins: + patterns: + - "org.apache.maven.plugins:*" + - "org.apache.felix:maven-bundle-plugin" + - "org.codehaus.mojo:*" + - "org.graalvm.buildtools:*" + - "org.sonatype.central:*" + - "com.google.code.maven-replacer-plugin:*" - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "weekly" \ No newline at end of file + interval: "weekly" + day: "sunday" + time: "07:00" \ No newline at end of file From 760217a2494a29ce3b46608397018578b61c4b1e Mon Sep 17 00:00:00 2001 From: trick77 Date: Mon, 26 Jan 2026 08:25:01 +0100 Subject: [PATCH 107/107] Rename PAT --- .github/workflows/sync-from-upstream.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/sync-from-upstream.yaml b/.github/workflows/sync-from-upstream.yaml index 641f99d0f..85383cf2b 100644 --- a/.github/workflows/sync-from-upstream.yaml +++ b/.github/workflows/sync-from-upstream.yaml @@ -20,11 +20,11 @@ jobs: - uses: actions/checkout@v5 with: fetch-depth: 0 - token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + token: ${{ secrets.UPSTREAM_SYNC_PAT }} - name: Check and sync upstream release env: - GH_TOKEN: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + GH_TOKEN: ${{ secrets.UPSTREAM_SYNC_PAT }} run: | LATEST=$(gh api repos/google/google-java-format/releases/latest --jq '.tag_name') @@ -52,7 +52,7 @@ jobs: steps: - uses: actions/checkout@v5 with: - token: ${{ secrets.UPDATE_FROM_TEMPLATE_PAT }} + token: ${{ secrets.UPSTREAM_SYNC_PAT }} - name: Create tag run: |