Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* @param lines Line ranges to format.
* @param offsets Character offsets for partial formatting, paired with {@code lengths}.
* @param lengths Partial formatting region lengths, paired with {@code offsets}.
* @param aosp Use AOSP style instead of Google Style (4-space indentation).
* @param style Code style configuration.
* @param version Print the version.
* @param help Print usage information.
* @param stdin Format input from stdin.
Expand All @@ -47,7 +47,7 @@ record CommandLineOptions(
ImmutableRangeSet<Integer> lines,
ImmutableList<Integer> offsets,
ImmutableList<Integer> lengths,
boolean aosp,
JavaFormatterOptions.Style style,
boolean version,
boolean help,
boolean stdin,
Expand All @@ -61,19 +61,27 @@ record CommandLineOptions(
boolean formatJavadoc,
boolean reorderModifiers) {

boolean aosp() {
return style().isAosp();
}

int maxLineLength() {
return style().maxLineLength();
}

/** Returns true if partial formatting was selected. */
boolean isSelection() {
return !lines().isEmpty() || !offsets().isEmpty() || !lengths().isEmpty();
}

static Builder builder() {
return new AutoBuilder_CommandLineOptions_Builder()
.style(JavaFormatterOptions.Style.GOOGLE)
.sortImports(true)
.removeUnusedImports(true)
.reflowLongStrings(true)
.formatJavadoc(true)
.reorderModifiers(true)
.aosp(false)
.version(false)
.help(false)
.stdin(false)
Expand Down Expand Up @@ -108,7 +116,7 @@ default Builder addLength(Integer length) {
return this;
}

Builder aosp(boolean aosp);
Builder style(JavaFormatterOptions.Style style);

Builder version(boolean version);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ final class CommandLineOptionsParser {
/** Parses {@link CommandLineOptions}. */
static CommandLineOptions parse(Iterable<String> options) {
CommandLineOptions.Builder optionsBuilder = CommandLineOptions.builder();
JavaFormatterOptions.Style.Builder styleBuilder = JavaFormatterOptions.Style.GOOGLE.toBuilder();
List<String> expandedOptions = new ArrayList<>();
expandParamsFiles(options, expandedOptions);
Iterator<String> it = expandedOptions.iterator();
Expand Down Expand Up @@ -71,8 +72,17 @@ static CommandLineOptions parse(Iterable<String> options) {
parseRangeSet(linesBuilder, getValue(flag, it, value));
case "--offset", "-offset" -> optionsBuilder.addOffset(parseInteger(it, flag, value));
case "--length", "-length" -> optionsBuilder.addLength(parseInteger(it, flag, value));
case "--google-style", "-google-style" -> optionsBuilder.aosp(false);
case "--aosp", "-aosp", "-a" -> optionsBuilder.aosp(true);
case "--google-style", "-google-style" -> styleBuilder.google();
case "--aosp", "-aosp", "-a" -> styleBuilder.aosp();
case "--style" -> {
String style = getValue(flag, it, value);
switch (style) {
case "google" -> styleBuilder.google();
case "aosp" -> styleBuilder.aosp();
default ->
throw new IllegalArgumentException(String.format("invalid style value: %s", style));
}
}
case "--version", "-version", "-v" -> optionsBuilder.version(true);
case "--help", "-help", "-h" -> optionsBuilder.help(true);
case "--fix-imports-only" -> optionsBuilder.fixImportsOnly(true);
Expand All @@ -81,6 +91,14 @@ static CommandLineOptions parse(Iterable<String> options) {
case "--skip-reflowing-long-strings" -> optionsBuilder.reflowLongStrings(false);
case "--skip-javadoc-formatting" -> optionsBuilder.formatJavadoc(false);
case "--skip-reordering-modifiers" -> optionsBuilder.reorderModifiers(false);
case "--max-line-length" -> {
int length = parseInteger(it, flag, value);
if (length <= 0) {
throw new IllegalArgumentException(
String.format("invalid max-line-length: %d (must be positive)", length));
}
styleBuilder.maxLineLength(length);
}
case "-" -> optionsBuilder.stdin(true);
case "-n", "--dry-run" -> optionsBuilder.dryRun(true);
case "--set-exit-if-changed" -> optionsBuilder.setExitIfChanged(true);
Expand All @@ -89,6 +107,7 @@ static CommandLineOptions parse(Iterable<String> options) {
default -> throw new IllegalArgumentException("unexpected flag: " + flag);
}
}
optionsBuilder.style(styleBuilder.build());
optionsBuilder.lines(ImmutableRangeSet.copyOf(linesBuilder));
return optionsBuilder.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public Result call() {
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.maxLineLength(), formatted, formatter);
}
return Result.create(path, input, formatted, /* exception= */ null);
} catch (FormatterException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

package com.google.googlejavaformat.java;


import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
Expand Down Expand Up @@ -90,6 +89,10 @@ public Formatter(JavaFormatterOptions options) {
this.options = options;
}

JavaFormatterOptions options() {
return options;
}

/**
* Construct a {@code Formatter} given a Java compilation unit. Parses the code; builds a {@link
* JavaInput} and the corresponding {@link JavaOutput}.
Expand Down Expand Up @@ -124,7 +127,7 @@ static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatt
Newlines.guessLineSeparator(javaInput.getText()),
options,
markdownJavadocPositions.build());
doc.computeBreaks(commentsHelper, MAX_LINE_LENGTH, new Doc.State(+0, 0));
doc.computeBreaks(commentsHelper, options.maxLineLength(), new Doc.State(+0, 0));
doc.write(javaOutput);
javaOutput.flush();
}
Expand Down Expand Up @@ -221,7 +224,8 @@ public ImmutableList<Replacement> getFormatReplacements(
new JavaOutput(
lineSeparator,
javaInput,
new JavaCommentsHelper(lineSeparator, options, ImmutableSet.of()));
new JavaCommentsHelper(lineSeparator, options, ImmutableSet.of()),
options::indentString);
try {
format(javaInput, javaOutput, options);
} catch (FormattingError e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
* @throws FormatterException if the input could not be parsed.
*/
@Deprecated
public static String reorderImports(String text) throws FormatterException {

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on macos-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on macos-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on macos-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on macos-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 21 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 21 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 21 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 21 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / JDK 25 on ubuntu-latest

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.

Check warning on line 61 in core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java

View workflow job for this annotation

GitHub Actions / Publish snapshot

[InlineMeSuggester] This deprecated API looks inlineable. If you'd like the body of the API to be automatically inlined to its callers, please annotate it with @InlineMe. NOTE: the suggested fix makes the method final if it was not already.
return reorderImports(text, Style.GOOGLE);
}

Expand Down Expand Up @@ -177,14 +177,16 @@
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.importOrder()) {
case GOOGLE -> {
this.importComparator = GOOGLE_IMPORT_COMPARATOR;
this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineGoogle;
}
case AOSP -> {
this.importComparator = AOSP_IMPORT_COMPARATOR;
this.shouldInsertBlankLineFn = ImportOrderer::shouldInsertBlankLineAosp;
}
default -> throw new IllegalArgumentException("Unsupported code style: " + style);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ public String rewrite(Tok tok, int maxWidth, int column0) {
if (tok.isJavadocComment() && options.formatJavadoc()) {
if (text.startsWith("///")) {
if (markdownJavadocPositions.contains(tok.getPosition())) {
return JavadocFormatter.formatJavadoc(text, column0);
return JavadocFormatter.formatJavadoc(text, column0, options.maxLineLength());
}
} else {
text = JavadocFormatter.formatJavadoc(text, column0);
text = JavadocFormatter.formatJavadoc(text, column0, options.maxLineLength());
}
}
List<String> lines = new ArrayList<>();
Expand Down Expand Up @@ -95,8 +95,9 @@ private String preserveIndentation(List<String> lines, int column0) {
builder.append(lines.get(0));

// output all trailing lines with plausible indentation
String indentString = options.indentString(column0);
for (int i = 1; i < lines.size(); ++i) {
builder.append(lineSeparator).repeat(" ", column0);
builder.append(lineSeparator).append(indentString);
// check that startCol is valid index, e.g. for blank lines
if (lines.get(i).length() >= startCol) {
builder.append(lines.get(i).substring(startCol));
Expand All @@ -112,7 +113,7 @@ private String indentLineComments(Tok tok, List<String> lines, int column0) {
lines = wrapLineComments(tok, lines, column0);
StringBuilder builder = new StringBuilder();
builder.append(lines.get(0).trim());
String indentString = " ".repeat(column0);
String indentString = options.indentString(column0);
for (int i = 1; i < lines.size(); ++i) {
builder.append(lineSeparator).append(indentString).append(lines.get(i).trim());
}
Expand Down Expand Up @@ -146,8 +147,8 @@ private List<String> wrapLineComments(Tok tok, List<String> 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.maxLineLength()) {
int idx = options.maxLineLength() - column0;
// only break on whitespace characters, and ignore the leading `// `
while (idx >= 2 && !CharMatcher.whitespace().matches(line.charAt(idx))) {
idx--;
Expand All @@ -169,7 +170,7 @@ private String indentJavadoc(List<String> lines, int column0) {
StringBuilder builder = new StringBuilder();
builder.append(lines.get(0).trim());
int indent = column0 + 1;
String indentString = " ".repeat(indent);
String indentString = options.indentString(indent);
for (int i = 1; i < lines.size(); ++i) {
builder.append(lineSeparator).append(indentString);
String line = lines.get(i).trim();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import static java.util.Objects.requireNonNull;

import com.google.auto.value.AutoBuilder;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;

/**
Expand All @@ -37,29 +38,143 @@ public record JavaFormatterOptions(boolean formatJavadoc, boolean reorderModifie
requireNonNull(style, "style");
}

public enum Style {
/** Code style configuration for layout and imports. */
@Immutable
public record Style(
Comment on lines -40 to +43

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a breaking change. See diffplug/spotless#3126

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

int indentationMultiplier, int maxLineLength, boolean useTabs, ImportOrder importOrder) {
public Style {
if (maxLineLength <= 0) {
throw new IllegalArgumentException(
String.format("maxLineLength must be positive, was: %d", maxLineLength));
}
requireNonNull(importOrder, "importOrder");
}

/** The default Google Java Style configuration. */
GOOGLE(1),
public static final Style GOOGLE = builder().google().build();

/** The AOSP-compliant configuration. */
AOSP(2);
public static final Style AOSP = builder().aosp().build();

/**
* Returns the visual column width of a tab stop.
*
* <p>This matches the standard block indentation width for the style: 2 columns for Google
* Style and 4 columns for AOSP.
*/
public int tabWidth() {
return 2 * indentationMultiplier();
}

/** Returns the indentation string for the given visual column width. */
public String indentString(int indent) {
if (!useTabs()) {
return " ".repeat(indent);
}
int tabWidth = tabWidth();
return "\t".repeat(indent / tabWidth) + " ".repeat(indent % tabWidth);
}

/** Returns the visual column width of the given character sequence. */
public int visualLength(CharSequence input) {
return visualLength(input, 0, input.length());
}

private final int indentationMultiplier;
/** Returns the visual column width of the given subsequence. */
public int visualLength(CharSequence input, int start, int end) {
if (!useTabs()) {
return end - start;
}
int tabWidth = tabWidth();
int column = 0;
for (int i = start; i < end; i++) {
if (input.charAt(i) == '\t') {
column += tabWidth - (column % tabWidth);
} else {
column++;
}
}
return column;
}

Style(int indentationMultiplier) {
this.indentationMultiplier = indentationMultiplier;
public boolean isAosp() {
return importOrder() == ImportOrder.AOSP;
}

int indentationMultiplier() {
return indentationMultiplier;
public static Builder builder() {
return new AutoBuilder_JavaFormatterOptions_Style_Builder()
.maxLineLength(100)
.useTabs(false)
.google();
}

public Builder toBuilder() {
return new AutoBuilder_JavaFormatterOptions_Style_Builder()
.indentationMultiplier(indentationMultiplier())
.maxLineLength(maxLineLength())
.useTabs(useTabs())
.importOrder(importOrder());
}

/** A builder for {@link Style}. */
@AutoBuilder
public abstract static class Builder {
public abstract Builder indentationMultiplier(int indentationMultiplier);

public abstract Builder maxLineLength(int maxLineLength);

public abstract Builder useTabs(boolean useTabs);

public abstract Builder importOrder(ImportOrder importOrder);

@CanIgnoreReturnValue
public Builder aosp() {
return indentationMultiplier(2).importOrder(ImportOrder.AOSP);
}

@CanIgnoreReturnValue
public Builder google() {
return indentationMultiplier(1).importOrder(ImportOrder.GOOGLE);
}

public abstract Style build();
}
}

/** The import order to use. */
public enum ImportOrder {
GOOGLE,
AOSP,
}

/** Returns the multiplier for the unit of indent. */
public int indentationMultiplier() {
return style().indentationMultiplier();
}

public int maxLineLength() {
return style().maxLineLength();
}

public boolean useTabs() {
return style().useTabs();
}

/** Returns the indentation string for the given visual column width. */
public String indentString(int indent) {
return style().indentString(indent);
}

/** Returns the visual column width of the given character sequence. */
public int visualLength(CharSequence input) {
return style().visualLength(input);
}

/** Returns the visual column width of the given subsequence. */
public int visualLength(CharSequence input, int start, int end) {
return style().visualLength(input, start, end);
}

/** Returns the default formatting options. */
public static JavaFormatterOptions defaultOptions() {
return builder().build();
Expand Down
Loading
Loading