Skip to content

Commit fb93b7c

Browse files
authored
Refactor to use enhanced enums for Output and Show. (#1116)
Also some other minor clean-up while I was at it: - Remove unneeded library tags. - Fix some raw typed collections. - Use list element where it makes sense. - Remove unneeded .whereType<Rule>() calls. (They were to filter out null, but the rule field is non-nullable now.)
1 parent a9115cd commit fb93b7c

21 files changed

+132
-222
lines changed

benchmark/benchmark.dart

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
library dart_style.benchmark.benchmark;
6-
75
import 'dart:io';
86

97
import 'package:dart_style/dart_style.dart';

lib/src/cli/format_command.dart

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -87,20 +87,16 @@ class FormatCommand extends Command<int> {
8787
usageException('Cannot print a summary with JSON output.');
8888
}
8989

90-
int pageWidth;
91-
try {
92-
pageWidth = int.parse(argResults['line-length']);
93-
} on FormatException catch (_) {
94-
usageException('--line-length must be an integer, was '
95-
'"${argResults['line-length']}".');
96-
}
90+
var pageWidth = int.tryParse(argResults['line-length']) ??
91+
usageException('--line-length must be an integer, was '
92+
'"${argResults['line-length']}".');
9793

98-
int indent;
99-
try {
100-
indent = int.parse(argResults['indent']);
101-
if (indent < 0 || indent.toInt() != indent) throw FormatException();
102-
} on FormatException catch (_) {
103-
usageException('--indent must be a non-negative integer, was '
94+
var indent = int.tryParse(argResults['indent']) ??
95+
usageException('--indent must be an integer, was '
96+
'"${argResults['indent']}".');
97+
98+
if (indent < 0) {
99+
usageException('--indent must be non-negative, was '
104100
'"${argResults['indent']}".');
105101
}
106102

lib/src/cli/formatter_options.dart

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
library dart_style.src.formatter_options;
6-
75
import 'dart:io';
86

97
import '../source_code.dart';

lib/src/cli/output.dart

Lines changed: 33 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,26 @@ import 'dart:io';
77
import '../source_code.dart';
88

99
/// Where formatted code results should go.
10-
class Output {
10+
enum Output {
1111
/// Overwrite files on disc.
12-
static const Output write = _WriteOutput();
12+
write,
1313

1414
/// Print the code to the terminal as human-friendly text.
15-
static const Output show = _ShowOutput();
15+
show,
1616

1717
/// Print the code to the terminal as JSON.
18-
static const Output json = _JsonOutput();
18+
json,
1919

2020
/// Do nothing. (Used when the user just wants the list of files that would
2121
/// be changed.)
22-
static const Output none = Output._();
23-
24-
const Output._();
22+
none;
2523

2624
/// Write the file to disc.
2725
///
2826
/// If stdin is being formatted, then [file] is `null`.
29-
bool writeFile(File? file, String displayPath, SourceCode result) => false;
30-
31-
/// Print the file to the terminal in some way.
32-
void showFile(String path, SourceCode result) {}
33-
}
34-
35-
class _WriteOutput extends Output {
36-
const _WriteOutput() : super._();
37-
38-
@override
3927
bool writeFile(File? file, String displayPath, SourceCode result) {
28+
if (this != Output.write) return false;
29+
4030
try {
4131
file!.writeAsStringSync(result.text);
4232
} on FileSystemException catch (err) {
@@ -46,35 +36,35 @@ class _WriteOutput extends Output {
4636

4737
return true;
4838
}
49-
}
50-
51-
class _ShowOutput extends Output {
52-
const _ShowOutput() : super._();
5339

54-
@override
40+
/// Print the file to the terminal in some way.
5541
void showFile(String path, SourceCode result) {
56-
// Don't add an extra newline.
57-
stdout.write(result.text);
58-
}
59-
}
42+
switch (this) {
43+
case Output.show:
44+
// Don't add an extra newline.
45+
stdout.write(result.text);
46+
break;
6047

61-
class _JsonOutput extends Output {
62-
const _JsonOutput() : super._();
48+
case Output.json:
49+
// TODO(rnystrom): Put an empty selection in here to remain compatible with
50+
// the old formatter. Since there's no way to pass a selection on the
51+
// command line, this will never be used, which is why it's hard-coded to
52+
// -1, -1. If we add support for passing in a selection, put the real
53+
// result here.
54+
print(jsonEncode({
55+
'path': path,
56+
'source': result.text,
57+
'selection': {
58+
'offset': result.selectionStart ?? -1,
59+
'length': result.selectionLength ?? -1
60+
}
61+
}));
62+
break;
6363

64-
@override
65-
void showFile(String path, SourceCode result) {
66-
// TODO(rnystrom): Put an empty selection in here to remain compatible with
67-
// the old formatter. Since there's no way to pass a selection on the
68-
// command line, this will never be used, which is why it's hard-coded to
69-
// -1, -1. If we add support for passing in a selection, put the real
70-
// result here.
71-
print(jsonEncode({
72-
'path': path,
73-
'source': result.text,
74-
'selection': {
75-
'offset': result.selectionStart ?? -1,
76-
'length': result.selectionLength ?? -1
77-
}
78-
}));
64+
case Output.write:
65+
case Output.none:
66+
// Do nothing.
67+
break;
68+
}
7969
}
8070
}

lib/src/cli/show.dart

Lines changed: 56 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -4,49 +4,90 @@
44
import 'package:path/path.dart' as p;
55

66
/// Which file paths should be printed.
7-
abstract class Show {
7+
enum Show {
88
/// No files.
9-
static const Show none = _NoneShow();
9+
none,
1010

1111
/// All traversed files.
12-
static const Show all = _AllShow();
12+
all,
1313

1414
/// Only files whose formatting changed.
15-
static const Show changed = _ChangedShow();
15+
changed,
1616

1717
/// The legacy dartfmt output style when not overwriting files.
18-
static const Show legacy = _LegacyShow();
18+
legacy,
1919

2020
/// The legacy dartfmt output style when overwriting files.
21-
static const Show overwrite = _OverwriteShow();
21+
overwrite,
2222

2323
/// The legacy dartfmt output style in "--dry-run".
24-
static const Show dryRun = _DryRunShow();
25-
26-
const Show._();
24+
dryRun;
2725

2826
/// The display path to show for [file] which is in [directory].
2927
///
3028
/// In the old CLI, this does not include [directory], since the directory
3129
/// name is printed separately. The new CLI only prints file paths, so this
3230
/// includes the root directory to disambiguate which directory the file is
3331
/// in.
34-
String displayPath(String directory, String file) => p.normalize(file);
32+
String displayPath(String directory, String file) {
33+
switch (this) {
34+
case Show.legacy:
35+
case Show.overwrite:
36+
case Show.dryRun:
37+
return p.relative(file, from: directory);
38+
39+
default:
40+
return p.normalize(file);
41+
}
42+
}
3543

3644
/// Describes a file that was processed.
3745
///
3846
/// Returns whether or not this file should be displayed.
39-
bool file(String path, {required bool changed, required bool overwritten}) =>
40-
true;
47+
bool file(String path, {required bool changed, required bool overwritten}) {
48+
switch (this) {
49+
case Show.all:
50+
case Show.overwrite:
51+
if (changed) {
52+
_showFileChange(path, overwritten: overwritten);
53+
} else {
54+
print('Unchanged $path');
55+
}
56+
return true;
57+
58+
case Show.changed:
59+
if (changed) _showFileChange(path, overwritten: overwritten);
60+
return changed;
61+
62+
case Show.dryRun:
63+
if (changed) print(path);
64+
return true;
65+
66+
default:
67+
return true;
68+
}
69+
}
4170

4271
/// Describes the directory whose contents are about to be processed.
43-
void directory(String path) {}
72+
void directory(String path) {
73+
if (this == Show.legacy || this == Show.overwrite) {
74+
print('Formatting directory $directory:');
75+
}
76+
}
4477

4578
/// Describes the symlink at [path] that wasn't followed.
46-
void skippedLink(String path) {}
79+
void skippedLink(String path) {
80+
if (this == Show.legacy || this == Show.overwrite) {
81+
print('Skipping link $path');
82+
}
83+
}
4784

4885
/// Describes the hidden [path] that wasn't processed.
49-
void hiddenPath(String path) {}
86+
void hiddenPath(String path) {
87+
if (this == Show.legacy || this == Show.overwrite) {
88+
print('Skipping hidden path $path');
89+
}
90+
}
5091

5192
void _showFileChange(String path, {required bool overwritten}) {
5293
if (overwritten) {
@@ -56,77 +97,3 @@ abstract class Show {
5697
}
5798
}
5899
}
59-
60-
mixin _ShowFileMixin on Show {
61-
@override
62-
bool file(String path, {required bool changed, required bool overwritten}) {
63-
if (changed) {
64-
_showFileChange(path, overwritten: overwritten);
65-
} else {
66-
print('Unchanged $path');
67-
}
68-
69-
return true;
70-
}
71-
}
72-
73-
mixin _LegacyMixin on Show {
74-
@override
75-
String displayPath(String directory, String file) =>
76-
p.relative(file, from: directory);
77-
78-
@override
79-
void directory(String directory) {
80-
print('Formatting directory $directory:');
81-
}
82-
83-
@override
84-
void skippedLink(String path) {
85-
print('Skipping link $path');
86-
}
87-
88-
@override
89-
void hiddenPath(String path) {
90-
print('Skipping hidden path $path');
91-
}
92-
}
93-
94-
class _NoneShow extends Show {
95-
const _NoneShow() : super._();
96-
}
97-
98-
class _AllShow extends Show with _ShowFileMixin {
99-
const _AllShow() : super._();
100-
}
101-
102-
class _ChangedShow extends Show {
103-
const _ChangedShow() : super._();
104-
105-
@override
106-
bool file(String path, {required bool changed, required bool overwritten}) {
107-
if (changed) _showFileChange(path, overwritten: overwritten);
108-
return changed;
109-
}
110-
}
111-
112-
class _LegacyShow extends Show with _LegacyMixin {
113-
const _LegacyShow() : super._();
114-
}
115-
116-
class _OverwriteShow extends Show with _ShowFileMixin, _LegacyMixin {
117-
const _OverwriteShow() : super._();
118-
}
119-
120-
class _DryRunShow extends Show {
121-
const _DryRunShow() : super._();
122-
123-
@override
124-
String displayPath(String directory, String file) =>
125-
p.relative(file, from: directory);
126-
127-
@override
128-
bool file(String path, {required bool changed, required bool overwritten}) {
129-
if (changed) print(path);
130-
return true;
131-
}
132-
}

lib/src/debug.dart

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import 'dart:math' as math;
77

88
import 'chunk.dart';
99
import 'line_splitting/rule_set.dart';
10-
import 'rule/rule.dart';
1110

1211
/// Set this to `true` to turn on diagnostic output while building chunks.
1312
bool traceChunkBuilder = false;
@@ -189,12 +188,12 @@ void dumpChunks(int start, List<Chunk> chunks) {
189188

190189
/// Shows all of the constraints between the rules used by [chunks].
191190
void dumpConstraints(List<Chunk> chunks) {
192-
var rules = chunks.map((chunk) => chunk.rule).whereType<Rule>().toSet();
191+
var rules = chunks.map((chunk) => chunk.rule).toSet();
193192

194193
for (var rule in rules) {
195-
var constrainedValues = [];
194+
var constrainedValues = <String>[];
196195
for (var value = 0; value < rule.numValues; value++) {
197-
var constraints = [];
196+
var constraints = <String>[];
198197
for (var other in rules) {
199198
if (rule == other) continue;
200199

lib/src/exceptions.dart

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
library dart_style.src.formatter_exception;
6-
75
import 'package:analyzer/error/error.dart';
86
import 'package:source_span/source_span.dart';
97

lib/src/fast_hash.dart

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
library dart_style.src.fast_hash;
6-
75
/// A mixin for classes with identity equality that need to be frequently
86
/// hashed.
97
abstract class FastHash {

0 commit comments

Comments
 (0)