-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathdartdoc_options.dart
1639 lines (1426 loc) · 58.9 KB
/
dartdoc_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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
///
/// dartdoc's dartdoc_options.yaml configuration file follows similar loading
/// semantics to that of analysis_options.yaml,
/// [documented here](https://dart.dev/guides/language/analysis-options).
/// It searches parent directories until it finds an analysis_options.yaml file,
/// and uses built-in defaults if one is not found.
///
/// The classes here manage both the dartdoc_options.yaml loading and command
/// line arguments.
///
library dartdoc.dartdoc_options;
import 'dart:async';
import 'dart:io';
import 'package:analyzer/dart/element/element.dart';
import 'package:args/args.dart';
import 'package:dartdoc/dartdoc.dart';
import 'package:dartdoc/src/experiment_options.dart';
import 'package:dartdoc/src/io_utils.dart';
import 'package:dartdoc/src/source_linker.dart';
import 'package:dartdoc/src/tool_runner.dart';
import 'package:dartdoc/src/tuple.dart';
import 'package:dartdoc/src/warnings.dart';
import 'package:path/path.dart' as p;
import 'package:yaml/yaml.dart';
/// Constants to help with type checking, because T is int and so forth
/// don't work in Dart.
const String _kStringVal = '';
const List<String> _kListStringVal = <String>[];
const Map<String, String> _kMapStringVal = <String, String>{};
const int _kIntVal = 0;
const double _kDoubleVal = 0.0;
const bool _kBoolVal = true;
/// Args are computed relative to the current directory at the time the
/// program starts.
final Directory directoryCurrent = Directory.current;
final String directoryCurrentPath = p.canonicalize(Directory.current.path);
class DartdocOptionError extends DartdocFailure {
DartdocOptionError(String details) : super(details);
}
class DartdocFileMissing extends DartdocOptionError {
DartdocFileMissing(String details) : super(details);
}
/// Defines the attributes of a category in the options file, corresponding to
/// the 'categories' keyword in the options file, and populated by the
/// [CategoryConfiguration] class.
class CategoryDefinition {
/// Internal name of the category.
final String name;
/// Displayed name of the category in docs, or null if there is none.
final String _displayName;
/// Canonical path of the markdown file used to document this category
/// (or null if undocumented).
final String documentationMarkdown;
CategoryDefinition(this.name, this._displayName, this.documentationMarkdown);
/// Returns the [_displayName], if available, or else simply [name].
String get displayName => _displayName ?? name;
}
/// A configuration class that can interpret category definitions from a YAML
/// map.
class CategoryConfiguration {
/// A map of [CategoryDefinition.name] to [CategoryDefinition] objects.
final Map<String, CategoryDefinition> categoryDefinitions;
CategoryConfiguration._(this.categoryDefinitions);
static CategoryConfiguration get empty {
return CategoryConfiguration._({});
}
static CategoryConfiguration fromYamlMap(
YamlMap yamlMap, p.Context pathContext) {
Map<String, CategoryDefinition> newCategoryDefinitions = {};
for (MapEntry entry in yamlMap.entries) {
String name = entry.key.toString();
String displayName;
String documentationMarkdown;
var categoryMap = entry.value;
if (categoryMap is Map) {
displayName = categoryMap['displayName']?.toString();
documentationMarkdown = categoryMap['markdown']?.toString();
if (documentationMarkdown != null) {
documentationMarkdown =
pathContext.canonicalize(documentationMarkdown);
if (!File(documentationMarkdown).existsSync()) {
throw DartdocFileMissing(
'In categories definition for ${name}, "markdown" resolves to the missing file $documentationMarkdown');
}
}
newCategoryDefinitions[name] =
CategoryDefinition(name, displayName, documentationMarkdown);
}
}
return CategoryConfiguration._(newCategoryDefinitions);
}
}
/// Defines the attributes of a tool in the options file, corresponding to
/// the 'tools' keyword in the options file, and populated by the
/// [ToolConfiguration] class.
class ToolDefinition {
/// A list containing the command and options to be run for this tool. The
/// first argument in the command is the tool executable, and will have its
/// path evaluated relative to the `dartdoc_options.yaml` location. Must not
/// be an empty list, or be null.
final List<String> command;
/// A list containing the command and options to setup phase for this tool.
/// The first argument in the command is the tool executable, and will have
/// its path evaluated relative to the `dartdoc_options.yaml` location. May
/// be null or empty, in which case it will be ignored at setup time.
final List<String> setupCommand;
/// A description of the defined tool. Must not be null.
final String description;
/// If set, then the setup command has been run once for this tool definition.
bool setupComplete = false;
/// Returns true if the given executable path has an extension recognized as a
/// Dart extension (e.g. '.dart' or '.snapshot').
static bool isDartExecutable(String executable) {
var extension = p.extension(executable);
return extension == '.dart' || extension == '.snapshot';
}
/// Creates a ToolDefinition or subclass that is appropriate for the command
/// given.
factory ToolDefinition.fromCommand(
List<String> command, List<String> setupCommand, String description) {
assert(command != null);
assert(command.isNotEmpty);
assert(description != null);
if (isDartExecutable(command[0])) {
return DartToolDefinition(command, setupCommand, description);
} else {
return ToolDefinition(command, setupCommand, description);
}
}
ToolDefinition(this.command, this.setupCommand, this.description)
: assert(command != null),
assert(command.isNotEmpty),
assert(description != null);
@override
String toString() {
final String commandString =
'${this is DartToolDefinition ? '(Dart) ' : ''}"${command.join(' ')}"';
if (setupCommand == null) {
return '$runtimeType: $commandString ($description)';
} else {
return '$runtimeType: $commandString, with setup command '
'"${setupCommand.join(' ')}" ($description)';
}
}
}
/// Manages the creation of a single snapshot file in a context where multiple
/// async functions could be trying to use and/or create it.
///
/// To use:
///
/// var s = new Snapshot(...);
///
/// if (s.needsSnapshot) {
/// // create s.snapshotFile, then call:
/// s.snapshotCompleted();
/// } else {
/// await snapshotValid();
/// // use existing s.snapshotFile;
/// }
///
class Snapshot {
File _snapshotFile;
File get snapshotFile => _snapshotFile;
final Completer _snapshotCompleter = Completer();
Snapshot(Directory snapshotCache, String toolPath, int serial) {
if (toolPath.endsWith('.snapshot')) {
_needsSnapshot = false;
_snapshotFile = File(toolPath);
snapshotCompleted();
} else {
_snapshotFile =
File(p.join(snapshotCache.absolute.path, 'snapshot_$serial'));
}
}
bool _needsSnapshot = true;
/// Will return true precisely once, unless [snapshotFile] was already a
/// snapshot. In that case, will always return false.
bool get needsSnapshot {
if (_needsSnapshot == true) {
_needsSnapshot = false;
return true;
}
return _needsSnapshot;
}
Future<void> snapshotValid() => _snapshotCompleter.future;
void snapshotCompleted() => _snapshotCompleter.complete();
}
/// A singleton that keeps track of cached snapshot files. The [dispose]
/// function must be called before process exit to clean up snapshots in the
/// cache.
class SnapshotCache {
static SnapshotCache _instance;
Directory snapshotCache;
final Map<String, Snapshot> snapshots = {};
int _serial = 0;
SnapshotCache._()
: snapshotCache =
Directory.systemTemp.createTempSync('dartdoc_snapshot_cache_');
static SnapshotCache get instance {
_instance ??= SnapshotCache._();
return _instance;
}
Snapshot getSnapshot(String toolPath) {
if (snapshots.containsKey(toolPath)) {
return snapshots[toolPath];
}
snapshots[toolPath] = Snapshot(snapshotCache, toolPath, _serial);
_serial++;
return snapshots[toolPath];
}
Future<void> dispose() {
_instance = null;
if (snapshotCache != null && snapshotCache.existsSync()) {
return snapshotCache.delete(recursive: true);
}
return null;
}
}
/// A special kind of tool definition for Dart commands.
class DartToolDefinition extends ToolDefinition {
/// Takes a list of args to modify, and returns the name of the executable
/// to run. If no snapshot file existed, then create one and modify the args
/// so that if they are executed with dart, will result in the snapshot being
/// built.
Future<Tuple2<String, Function()>> modifyArgsToCreateSnapshotIfNeeded(
List<String> args) async {
assert(args[0] == command.first);
// Set up flags to create a new snapshot, if needed, and use the first run as the training
// run.
Snapshot snapshot = SnapshotCache.instance.getSnapshot(command.first);
File snapshotFile = snapshot.snapshotFile;
bool needsSnapshot = snapshot.needsSnapshot;
if (needsSnapshot) {
args.insertAll(0, [
'--snapshot=${snapshotFile.absolute.path}',
'--snapshot_kind=app-jit'
]);
} else {
await snapshot.snapshotValid();
// replace the first argument with the path to the snapshot.
args[0] = snapshotFile.absolute.path;
}
return Tuple2(Platform.resolvedExecutable,
needsSnapshot ? snapshot.snapshotCompleted : null);
}
DartToolDefinition(
List<String> command, List<String> setupCommand, String description)
: super(command, setupCommand, description);
}
/// A configuration class that can interpret [ToolDefinition]s from a YAML map.
class ToolConfiguration {
final Map<String, ToolDefinition> tools;
ToolRunner _runner;
ToolRunner get runner => _runner ??= ToolRunner(this);
ToolConfiguration._(this.tools);
static ToolConfiguration get empty {
return ToolConfiguration._({});
}
// TODO(jcollins-g): consider caching these.
static ToolConfiguration fromYamlMap(YamlMap yamlMap, p.Context pathContext) {
var newToolDefinitions = <String, ToolDefinition>{};
for (var entry in yamlMap.entries) {
var name = entry.key.toString();
var toolMap = entry.value;
var description;
List<String> command;
List<String> setupCommand;
if (toolMap is Map) {
description = toolMap['description']?.toString();
List<String> findCommand([String prefix = '']) {
List<String> command;
// If the command key is given, then it applies to all platforms.
var commandFrom = toolMap.containsKey('${prefix}command')
? '${prefix}command'
: '$prefix${Platform.operatingSystem}';
if (toolMap.containsKey(commandFrom)) {
if (toolMap[commandFrom].value is String) {
command = [toolMap[commandFrom].toString()];
if (command[0].isEmpty) {
throw DartdocOptionError(
'Tool commands must not be empty. Tool $name command entry '
'"$commandFrom" must contain at least one path.');
}
} else if (toolMap[commandFrom] is YamlList) {
command = (toolMap[commandFrom] as YamlList)
.map<String>((node) => node.toString())
.toList();
if (command.isEmpty) {
throw DartdocOptionError(
'Tool commands must not be empty. Tool $name command entry '
'"$commandFrom" must contain at least one path.');
}
} else {
throw DartdocOptionError(
'Tool commands must be a path to an executable, or a list of '
'strings that starts with a path to an executable. '
'The tool $name has a $commandFrom entry that is a '
'${toolMap[commandFrom].runtimeType}');
}
}
return command;
}
command = findCommand();
setupCommand = findCommand('setup_');
} else {
throw DartdocOptionError(
'Tools must be defined as a map of tool names to definitions. Tool '
'$name is not a map.');
}
if (command == null) {
throw DartdocOptionError(
'At least one of "command" or "${Platform.operatingSystem}" must '
'be defined for the tool $name.');
}
bool validateExecutable(String executable) {
bool isExecutable(int mode) {
return (0x1 & ((mode >> 6) | (mode >> 3) | mode)) != 0;
}
var executableFile = File(executable);
var exeStat = executableFile.statSync();
if (exeStat.type == FileSystemEntityType.notFound) {
throw DartdocOptionError('Command executables must exist. '
'The file "$executable" does not exist for tool $name.');
}
var isDartCommand = ToolDefinition.isDartExecutable(executable);
// Dart scripts don't need to be executable, because they'll be
// executed with the Dart binary.
if (!isDartCommand && !isExecutable(exeStat.mode)) {
throw DartdocOptionError('Non-Dart commands must be '
'executable. The file "$executable" for tool $name does not have '
'execute permission.');
}
return isDartCommand;
}
var executable = pathContext.canonicalize(command.removeAt(0));
validateExecutable(executable);
if (setupCommand != null) {
var setupExecutable =
pathContext.canonicalize(setupCommand.removeAt(0));
var isDartSetupCommand = validateExecutable(executable);
// Setup commands aren't snapshotted, since they're only run once.
setupCommand = (isDartSetupCommand
? [Platform.resolvedExecutable, setupExecutable]
: [setupExecutable]) +
setupCommand;
}
newToolDefinitions[name] = ToolDefinition.fromCommand(
[executable] + command, setupCommand, description);
}
return ToolConfiguration._(newToolDefinitions);
}
}
/// A container class to keep track of where our yaml data came from.
class _YamlFileData {
/// The map from the yaml file.
final Map data;
/// The path to the directory containing the yaml file.
final String canonicalDirectoryPath;
_YamlFileData(this.data, this.canonicalDirectoryPath);
}
/// Some DartdocOption subclasses need to keep track of where they
/// got the value from; this class contains those intermediate results
/// so that error messages can be more useful.
class _OptionValueWithContext<T> {
/// The value of the option at canonicalDirectoryPath.
final T value;
/// A canonical path to the directory where this value came from. May
/// be different from [DartdocOption.valueAt]'s `dir` parameter.
String canonicalDirectoryPath;
/// If non-null, the basename of the configuration file the value came from.
String definingFile;
/// A [pathLib.Context] variable initialized with canonicalDirectoryPath.
p.Context pathContext;
/// Build a _OptionValueWithContext.
/// [path] is the path where this value came from (not required to be canonical)
_OptionValueWithContext(this.value, String path, {String definingFile}) {
this.definingFile = definingFile;
canonicalDirectoryPath = p.canonicalize(path);
pathContext = p.Context(current: canonicalDirectoryPath);
}
/// Assume value is a path, and attempt to resolve it. Throws [UnsupportedError]
/// if [T] isn't a [String] or [List<String>].
T get resolvedValue {
if (value is List<String>) {
return (value as List<String>)
.map((v) => pathContext.canonicalize(resolveTildePath(v)))
.cast<String>()
.toList() as T;
} else if (value is String) {
return pathContext.canonicalize(resolveTildePath(value as String)) as T;
} else if (value is Map<String, String>) {
return (value as Map<String, String>)
.map<String, String>((String key, String value) {
return MapEntry(key, pathContext.canonicalize(resolveTildePath(value)));
}) as T;
} else {
throw UnsupportedError('Type $T is not supported for resolvedValue');
}
}
}
/// An abstract class for interacting with dartdoc options.
///
/// This class and its implementations allow Dartdoc to declare options
/// that are both defined in a configuration file and specified via the
/// command line, with searching the directory tree for a proper file
/// and overriding file options with the command line built-in. A number
/// of sanity checks are also built in to these classes so that file existence
/// can be verified, types constrained, and defaults provided.
///
/// Use via implementations [DartdocOptionSet], [DartdocOptionArgFile],
/// [DartdocOptionArgOnly], and [DartdocOptionFileOnly].
abstract class DartdocOption<T> {
/// This is the value returned if we couldn't find one otherwise.
final T defaultsTo;
/// Text string for help passed on in command line options.
final String help;
/// The name of this option, not including the names of any parents.
final String name;
/// Set to true if this option represents the name of a directory.
final bool isDir;
/// Set to true if this option represents the name of a file.
final bool isFile;
/// Set to true if DartdocOption subclasses should validate that the
/// directory or file exists. Does not imply validation of [defaultsTo],
/// and requires that one of [isDir] or [isFile] is set.
final bool mustExist;
DartdocOption(this.name, this.defaultsTo, this.help, this.isDir, this.isFile,
this.mustExist, this._convertYamlToType) {
assert(!(isDir && isFile));
if (isDir || isFile) assert(_isString || _isListString || _isMapString);
if (mustExist) {
assert(isDir || isFile);
}
}
/// Closure to convert yaml data into some other structure.
T Function(YamlMap, p.Context) _convertYamlToType;
// The choice not to use reflection means there's some ugly type checking,
// somewhat more ugly than we'd have to do anyway to automatically convert
// command line arguments and yaml data to real types.
//
// Condense the ugly all in one place, this set of getters.
bool get _isString => _kStringVal is T;
bool get _isListString => _kListStringVal is T;
bool get _isMapString => _kMapStringVal is T;
bool get _isBool => _kBoolVal is T;
bool get _isInt => _kIntVal is T;
bool get _isDouble => _kDoubleVal is T;
DartdocOption _parent;
/// The parent of this DartdocOption, or null if this is the root.
DartdocOption get parent => _parent;
final Map<String, _YamlFileData> __yamlAtCanonicalPathCache = {};
/// Implementation detail for [DartdocOptionFileOnly]. Make sure we use
/// the root node's cache.
Map<String, _YamlFileData> get _yamlAtCanonicalPathCache =>
root.__yamlAtCanonicalPathCache;
final ArgParser __argParser = ArgParser(usageLineLength: 80);
ArgParser get argParser => root.__argParser;
ArgResults __argResults;
/// Parse these as string arguments (from argv) with the argument parser.
/// Call before calling [valueAt] for any [DartdocOptionArgOnly] or
/// [DartdocOptionArgFile] in this tree.
void _parseArguments(List<String> arguments) {
__argResults = argParser.parse(arguments);
}
/// Throw [DartdocFileMissing] with a detailed error message indicating where
/// the error came from when a file or directory option is missing.
void _onMissing(
_OptionValueWithContext valueWithContext, String missingFilename);
/// Call [_onMissing] for every path that does not exist.
void _validatePaths(_OptionValueWithContext valueWithContext) {
if (!mustExist) return;
assert(isDir || isFile);
List<String> resolvedPaths;
if (valueWithContext.value is String) {
resolvedPaths = [valueWithContext.resolvedValue];
} else if (valueWithContext.value is List<String>) {
resolvedPaths = valueWithContext.resolvedValue.toList();
} else if (valueWithContext.value is Map<String, String>) {
resolvedPaths = valueWithContext.resolvedValue.values.toList();
} else {
assert(
false,
"Trying to ensure existence of unsupported type "
"${valueWithContext.value.runtimeType}");
}
for (String path in resolvedPaths) {
FileSystemEntity f = isDir ? Directory(path) : File(path);
if (!f.existsSync()) {
_onMissing(valueWithContext, path);
}
}
}
/// For a [List<String>] or [String] value, if [isDir] or [isFile] is set,
/// resolve paths in value relative to canonicalPath.
T _handlePathsInContext(_OptionValueWithContext valueWithContext) {
if (valueWithContext?.value == null || !(isDir || isFile)) {
return valueWithContext?.value;
}
_validatePaths(valueWithContext);
return valueWithContext.resolvedValue;
}
/// Call this with argv to set up the argument overrides. Applies to all
/// children.
void parseArguments(List<String> arguments) =>
root._parseArguments(arguments);
ArgResults get _argResults => root.__argResults;
/// Set the parent of this [DartdocOption]. Do not call more than once.
set parent(DartdocOption newParent) {
assert(_parent == null);
_parent = newParent;
}
/// The root [DartdocOption] containing this object, or [this] if the object
/// has no parent.
DartdocOption get root {
DartdocOption p = this;
while (p.parent != null) {
p = p.parent;
}
return p;
}
/// All object names starting at the root.
Iterable<String> get keys {
List<String> keyList = [];
DartdocOption option = this;
while (option?.name != null) {
keyList.add(option.name);
option = option.parent;
}
return keyList.reversed;
}
/// Direct children of this node, mapped by name.
final Map<String, DartdocOption> _children = {};
/// Return the calculated value of this option, given the directory as context.
///
/// If [isFile] or [isDir] is set, the returned value will be transformed
/// into a canonical path relative to the current working directory
/// (for arguments) or the config file from which the value was derived.
///
/// May throw [DartdocOptionError] if a command line argument is of the wrong
/// type. If [mustExist] is true, will throw [DartdocFileMissing] for command
/// line parameters and file paths in config files that don't point to
/// corresponding files or directories.
T valueAt(Directory dir);
/// Calls [valueAt] with the working directory at the start of the program.
T valueAtCurrent() => valueAt(directoryCurrent);
/// Calls [valueAt] on the directory this element is defined in.
T valueAtElement(Element element) =>
valueAt(Directory(p.canonicalize(p.basename(element.source.fullName))));
/// Adds a DartdocOption to the children of this DartdocOption.
void add(DartdocOption option) {
if (_children.containsKey(option.name)) {
throw DartdocOptionError(
'Tried to add two children with the same name: ${option.name}');
}
_children[option.name] = option;
option.parent = this;
option.traverse((option) => option._onAdd());
}
/// This method is guaranteed to be called when [this] or any parent is added.
void _onAdd() {}
/// Adds a list of dartdoc options to the children of this DartdocOption.
void addAll(Iterable<DartdocOption> options) =>
options.forEach((o) => add(o));
/// Get the immediate child of this node named [name].
DartdocOption operator [](String name) {
return _children[name];
}
/// Apply the function [visit] to [this] and all children.
void traverse(void visit(DartdocOption option)) {
visit(this);
_children.values.forEach((d) => d.traverse(visit));
}
}
/// A class that defaults to a value computed from a closure, but can be
/// overridden by a file.
class DartdocOptionFileSynth<T> extends DartdocOption<T>
with DartdocSyntheticOption<T>, _DartdocFileOption<T> {
bool _parentDirOverridesChild;
@override
final T Function(DartdocSyntheticOption<T>, Directory) _compute;
DartdocOptionFileSynth(String name, this._compute,
{bool mustExist = false,
String help = '',
bool isDir = false,
bool isFile = false,
bool parentDirOverridesChild,
T Function(YamlMap, p.Context) convertYamlToType})
: super(name, null, help, isDir, isFile, mustExist, convertYamlToType) {
_parentDirOverridesChild = parentDirOverridesChild;
}
@override
T valueAt(Directory dir) {
_OptionValueWithContext result = _valueAtFromFile(dir);
if (result?.definingFile != null) {
return _handlePathsInContext(result);
}
return _valueAtFromSynthetic(dir);
}
@override
void _onMissing(
_OptionValueWithContext valueWithContext, String missingPath) {
if (valueWithContext.definingFile != null) {
_onMissingFromFiles(valueWithContext, missingPath);
} else {
_onMissingFromSynthetic(valueWithContext, missingPath);
}
}
@override
bool get parentDirOverridesChild => _parentDirOverridesChild;
}
/// A class that defaults to a value computed from a closure, but can
/// be overridden on the command line.
class DartdocOptionArgSynth<T> extends DartdocOption<T>
with DartdocSyntheticOption<T>, _DartdocArgOption<T> {
String _abbr;
bool _hide;
bool _negatable;
bool _splitCommas;
@override
final T Function(DartdocSyntheticOption<T>, Directory) _compute;
DartdocOptionArgSynth(String name, this._compute,
{String abbr,
bool mustExist = false,
String help = '',
bool hide = false,
bool isDir = false,
bool isFile = false,
bool negatable = false,
bool splitCommas})
: super(name, null, help, isDir, isFile, mustExist, null) {
_hide = hide;
_negatable = negatable;
_splitCommas = splitCommas;
_abbr = abbr;
}
@override
void _onMissing(
_OptionValueWithContext valueWithContext, String missingPath) {
_onMissingFromArgs(valueWithContext, missingPath);
}
@override
T valueAt(Directory dir) {
if (_argResults.wasParsed(argName)) {
return _valueAtFromArgs();
}
return _valueAtFromSynthetic(dir);
}
@override
String get abbr => _abbr;
@override
bool get hide => _hide;
@override
bool get negatable => _negatable;
@override
bool get splitCommas => _splitCommas;
}
/// A synthetic option takes a closure at construction time that computes
/// the value of the configuration option based on other configuration options.
/// Does not protect against closures that self-reference. If [mustExist] and
/// [isDir] or [isFile] is set, computed values will be resolved to canonical
/// paths.
class DartdocOptionSyntheticOnly<T> extends DartdocOption<T>
with DartdocSyntheticOption<T> {
@override
final T Function(DartdocSyntheticOption<T>, Directory) _compute;
DartdocOptionSyntheticOnly(String name, this._compute,
{bool mustExist = false,
String help = '',
bool isDir = false,
bool isFile = false})
: super(name, null, help, isDir, isFile, mustExist, null);
}
abstract class DartdocSyntheticOption<T> implements DartdocOption<T> {
T Function(DartdocSyntheticOption<T>, Directory) get _compute;
@override
T valueAt(Directory dir) => _valueAtFromSynthetic(dir);
T _valueAtFromSynthetic(Directory dir) {
_OptionValueWithContext context =
_OptionValueWithContext<T>(_compute(this, dir), dir.path);
return _handlePathsInContext(context);
}
@override
void _onMissing(
_OptionValueWithContext valueWithContext, String missingPath) =>
_onMissingFromSynthetic(valueWithContext, missingPath);
void _onMissingFromSynthetic(
_OptionValueWithContext valueWithContext, String missingPath) {
String description =
'Synthetic configuration option ${name} from <internal>';
throw DartdocFileMissing(
'$description, computed as ${valueWithContext.value}, resolves to missing path: "${missingPath}"');
}
}
typedef OptionGenerator = Future<List<DartdocOption>> Function();
/// A [DartdocOption] that only contains other [DartdocOption]s and is not an option itself.
class DartdocOptionSet extends DartdocOption<Null> {
DartdocOptionSet(String name)
: super(name, null, null, false, false, false, null);
/// Asynchronous factory that is the main entry point to initialize Dartdoc
/// options for use.
///
/// [name] is the top level key for the option set.
/// [optionGenerators] is a sequence of asynchronous functions that return
/// [DartdocOption]s that will be added to the new option set.
static Future<DartdocOptionSet> fromOptionGenerators(
String name, Iterable<OptionGenerator> optionGenerators) async {
DartdocOptionSet optionSet = DartdocOptionSet(name);
for (OptionGenerator generator in optionGenerators) {
optionSet.addAll(await generator());
}
return optionSet;
}
/// [DartdocOptionSet] always has the null value.
@override
Null valueAt(Directory dir) => null;
/// Since we have no value, [_onMissing] does nothing.
@override
void _onMissing(
_OptionValueWithContext valueWithContext, String missingFilename) {}
/// Traverse skips this node, because it doesn't represent a real configuration object.
@override
void traverse(void visitor(DartdocOption option)) {
_children.values.forEach((d) => d.traverse(visitor));
}
}
/// A [DartdocOption] that only exists as a command line argument. --help would
/// be a good example.
class DartdocOptionArgOnly<T> extends DartdocOption<T>
with _DartdocArgOption<T> {
String _abbr;
bool _hide;
bool _negatable;
bool _splitCommas;
DartdocOptionArgOnly(String name, T defaultsTo,
{String abbr,
bool mustExist = false,
String help = '',
bool hide = false,
bool isDir = false,
bool isFile = false,
bool negatable = false,
bool splitCommas})
: super(name, defaultsTo, help, isDir, isFile, mustExist, null) {
_hide = hide;
_negatable = negatable;
_splitCommas = splitCommas;
_abbr = abbr;
}
@override
String get abbr => _abbr;
@override
bool get hide => _hide;
@override
bool get negatable => _negatable;
@override
bool get splitCommas => _splitCommas;
}
/// A [DartdocOption] that works with command line arguments and dartdoc_options files.
class DartdocOptionArgFile<T> extends DartdocOption<T>
with _DartdocArgOption<T>, _DartdocFileOption<T> {
String _abbr;
bool _hide;
bool _negatable;
bool _parentDirOverridesChild;
bool _splitCommas;
DartdocOptionArgFile(String name, T defaultsTo,
{String abbr,
bool mustExist = false,
String help = '',
bool hide = false,
bool isDir = false,
bool isFile = false,
bool negatable = false,
bool parentDirOverridesChild = false,
bool splitCommas})
: super(name, defaultsTo, help, isDir, isFile, mustExist, null) {
_abbr = abbr;
_hide = hide;
_negatable = negatable;
_parentDirOverridesChild = parentDirOverridesChild;
_splitCommas = splitCommas;
}
@override
void _onMissing(
_OptionValueWithContext valueWithContext, String missingPath) {
if (valueWithContext.definingFile != null) {
_onMissingFromFiles(valueWithContext, missingPath);
} else {
_onMissingFromArgs(valueWithContext, missingPath);
}
}
/// Try to find an explicit argument setting this value, but if not, fall back to files
/// finally, the default.
@override
T valueAt(Directory dir) {
T value = _valueAtFromArgs();
if (value == null) value = _valueAtFromFiles(dir);
if (value == null) value = defaultsTo;
return value;
}
@override
String get abbr => _abbr;
@override
bool get hide => _hide;
@override
bool get negatable => _negatable;
@override
bool get parentDirOverridesChild => _parentDirOverridesChild;
@override
bool get splitCommas => _splitCommas;
}
class DartdocOptionFileOnly<T> extends DartdocOption<T>
with _DartdocFileOption<T> {
bool _parentDirOverridesChild;
DartdocOptionFileOnly(String name, T defaultsTo,
{bool mustExist = false,
String help = '',
bool isDir = false,
bool isFile = false,
bool parentDirOverridesChild = false,
T Function(YamlMap, p.Context) convertYamlToType})
: super(name, defaultsTo, help, isDir, isFile, mustExist,
convertYamlToType) {
_parentDirOverridesChild = parentDirOverridesChild;
}
@override
bool get parentDirOverridesChild => _parentDirOverridesChild;
}
/// Implements checking for options contained in dartdoc.yaml.
abstract class _DartdocFileOption<T> implements DartdocOption<T> {
/// If true, the parent directory's value overrides the child's. Otherwise, the child's
/// value overrides values in parents.
bool get parentDirOverridesChild;
/// The name of the option, with nested options joined by [.]. For example:
///
/// ```yaml
/// dartdoc:
/// stuff:
/// things:
/// ```
/// would have the name `things` and the fieldName `dartdoc.stuff.things`.
String get fieldName => keys.join('.');
@override
void _onMissing(
_OptionValueWithContext valueWithContext, String missingPath) =>
_onMissingFromFiles(valueWithContext, missingPath);
void _onMissingFromFiles(
_OptionValueWithContext valueWithContext, String missingPath) {
String dartdocYaml = p.join(
valueWithContext.canonicalDirectoryPath, valueWithContext.definingFile);
throw DartdocFileMissing(