Java Code Examples for com.google.googlejavaformat.Newlines#getLineEnding()

The following examples show how to use com.google.googlejavaformat.Newlines#getLineEnding() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImportOrderer.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
private String reorderImports() throws FormatterException {
  int firstImportStart;
  Optional<Integer> 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);

  ImportsAndIndex imports = scanImports(firstImportStart);
  int afterLastImport = imports.index;

  // Make sure there are no more imports before the next class (etc) definition.
  Optional<Integer> 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);
  result.append(prefix);
  if (!prefix.isEmpty() && Newlines.getLineEnding(prefix) == null) {
    result.append(lineSeparator).append(lineSeparator);
  }
  result.append(reorderedImportsString(imports.imports));

  List<String> 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();
    tail.add(text.substring(tailStart));
  }
  if (tail.stream().anyMatch(s -> !s.isEmpty())) {
    result.append(lineSeparator);
    tail.forEach(result::append);
  }

  return result.toString();
}
 
Example 2
Source File: FormatterIntegrationTest.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
public FormatterIntegrationTest(String name, String input, String expected) {
  this.name = name;
  this.input = input;
  this.expected = expected;
  this.separator = Newlines.getLineEnding(expected);
}