-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathcompound_tool.dart
321 lines (276 loc) · 9.38 KB
/
compound_tool.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import 'dart:async';
import 'dart:math';
import 'package:args/args.dart';
import 'package:dart_dev/dart_dev.dart';
import 'package:logging/logging.dart';
import '../dart_dev_tool.dart';
import '../utils/rest_args_with_separator.dart';
final _log = Logger('CompoundTool');
typedef ArgMapper = ArgResults Function(ArgParser parser, ArgResults results);
/// Return a parsed [ArgResults] that only includes the option args (flags,
/// single options, and multi options) supported by [parser].
///
/// Positional args and any option args not supported by [parser] will be
/// excluded.
///
/// This [ArgMapper] is the default for tools added to a [CompoundTool].
ArgResults takeOptionArgs(ArgParser parser, ArgResults results) =>
parser.parse(optionArgsOnly(results, allowedOptions: parser.options.keys));
/// Return a parsed [ArgResults] that includes the option args (flags, single
/// options, and multi options) supported by [parser] as well as any positional
/// args.
///
/// Option args not supported by [parser] will be excluded.
///
/// Use this with a [CompoundTool] to indicate which tool should receive the
/// positional args given to the compound target.
///
/// // tool/dart_dev/config.dart
/// import 'package:dart_dev/dart_dev.dart';
///
/// final config = {
/// 'test': CompoundTool()
/// // This tool will not receive any positional args
/// ..addTool(startServerTool)
/// // This tool will receive the test-specific option args as well as
/// // any positional args given to `ddev test`.
/// ..addTool(TestTool(), argMapper: takeAllArgs)
/// };
ArgResults takeAllArgs(ArgParser parser, ArgResults results) => parser.parse([
...optionArgsOnly(results, allowedOptions: parser.options.keys),
...restArgsWithSeparator(results),
]);
class CompoundTool extends DevTool with CompoundToolMixin {}
mixin CompoundToolMixin on DevTool {
@override
ArgParser get argParser => _argParser;
final _argParser = CompoundArgParser();
final _specs = <DevToolSpec>[];
@override
String get description => _description ??= _specs
.map((s) => s.tool.description)
.firstWhere((desc) => desc != null, orElse: () => null);
set description(String value) => _description = value;
String _description;
void addTool(DevTool tool, {bool alwaysRun, ArgMapper argMapper}) {
final runWhen = alwaysRun ?? false ? RunWhen.always : RunWhen.passing;
_specs.add(DevToolSpec(runWhen, tool, argMapper: argMapper));
if (tool.argParser != null) {
_argParser.addParser(tool.argParser);
}
}
@override
FutureOr<int> run([DevToolExecutionContext context]) async {
context ??= DevToolExecutionContext();
int code = 0;
for (var i = 0; i < _specs.length; i++) {
if (!shouldRunTool(_specs[i].when, code)) continue;
final newCode =
await _specs[i].tool.run(contextForTool(context, _specs[i]));
_log.fine('Step ${i + 1}/${_specs.length} done (code: $newCode)\n');
if (code == 0) {
code = newCode;
}
}
return code;
}
}
List<String> optionArgsOnly(ArgResults results,
{Iterable<String> allowedOptions}) {
final args = <String>[];
for (final option in results.options) {
if (!results.wasParsed(option)) continue;
if (allowedOptions != null && !allowedOptions.contains(option)) continue;
final value = results[option];
if (value is bool) {
args.add('--${value ? '' : 'no-'}$option');
} else if (value is Iterable) {
args.addAll([for (final v in value as List<String>) '--$option=$v']);
} else {
args.add('--$option=$value');
}
}
return args;
}
DevToolExecutionContext contextForTool(
DevToolExecutionContext baseContext, DevToolSpec spec) {
if (baseContext.argResults == null) return baseContext;
final parser = spec.tool.argParser ?? ArgParser();
final argMapper = spec.argMapper ?? takeOptionArgs;
return baseContext.update(
argResults: argMapper(parser, baseContext.argResults));
}
bool shouldRunTool(RunWhen runWhen, int currentExitCode) {
switch (runWhen) {
case RunWhen.always:
return true;
case RunWhen.passing:
return currentExitCode == 0;
default:
throw FallThroughError();
}
}
class DevToolSpec {
final ArgMapper argMapper;
final DevTool tool;
final RunWhen when;
DevToolSpec(this.when, this.tool, {this.argMapper});
}
enum RunWhen { always, passing }
class CompoundArgParser implements ArgParser {
final _compoundParser = ArgParser();
final _subParsers = <ArgParser>[];
void addParser(ArgParser argParser) {
_subParsers.add(argParser);
argParser.commands.forEach(_compoundParser.addCommand);
for (final option in argParser.options.values) {
if (option.isFlag) {
_compoundParser.addFlag(option.name,
abbr: option.abbr,
help: option.help,
defaultsTo: option.defaultsTo,
negatable: option.negatable,
callback: option.callback,
hide: option.hide);
} else if (option.isMultiple) {
_compoundParser.addMultiOption(option.name,
abbr: option.abbr,
help: option.help,
valueHelp: option.valueHelp,
allowed: option.allowed,
allowedHelp: option.allowedHelp,
defaultsTo: option.defaultsTo,
callback: option.callback,
splitCommas: option.splitCommas,
hide: option.hide);
} else if (option.isSingle) {
_compoundParser.addOption(option.name,
abbr: option.abbr,
help: option.help,
valueHelp: option.valueHelp,
allowed: option.allowed,
allowedHelp: option.allowedHelp,
defaultsTo: option.defaultsTo,
callback: option.callback,
hide: option.hide);
}
}
}
// ---------------------------------------------------------------------------
// ArgParser overrides.
// ---------------------------------------------------------------------------
@override
bool get allowTrailingOptions =>
_subParsers.every((ap) => ap.allowTrailingOptions);
@override
bool get allowsAnything => false;
@override
Map<String, ArgParser> get commands => _compoundParser.commands;
@override
Option findByAbbreviation(String abbr) =>
_compoundParser.findByAbbreviation(abbr);
@override
getDefault(String option) => _compoundParser.getDefault(option);
@deprecated
@override
String getUsage() => usage;
@override
Map<String, Option> get options => _compoundParser.options;
@override
ArgResults parse(Iterable<String> args) => _compoundParser.parse(args);
@override
String get usage {
if (_subParsers.isEmpty) return '';
final buffer = StringBuffer()
..writeln()
..writeln('This command is composed of multiple parts, each of which has '
'its own options.');
for (final parser in _subParsers) {
buffer
..writeln()
..writeln('-' * max(usageLineLength ?? 80, 80))
..writeln()
..writeln(parser.usage);
}
return buffer.toString();
}
@override
int get usageLineLength {
if (_subParsers.isEmpty) return null;
int max;
for (final parser in _subParsers) {
if (max != null &&
parser.usageLineLength != null &&
parser.usageLineLength > max) {
max = parser.usageLineLength;
}
}
return max;
}
@override
ArgParser addCommand(String name, [ArgParser parser]) =>
_compoundParser.addCommand(name, parser);
@override
void addFlag(String name,
{String abbr,
String help,
bool defaultsTo = false,
bool negatable = true,
void Function(bool value) callback,
bool hide = false}) =>
_compoundParser.addFlag(name,
abbr: abbr,
help: help,
defaultsTo: defaultsTo,
negatable: negatable,
callback: callback,
hide: hide);
@override
void addMultiOption(String name,
{String abbr,
String help,
String valueHelp,
Iterable<String> allowed,
Map<String, String> allowedHelp,
Iterable<String> defaultsTo,
void Function(List<String> values) callback,
bool splitCommas = true,
bool hide = false}) =>
_compoundParser.addMultiOption(name,
abbr: abbr,
help: help,
valueHelp: valueHelp,
allowed: allowed,
allowedHelp: allowedHelp,
defaultsTo: defaultsTo,
callback: callback,
splitCommas: splitCommas,
hide: hide);
@override
void addOption(String name,
{String abbr,
String help,
String valueHelp,
Iterable<String> allowed,
Map<String, String> allowedHelp,
String defaultsTo,
Function callback,
bool allowMultiple = false,
bool splitCommas,
bool hide = false}) =>
_compoundParser.addOption(name,
abbr: abbr,
help: help,
valueHelp: valueHelp,
allowed: allowed,
allowedHelp: allowedHelp,
defaultsTo: defaultsTo,
callback: callback,
// ignore: deprecated_member_use
allowMultiple: allowMultiple,
// ignore: deprecated_member_use
splitCommas: splitCommas,
hide: hide);
@override
void addSeparator(String text) => _compoundParser.addSeparator(text);
}