Skip to content

Insert missing braces around single-statement if/else/for/while/do bodies (--cleanup) #147

Open

Description

@abashev

Upstream: google/google-java-format#1492
Kind: feature | Priority: medium

google-java-format#1492 (merged 2026-10-22, a Google-internal change exported by copybara) adds a --cleanup[=true|false] flag and a matching JavaFormatterOptions.Builder.cleanup(boolean) option, on by default. It gates a new AST cleanup pass (CleanupScanner) that wraps unbraced bodies of if, else, for, do and while in braces, keeps trailing comments on the opening-brace line, and handles nested if/else chains. The pass runs inside the cleanups pipeline introduced by google-java-format#1488.

Why it matters: it is the first non-whitespace rewrite google-java-format applies by default, so users of our fork who also use that tool may expect the same result. It changes formatted output for existing code bases, which is why upstream made it switchable. A follow-up in google-java-format#1491 adds redundant-semicolon removal to the same pass. We have no brace insertion today (no scanner of this kind in our sources).

Before (how it is formatted today, our formatter keeps the unbraced body):

class T {
  void f(boolean a, boolean b) {
    if (a)
      if (b) doA();
      else doB();
    while (a) doA();
  }
}

After (with the change, from upstream test expectations):

class T {
  void f(boolean a, boolean b) {
    if (a) {
      if (b) {
        doA();
      } else {
        doB();
      }
    }
    while (a) {
      doA();
    }
  }
}

(Indentation shown at two spaces for brevity; ours would use the project's four-space layout.)

Affected files in our repo:

  • open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java (pipeline entry points)
  • open-java-format/src/main/java/com/palantir/javaformat/java/CommandLineOptions.java and CommandLineOptionsParser.java (new flag)
  • open-java-format/src/main/java/com/palantir/javaformat/java/JavaInputAstVisitor.java (statement visiting, for context)
  • open-java-format/src/test/resources/com/palantir/javaformat/java/testdata (goldens would need an opt-out)

Suggested action: investigate. Decide whether we want any non-whitespace rewrite, and if so make it opt-in (default off) so existing output does not change. Depends on the cleanups-pipeline decision in the existing ticket for google-java-format#1488. Otherwise ignore-with-reason ("formatter should not rewrite code").


Filed from an upstream-watch ticket after manual review.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions