Skip to content

Commit 19e6383

Browse files
maxException
1 parent 50349c7 commit 19e6383

File tree

3 files changed

+30
-29
lines changed

3 files changed

+30
-29
lines changed

tools/add_imports/bin/add_imports.dart

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@ import 'dart:io';
22

33
import 'package:add_imports/src/args.dart';
44
import 'package:add_imports/src/config.dart';
5-
import 'package:add_imports/src/function_or_null.dart';
5+
import 'package:add_imports/src/util.dart';
66
import 'package:collection/collection.dart';
77

88
void main(List<String> arguments) {
99
try {
1010
final (sourceFile, config) = init(arguments);
1111

12-
final sourceString = sourceFile.readAsStringSync.orNull();
13-
if (sourceString == null) {
14-
throw 'Error while reading source from "${sourceFile.path}"';
15-
}
12+
final sourceString = mapException(
13+
sourceFile.readAsStringSync,
14+
(_) => 'Error while reading source from "${sourceFile.path}"',
15+
);
1616

1717
final classes = RegExp(r'new self.([A-Za-z]+)\(')
1818
.allMatches(sourceString)
@@ -42,27 +42,27 @@ void main(List<String> arguments) {
4242
sourceString,
4343
].join('\n');
4444

45-
try {
46-
sourceFile.writeAsStringSync(newSource);
47-
} catch (_) {
48-
throw 'Error while writing new source to "${sourceFile.path}"';
49-
}
45+
mapException(
46+
() => sourceFile.writeAsStringSync(newSource),
47+
(_) => 'Error while writing new source to "${sourceFile.path}"',
48+
);
5049
} on String catch (e) {
5150
print(e);
5251
}
5352
}
5453

5554
(File, Config) init(List<String> arguments) {
56-
final args = (() => Args.parse(arguments)).orNull();
57-
if (args == null) throw Args.usage;
55+
final Args(
56+
:filename,
57+
:configpath,
58+
) = mapException(() => Args.parse(arguments), (_) => Args.usage);
5859

59-
final config = (() => Config.fromYaml(
60-
File(args.configpath).readAsStringSync(),
61-
)).orNull();
62-
63-
if (config == null) {
64-
throw 'Error while reading config from "${args.configpath}"';
65-
}
60+
final config = mapException(
61+
() => Config.fromYaml(
62+
File(configpath).readAsStringSync(),
63+
),
64+
(_) => 'Error while reading config from "$configpath"',
65+
);
6666

67-
return (File(args.filename), config);
67+
return (File(filename), config);
6868
}

tools/add_imports/lib/src/function_or_null.dart

Lines changed: 0 additions & 9 deletions
This file was deleted.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
T mapException<T, U extends Object, K extends Object>(
2+
T Function() f,
3+
K Function(U) m,
4+
) {
5+
try {
6+
return f();
7+
} on U catch (e) {
8+
throw m(e);
9+
}
10+
}

0 commit comments

Comments
 (0)