dart-lang / dart_style

An opinionated formatter/linter for Dart code
https://pub.dev/packages/dart_style
BSD 3-Clause "New" or "Revised" License
648 stars 121 forks source link

dartfmt and dartanalyzer are conflicting when using linter rule always_put_control_body_on_new_line #808

Closed apaatsio closed 5 years ago

apaatsio commented 5 years ago

dartfmt formats code in a way that doesn't agree with the linter rule always_put_control_body_on_new_line. This creates quite an annoying problem where I cannot use dartfmt if I want to use the rule always_put_control_body_on_new_line, and I cannot use the said linter rule if I want to use dartfmt.

Here's an example. Linter finds no issues before formatting but finds one issue afterward.

Log

$ cat analysis_options.yaml
linter:
  rules:
    - always_put_control_body_on_new_line

$ cat test.dart
void main() {
  if(true)
    return;
}

$ dartanalyzer test.dart 
Analyzing test.dart...
No issues found!

$ dartfmt -w test.dart 
Formatted test.dart

$ dartanalyzer test.dart 
Analyzing test.dart...
  lint • Separate the control structure expression from its statement at test.dart:2:13 • always_put_control_body_on_new_line
1 lint found.

$ cat test.dart
void main() {
  if (true) return;
}

Versions

apaatsio commented 5 years ago

Somewhat related discussion: flutter/flutter#31448

munificent commented 5 years ago

dartfmt is opinionated by design. It does it's best to format your code to one canonical style so that all code formatted using dartfmt is consistent.

The linter is not opinionated. Most lint rules do fit within dartfmt and "Effective Dart"'s guidelines, but some do not. If you choose to enable a lint rule that conflicts with dartfmt, then using dartfmt will produce lint errors.

The easiest fix in this case is to always put braces on your ifs. The lint is happy with braced ifs and dartfmt will format them the way you expect. It is only on unbraced ifs where you run into conflict.