-
Notifications
You must be signed in to change notification settings - Fork 205
/
options.dart
525 lines (475 loc) · 19.6 KB
/
options.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
import 'package:build_config/build_config.dart';
import 'package:build_daemon/constants.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:path/path.dart' as p;
import 'package:watcher/watcher.dart';
import '../generate/directory_watcher_factory.dart';
const buildFilterOption = 'build-filter';
const configOption = 'config';
const defineOption = 'define';
const deleteFilesByDefaultOption = 'delete-conflicting-outputs';
const enableExperimentOption = 'enable-experiment';
const failOnSevereOption = 'fail-on-severe';
const hostnameOption = 'hostname';
const liveReloadOption = 'live-reload';
const logPerformanceOption = 'log-performance';
const logRequestsOption = 'log-requests';
const lowResourcesModeOption = 'low-resources-mode';
const notFoundDefaultsToOption = 'not-found-defaults-to';
const outputOption = 'output';
const releaseOption = 'release';
const trackPerformanceOption = 'track-performance';
const skipBuildScriptCheckOption = 'skip-build-script-check';
const symlinkOption = 'symlink';
const usePollingWatcherOption = 'use-polling-watcher';
const verboseOption = 'verbose';
enum BuildUpdatesOption { none, liveReload }
final _defaultWebDirs = const ['web', 'test', 'example', 'benchmark'];
/// Base options that are shared among all commands.
class SharedOptions {
/// A set of explicit filters for files to build.
///
/// If provided no other files will be built that don't match these filters
/// unless they are an input to something matching a filter.
final Set<BuildFilter> buildFilters;
/// By default, the user will be prompted to delete any files which already
/// exist but were not generated by this specific build script.
///
/// This option can be set to `true` to skip this prompt.
final bool deleteFilesByDefault;
final bool enableLowResourcesMode;
/// Read `build.$configKey.yaml` instead of `build.yaml`.
final String? configKey;
/// A set of targets to build with their corresponding output locations.
final Set<BuildDirectory> buildDirs;
/// Whether or not the output directories should contain only symlinks,
/// or full copies of all files.
final bool outputSymlinksOnly;
/// Enables performance tracking and the `/$perf` page.
final bool trackPerformance;
/// A directory to log performance information to.
String? logPerformanceDir;
/// Check digest of imports to the build script to invalidate the build.
final bool skipBuildScriptCheck;
final bool verbose;
// Global config overrides by builder.
//
// Keys are the builder keys, such as my_package|my_builder, and values
// represent config objects. All keys in the config will override the parsed
// config for that key.
final Map<String, Map<String, dynamic>> builderConfigOverrides;
final bool isReleaseBuild;
final List<String> enableExperiments;
SharedOptions._({
required this.buildFilters,
required this.deleteFilesByDefault,
required this.enableLowResourcesMode,
required this.configKey,
required this.buildDirs,
required this.outputSymlinksOnly,
required this.trackPerformance,
required this.skipBuildScriptCheck,
required this.verbose,
required this.builderConfigOverrides,
required this.isReleaseBuild,
required this.logPerformanceDir,
required this.enableExperiments,
});
SharedOptions.fromParsedArgs(ArgResults argResults,
Iterable<String> positionalArgs, String rootPackage, Command command)
: this._(
buildFilters: _parseBuildFilters(argResults, rootPackage),
deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool,
enableLowResourcesMode: argResults[lowResourcesModeOption] as bool,
configKey: argResults[configOption] as String?,
buildDirs: {
..._parseBuildDirs(argResults),
..._parsePositionalBuildDirs(positionalArgs, command),
},
outputSymlinksOnly: argResults[symlinkOption] as bool,
trackPerformance: argResults[trackPerformanceOption] as bool,
skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool,
verbose: argResults[verboseOption] as bool,
builderConfigOverrides: _parseBuilderConfigOverrides(
argResults[defineOption], rootPackage),
isReleaseBuild: argResults[releaseOption] as bool,
logPerformanceDir: argResults[logPerformanceOption] as String?,
enableExperiments: argResults[enableExperimentOption] as List<String>,
);
}
/// Options specific to the `daemon` command.
class DaemonOptions extends WatchOptions {
BuildMode buildMode;
bool logRequests;
DaemonOptions._({
required Set<BuildFilter> buildFilters,
required this.buildMode,
required this.logRequests,
required bool deleteFilesByDefault,
required bool enableLowResourcesMode,
required String? configKey,
required Set<BuildDirectory> buildDirs,
required bool outputSymlinksOnly,
required bool trackPerformance,
required bool skipBuildScriptCheck,
required bool verbose,
required Map<String, Map<String, dynamic>> builderConfigOverrides,
required bool isReleaseBuild,
required String? logPerformanceDir,
required bool usePollingWatcher,
required List<String> enableExperiments,
}) : super._(
buildFilters: buildFilters,
deleteFilesByDefault: deleteFilesByDefault,
enableLowResourcesMode: enableLowResourcesMode,
configKey: configKey,
buildDirs: buildDirs,
outputSymlinksOnly: outputSymlinksOnly,
trackPerformance: trackPerformance,
skipBuildScriptCheck: skipBuildScriptCheck,
verbose: verbose,
builderConfigOverrides: builderConfigOverrides,
isReleaseBuild: isReleaseBuild,
logPerformanceDir: logPerformanceDir,
usePollingWatcher: usePollingWatcher,
enableExperiments: enableExperiments,
);
factory DaemonOptions.fromParsedArgs(ArgResults argResults,
Iterable<String> positionalArgs, String rootPackage, Command command) {
var buildDirs = {
..._parseBuildDirs(argResults),
..._parsePositionalBuildDirs(positionalArgs, command),
};
var buildFilters = _parseBuildFilters(argResults, rootPackage);
var buildModeValue = argResults[buildModeFlag] as String;
BuildMode buildMode;
if (buildModeValue == BuildMode.Auto.toString()) {
buildMode = BuildMode.Auto;
} else if (buildModeValue == BuildMode.Manual.toString()) {
buildMode = BuildMode.Manual;
} else {
throw UsageException(
'Unexpected value for $buildModeFlag: $buildModeValue',
command.usage);
}
return DaemonOptions._(
buildFilters: buildFilters,
buildMode: buildMode,
logRequests: argResults[logRequestsOption] as bool,
deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool,
enableLowResourcesMode: argResults[lowResourcesModeOption] as bool,
configKey: argResults[configOption] as String?,
buildDirs: buildDirs,
outputSymlinksOnly: argResults[symlinkOption] as bool,
trackPerformance: argResults[trackPerformanceOption] as bool,
skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool,
verbose: argResults[verboseOption] as bool,
builderConfigOverrides:
_parseBuilderConfigOverrides(argResults[defineOption], rootPackage),
isReleaseBuild: argResults[releaseOption] as bool,
logPerformanceDir: argResults[logPerformanceOption] as String?,
usePollingWatcher: argResults[usePollingWatcherOption] as bool,
enableExperiments: argResults[enableExperimentOption] as List<String>,
);
}
}
class WatchOptions extends SharedOptions {
final bool usePollingWatcher;
DirectoryWatcher Function(String) get directoryWatcherFactory =>
usePollingWatcher
? pollingDirectoryWatcherFactory
: defaultDirectoryWatcherFactory;
WatchOptions._({
required this.usePollingWatcher,
required Set<BuildFilter> buildFilters,
required bool deleteFilesByDefault,
required bool enableLowResourcesMode,
required String? configKey,
required Set<BuildDirectory> buildDirs,
required bool outputSymlinksOnly,
required bool trackPerformance,
required bool skipBuildScriptCheck,
required bool verbose,
required Map<String, Map<String, dynamic>> builderConfigOverrides,
required bool isReleaseBuild,
required String? logPerformanceDir,
required List<String> enableExperiments,
}) : super._(
buildFilters: buildFilters,
deleteFilesByDefault: deleteFilesByDefault,
enableLowResourcesMode: enableLowResourcesMode,
configKey: configKey,
buildDirs: buildDirs,
outputSymlinksOnly: outputSymlinksOnly,
trackPerformance: trackPerformance,
skipBuildScriptCheck: skipBuildScriptCheck,
verbose: verbose,
builderConfigOverrides: builderConfigOverrides,
isReleaseBuild: isReleaseBuild,
logPerformanceDir: logPerformanceDir,
enableExperiments: enableExperiments,
);
WatchOptions.fromParsedArgs(ArgResults argResults,
Iterable<String> positionalArgs, String rootPackage, Command command)
: this._(
buildFilters: _parseBuildFilters(argResults, rootPackage),
deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool,
enableLowResourcesMode: argResults[lowResourcesModeOption] as bool,
configKey: argResults[configOption] as String?,
buildDirs: {
..._parseBuildDirs(argResults),
..._parsePositionalBuildDirs(positionalArgs, command),
},
outputSymlinksOnly: argResults[symlinkOption] as bool,
trackPerformance: argResults[trackPerformanceOption] as bool,
skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool,
verbose: argResults[verboseOption] as bool,
builderConfigOverrides: _parseBuilderConfigOverrides(
argResults[defineOption], rootPackage),
isReleaseBuild: argResults[releaseOption] as bool,
logPerformanceDir: argResults[logPerformanceOption] as String?,
usePollingWatcher: argResults[usePollingWatcherOption] as bool,
enableExperiments: argResults[enableExperimentOption] as List<String>,
);
}
/// Options specific to the `serve` command.
class ServeOptions extends WatchOptions {
final String hostName;
final BuildUpdatesOption buildUpdates;
final bool logRequests;
final List<ServeTarget> serveTargets;
// An [AssetId] path to redirect when the file is not found by
// the web server
final String? notFoundDefaultsTo;
ServeOptions._(
{required this.hostName,
required this.buildUpdates,
required this.logRequests,
required this.serveTargets,
required Set<BuildFilter> buildFilters,
required bool deleteFilesByDefault,
required bool enableLowResourcesMode,
required String? configKey,
required Set<BuildDirectory> buildDirs,
required bool outputSymlinksOnly,
required bool trackPerformance,
required bool skipBuildScriptCheck,
required bool verbose,
required Map<String, Map<String, dynamic>> builderConfigOverrides,
required bool isReleaseBuild,
required String? logPerformanceDir,
required bool usePollingWatcher,
required List<String> enableExperiments,
this.notFoundDefaultsTo})
: super._(
buildFilters: buildFilters,
deleteFilesByDefault: deleteFilesByDefault,
enableLowResourcesMode: enableLowResourcesMode,
configKey: configKey,
buildDirs: buildDirs,
outputSymlinksOnly: outputSymlinksOnly,
trackPerformance: trackPerformance,
skipBuildScriptCheck: skipBuildScriptCheck,
verbose: verbose,
builderConfigOverrides: builderConfigOverrides,
isReleaseBuild: isReleaseBuild,
logPerformanceDir: logPerformanceDir,
usePollingWatcher: usePollingWatcher,
enableExperiments: enableExperiments);
factory ServeOptions.fromParsedArgs(ArgResults argResults,
Iterable<String> positionalArgs, String rootPackage, Command command) {
var serveTargets = <ServeTarget>[];
var nextDefaultPort = 8080;
for (var arg in positionalArgs) {
var parts = arg.split(':');
if (parts.length > 2) {
throw UsageException(
'Invalid format for positional argument to serve `$arg`'
', expected <directory>:<port>.',
command.usage);
}
var port = parts.length == 2 ? int.tryParse(parts[1]) : nextDefaultPort++;
if (port == null) {
throw UsageException(
'Unable to parse port number in `$arg`', command.usage);
}
var path = parts.first;
var pathParts = p.split(path);
if (pathParts.length > 1 || path == '.') {
throw UsageException(
'Only top level directories such as `web` or `test` are allowed as '
'positional args, but got `$path`',
command.usage);
}
serveTargets.add(ServeTarget(path, port));
}
if (serveTargets.isEmpty) {
for (var dir in _defaultWebDirs) {
if (Directory(dir).existsSync()) {
serveTargets.add(ServeTarget(dir, nextDefaultPort++));
}
}
}
var buildDirs = _parseBuildDirs(argResults);
for (var target in serveTargets) {
buildDirs.add(BuildDirectory(target.dir));
}
var buildFilters = _parseBuildFilters(argResults, rootPackage);
var buildUpdates = (argResults[liveReloadOption] as bool)
? BuildUpdatesOption.liveReload
: BuildUpdatesOption.none;
return ServeOptions._(
buildFilters: buildFilters,
hostName: argResults[hostnameOption] as String,
buildUpdates: buildUpdates,
logRequests: argResults[logRequestsOption] as bool,
serveTargets: serveTargets,
deleteFilesByDefault: argResults[deleteFilesByDefaultOption] as bool,
enableLowResourcesMode: argResults[lowResourcesModeOption] as bool,
configKey: argResults[configOption] as String?,
buildDirs: buildDirs,
outputSymlinksOnly: argResults[symlinkOption] as bool,
trackPerformance: argResults[trackPerformanceOption] as bool,
skipBuildScriptCheck: argResults[skipBuildScriptCheckOption] as bool,
verbose: argResults[verboseOption] as bool,
builderConfigOverrides:
_parseBuilderConfigOverrides(argResults[defineOption], rootPackage),
isReleaseBuild: argResults[releaseOption] as bool,
logPerformanceDir: argResults[logPerformanceOption] as String?,
usePollingWatcher: argResults[usePollingWatcherOption] as bool,
enableExperiments: argResults[enableExperimentOption] as List<String>,
notFoundDefaultsTo: argResults[notFoundDefaultsToOption] as String?,
);
}
}
/// A target to serve, representing a directory and a port.
class ServeTarget {
final String dir;
final int port;
ServeTarget(this.dir, this.port);
}
Map<String, Map<String, dynamic>> _parseBuilderConfigOverrides(
dynamic parsedArg, String rootPackage) {
final builderConfigOverrides = <String, Map<String, dynamic>>{};
if (parsedArg == null) return builderConfigOverrides;
var allArgs = parsedArg is List<String> ? parsedArg : [parsedArg as String];
for (final define in allArgs) {
final parts = define.split('=');
const expectedFormat = '--define "<builder_key>=<option>=<value>"';
if (parts.length < 3) {
throw ArgumentError.value(
define,
defineOption,
'Expected at least 2 `=` signs, should be of the format like '
'$expectedFormat');
} else if (parts.length > 3) {
var rest = parts.sublist(2);
parts
..removeRange(2, parts.length)
..add(rest.join('='));
}
final builderKey = normalizeBuilderKeyUsage(parts[0], rootPackage);
final option = parts[1];
dynamic value;
// Attempt to parse the value as JSON, and if that fails then treat it as
// a normal string.
try {
value = json.decode(parts[2]);
} on FormatException catch (_) {
value = parts[2];
}
final config = builderConfigOverrides.putIfAbsent(
builderKey, () => <String, dynamic>{});
if (config.containsKey(option)) {
throw ArgumentError(
'Got duplicate overrides for the same builder option: '
'$builderKey=$option. Only one is allowed.');
}
config[option] = value;
}
return builderConfigOverrides;
}
/// Returns build directories with output information parsed from output
/// arguments.
///
/// Each output option is split on `:` where the first value is the
/// root input directory and the second value output directory.
/// If no delimeter is provided the root input directory will be null.
Set<BuildDirectory> _parseBuildDirs(ArgResults argResults) {
var outputs = argResults[outputOption] as List<String>?;
if (outputs == null) return <BuildDirectory>{};
var result = <BuildDirectory>{};
var outputPaths = <String>{};
void checkExisting(String outputDir) {
if (outputPaths.contains(outputDir)) {
throw ArgumentError.value(outputs.join(' '), '--output',
'Duplicate output directories are not allowed, got');
}
outputPaths.add(outputDir);
}
for (var option in argResults[outputOption] as List<String>) {
var split = option.split(':');
if (split.length == 1) {
var output = split.first;
checkExisting(output);
result.add(BuildDirectory('',
outputLocation: OutputLocation(output, hoist: false)));
} else if (split.length >= 2) {
var output = split.sublist(1).join(':');
checkExisting(output);
var root = split.first;
if (root.contains('/')) {
throw ArgumentError.value(
option, '--output', 'Input root can not be nested');
}
result.add(
BuildDirectory(split.first, outputLocation: OutputLocation(output)));
}
}
return result;
}
/// Throws a [UsageException] if [arg] looks like anything other than a top
/// level directory.
String _checkTopLevel(String arg, Command command) {
var parts = p.split(arg);
if (parts.length > 1 || arg == '.') {
throw UsageException(
'Only top level directories such as `web` or `test` are allowed as '
'positional args, but got `$arg`',
command.usage);
}
return arg;
}
/// Parses positional arguments as plain build directories.
Set<BuildDirectory> _parsePositionalBuildDirs(
Iterable<String> positionalArgs, Command command) =>
{
for (var arg in positionalArgs)
BuildDirectory(_checkTopLevel(arg, command))
};
/// Returns build filters parsed from [buildFilterOption] arguments.
///
/// These support `package:` uri syntax as well as regular path syntax,
/// with glob support for both package names and paths.
Set<BuildFilter> _parseBuildFilters(ArgResults argResults, String rootPackage) {
var filterArgs = argResults[buildFilterOption] as List<String>?;
if (filterArgs == null || filterArgs.isEmpty) return const {};
try {
return {
for (var arg in filterArgs) BuildFilter.fromArg(arg, rootPackage),
};
} on FormatException catch (e) {
throw ArgumentError.value(
e.source,
'--build-filter',
'Not a valid build filter, must be either a relative path or '
'`package:` uri.\n\n$e');
}
}