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 @@ -45,7 +45,7 @@ public String call() throws FormatterException {
new Formatter(options).formatSource(input, characterRanges(input).asRanges());
formatted = fixImports(formatted);
if (parameters.reflowLongStrings()) {
formatted = StringWrapper.wrap(options.maxLineLength(), formatted);
formatted = StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, formatted);
}
return formatted;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@
@Immutable
public final class Formatter {

public static final int MAX_LINE_LENGTH = 100;

static final Range<Integer> EMPTY_RANGE = Range.closedOpen(-1, -1);

private final JavaFormatterOptions options;
Expand Down Expand Up @@ -156,8 +158,7 @@ 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(), options.maxLineLength(), new Doc.State(+0, 0));
doc.computeBreaks(javaOutput.getCommentsHelper(), MAX_LINE_LENGTH, new Doc.State(+0, 0));
doc.write(javaOutput);
javaOutput.flush();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,10 @@
/** {@code JavaCommentsHelper} extends {@link CommentsHelper} to rewrite Java comments. */
public final class JavaCommentsHelper implements CommentsHelper {

private final JavaFormatterOptions options;
private final String lineSeparator;

public JavaCommentsHelper(String lineSeparator, JavaFormatterOptions options) {
this.lineSeparator = lineSeparator;
this.options = options;
}

@Override
Expand All @@ -44,7 +42,7 @@ public String rewrite(Tok tok, int maxWidth, int column0) {
}
String text = tok.getOriginalText();
if (tok.isJavadocComment()) {
text = JavadocFormatter.formatJavadoc(text, column0, options);
text = JavadocFormatter.formatJavadoc(text, column0);
}
List<String> lines = new ArrayList<>();
Iterator<String> it = Newlines.lineIterator(text);
Expand Down Expand Up @@ -92,7 +90,7 @@ private String preserveIndentation(List<String> lines, int column0) {

// Wraps and re-indents line comments.
private String indentLineComments(List<String> lines, int column0) {
lines = wrapLineComments(lines, column0, options);
lines = wrapLineComments(lines, column0);
StringBuilder builder = new StringBuilder();
builder.append(lines.get(0).trim());
String indentString = Strings.repeat(" ", column0);
Expand All @@ -107,8 +105,7 @@ private String indentLineComments(List<String> lines, int column0) {
private static final Pattern LINE_COMMENT_MISSING_SPACE_PREFIX =
Pattern.compile("^(//+)(?!noinspection|\\$NON-NLS-\\d+\\$)[^\\s/]");

private List<String> wrapLineComments(
List<String> lines, int column0, JavaFormatterOptions options) {
private List<String> wrapLineComments(List<String> lines, int column0) {
List<String> result = new ArrayList<>();
for (String line : lines) {
// Add missing leading spaces to line comments: `//foo` -> `// foo`.
Expand All @@ -122,8 +119,8 @@ private List<String> wrapLineComments(
result.add(line);
continue;
}
while (line.length() + column0 > options.maxLineLength()) {
int idx = options.maxLineLength() - column0;
while (line.length() + column0 > Formatter.MAX_LINE_LENGTH) {
int idx = Formatter.MAX_LINE_LENGTH - column0;
// only break on whitespace characters, and ignore the leading `// `
while (idx >= 2 && !CharMatcher.whitespace().matches(line.charAt(idx))) {
idx--;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package com.google.googlejavaformat.java;

import com.google.errorprone.annotations.Immutable;
import com.google.googlejavaformat.java.javadoc.JavadocOptions;

/**
* Options for a google-java-format invocation.
Expand All @@ -28,9 +27,7 @@
* preferences, and in fact it would work directly against our primary goals.
*/
@Immutable
public class JavaFormatterOptions implements JavadocOptions {

static final int DEFAULT_MAX_LINE_LENGTH = 100;
public class JavaFormatterOptions {

public enum Style {

Expand All @@ -57,12 +54,6 @@ private JavaFormatterOptions(Style style) {
this.style = style;
}

/** Returns the maximum formatted width */
@Override
public int maxLineLength() {
return DEFAULT_MAX_LINE_LENGTH;
}

/** Returns the multiplier for the unit of indent */
public int indentationMultiplier() {
return style.indentationMultiplier();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1564,7 +1564,8 @@ private static List<Long> handleStream(List<ExpressionTree> parts) {
return false;
}
Name name = getMethodName((MethodInvocationTree) p);
return Stream.of("stream", "toBuilder").anyMatch(name::contentEquals);
return Stream.of("stream", "parallelStream", "toBuilder")
.anyMatch(name::contentEquals);
})
.collect(toList());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ private static RangeMap<Integer, String> buildReplacements(
endPosition = Math.max(CharMatcher.isNot(' ').indexIn(contents, endPosition), endPosition);
String sep = Newlines.guessLineSeparator(contents);
if (endPosition + sep.length() < contents.length()
&& contents.subSequence(endPosition, endPosition + sep.length()).equals(sep)) {
&& contents.subSequence(endPosition, endPosition + sep.length()).toString().equals(sep)) {
endPosition += sep.length();
}
replacements.put(Range.closedOpen(importTree.getStartPosition(), endPosition), "");
Expand Down Expand Up @@ -304,9 +304,7 @@ private static boolean isUnused(
JCImport importTree,
String simpleName) {
String qualifier =
importTree.getQualifiedIdentifier() instanceof JCFieldAccess
? ((JCFieldAccess) importTree.getQualifiedIdentifier()).getExpression().toString()
: null;
((JCFieldAccess) importTree.getQualifiedIdentifier()).getExpression().toString();
if (qualifier.equals("java.lang")) {
return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
public final class StringWrapper {
/** Reflows long string literals in the given Java source code. */
public static String wrap(String input) throws FormatterException {
return StringWrapper.wrap(JavaFormatterOptions.defaultOptions().maxLineLength(), input);
return StringWrapper.wrap(Formatter.MAX_LINE_LENGTH, input);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,26 @@
* single blank line if it's empty.
*/
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, JavadocOptions options) {
public static String formatJavadoc(String input, int blockIndent) {
ImmutableList<Token> tokens;
try {
tokens = lex(input);
} catch (LexException e) {
return input;
}
String result = render(tokens, blockIndent, options);
return makeSingleLineIfPossible(blockIndent, result, options);
String result = render(tokens, blockIndent);
return makeSingleLineIfPossible(blockIndent, result);
}

private static String render(List<Token> input, int blockIndent, JavadocOptions options) {
JavadocWriter output = new JavadocWriter(blockIndent, options);
private static String render(List<Token> input, int blockIndent) {
JavadocWriter output = new JavadocWriter(blockIndent);
for (Token token : input) {
switch (token.getType()) {
case BEGIN_JAVADOC:
Expand Down Expand Up @@ -162,9 +165,8 @@ 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, JavadocOptions options) {
int oneLinerContentLength = options.maxLineLength() - "/** */".length() - blockIndent;
private static String makeSingleLineIfPossible(int blockIndent, String input) {
int oneLinerContentLength = MAX_LINE_LENGTH - "/** */".length() - blockIndent;
Matcher matcher = ONE_CONTENT_LINE_PATTERN.matcher(input);
if (matcher.matches() && matcher.group(1).isEmpty()) {
return "/** */";
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
*/
final class JavadocWriter {
private final int blockIndent;
private final JavadocOptions options;
private final StringBuilder output = new StringBuilder();
/**
* Whether we are inside an {@code <li>} element, excluding the case in which the {@code <li>}
Expand All @@ -60,9 +59,8 @@ final class JavadocWriter {
private int indentForMoeEndStripComment;
private boolean wroteAnythingSignificant;

JavadocWriter(int blockIndent, JavadocOptions options) {
JavadocWriter(int blockIndent) {
this.blockIndent = blockIndent;
this.options = checkNotNull(options);
}

/**
Expand Down Expand Up @@ -375,7 +373,7 @@ private void writeNewline(AutoIndent autoIndent) {
appendSpaces(blockIndent + 1);
output.append("*");
appendSpaces(1);
remainingOnLine = options.maxLineLength() - blockIndent - 3;
remainingOnLine = JavadocFormatter.MAX_LINE_LENGTH - blockIndent - 3;
if (autoIndent == AUTO_INDENT) {
appendSpaces(innerIndent());
remainingOnLine -= innerIndent();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package com.google.googlejavaformat.java;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.Joiner;
Expand Down Expand Up @@ -99,7 +100,7 @@ public void preserveOriginalFile() throws Exception {
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.err, UTF_8)), true),
System.in);
int errorCode = main.format("-replace", path.toAbsolutePath().toString());
assertThat(errorCode).named("Error Code").isEqualTo(0);
assertWithMessage("Error Code").that(errorCode).isEqualTo(0);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class I365 {
{
return foo____________
.bar__________()
.baz____________()
.parallelStream()
.map(Baz::getId)
.collect(toList());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class I365 {
{
return foo____________.bar__________().baz____________().parallelStream()
.map(Baz::getId)
.collect(toList());
}
}
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
<java.version>1.8</java.version>
<guava.version>27.0.1-jre</guava.version>
<javac.version>9+181-r4173-1</javac.version>
<truth.version>0.40</truth.version>
<truth.version>0.44</truth.version>
<jsr305.version>3.0.2</jsr305.version>
</properties>

Expand Down
10 changes: 8 additions & 2 deletions scripts/google-java-format-diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ def main():
parser.add_argument('--skip-sorting-imports', action='store_true',
help='do not fix the import order')
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.
Expand Down Expand Up @@ -91,15 +94,18 @@ def main():
['-lines', str(start_line) + ':' + str(end_line)])

if args.binary:
binary = args.binary
base_command = [args.binary]
elif args.google_java_format_jar:
base_command = ['java', '-jar', args.google_java_format_jar]
else:
binary = find_executable('google-java-format') or '/usr/bin/google-java-format'
base_command = [binary]

# Reformat files containing changes in place.
for filename, lines in lines_by_file.iteritems():
if args.i and args.verbose:
print 'Formatting', filename
command = [binary]
command = base_command[:]
if args.i:
command.append('-i')
if args.aosp:
Expand Down