forked from dart-lang/dartdoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdartdoc.dart
541 lines (485 loc) · 18.4 KB
/
dartdoc.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
// Copyright (c) 2014, 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.
/// A documentation generator for Dart.
///
/// Library interface is currently under heavy construction and may change
/// drastically between minor revisions.
library dartdoc;
import 'dart:async';
import 'dart:convert';
import 'dart:io' show exitCode, stderr;
import 'package:analyzer/file_system/file_system.dart';
import 'package:dartdoc/src/dartdoc_options.dart';
import 'package:dartdoc/src/generator/empty_generator.dart';
import 'package:dartdoc/src/generator/generator.dart';
import 'package:dartdoc/src/generator/html_generator.dart';
import 'package:dartdoc/src/generator/markdown_generator.dart';
import 'package:dartdoc/src/logging.dart';
import 'package:dartdoc/src/model/model.dart';
import 'package:dartdoc/src/package_meta.dart';
import 'package:dartdoc/src/tool_runner.dart';
import 'package:dartdoc/src/tuple.dart';
import 'package:dartdoc/src/utils.dart';
import 'package:dartdoc/src/version.dart';
import 'package:dartdoc/src/warnings.dart';
import 'package:html/parser.dart' show parse;
import 'package:path/path.dart' as path;
export 'package:dartdoc/src/dartdoc_options.dart';
export 'package:dartdoc/src/element_type.dart';
export 'package:dartdoc/src/generator/generator.dart';
export 'package:dartdoc/src/model/model.dart';
export 'package:dartdoc/src/package_config_provider.dart';
export 'package:dartdoc/src/package_meta.dart';
const String programName = 'dartdoc';
// Update when pubspec version changes by running `pub run build_runner build`
const String dartdocVersion = packageVersion;
/// Helper class that consolidates option contexts for instantiating generators.
class DartdocGeneratorOptionContext extends DartdocOptionContext
with GeneratorContext {
DartdocGeneratorOptionContext(
DartdocOptionSet optionSet, Folder dir, ResourceProvider resourceProvider)
: super(optionSet, dir, resourceProvider);
}
class DartdocFileWriter implements FileWriter {
final String outputDir;
ResourceProvider resourceProvider;
final Map<String, Warnable> _fileElementMap = {};
@override
final Set<String> writtenFiles = {};
DartdocFileWriter(this.outputDir, this.resourceProvider);
@override
void write(String filePath, Object content,
{bool allowOverwrite, Warnable element}) {
// Replace '/' separators with proper separators for the platform.
var outFile = path.joinAll(filePath.split('/'));
allowOverwrite ??= false;
if (!allowOverwrite) {
if (_fileElementMap.containsKey(outFile)) {
assert(element != null,
'Attempted overwrite of ${outFile} without corresponding element');
var originalElement = _fileElementMap[outFile];
Iterable<Warnable> referredFrom =
originalElement != null ? [originalElement] : null;
element?.warn(PackageWarning.duplicateFile,
message: outFile, referredFrom: referredFrom);
}
}
_fileElementMap[outFile] = element;
var file = resourceProvider
.getFile(resourceProvider.pathContext.join(outputDir, outFile));
var parent = file.parent;
if (!parent.exists) {
parent.create();
}
if (content is String) {
file.writeAsStringSync(content);
} else if (content is List<int>) {
file.writeAsBytesSync(content);
} else {
throw ArgumentError.value(
content, 'content', '`content` must be `String` or `List<int>`.');
}
writtenFiles.add(outFile);
logProgress(outFile);
}
}
/// Generates Dart documentation for all public Dart libraries in the given
/// directory.
class Dartdoc {
final Generator generator;
final PackageBuilder packageBuilder;
final DartdocOptionContext config;
final Set<String> writtenFiles = {};
Folder outputDir;
// Fires when the self checks make progress.
final StreamController<String> _onCheckProgress =
StreamController(sync: true);
Dartdoc._(this.config, this.generator, this.packageBuilder) {
outputDir = config.resourceProvider
.getFolder(config.resourceProvider.pathContext.absolute(config.output))
..create();
}
/// An asynchronous factory method that builds Dartdoc's file writers
/// and returns a Dartdoc object with them.
@Deprecated('Prefer fromContext() instead')
static Future<Dartdoc> withDefaultGenerators(
DartdocGeneratorOptionContext config,
PackageBuilder packageBuilder,
) async {
return Dartdoc._(
config,
await initHtmlGenerator(config),
packageBuilder,
);
}
/// Asynchronous factory method that builds Dartdoc with an empty generator.
static Future<Dartdoc> withEmptyGenerator(
DartdocOptionContext config,
PackageBuilder packageBuilder,
) async {
return Dartdoc._(
config,
await initEmptyGenerator(config),
packageBuilder,
);
}
/// Asynchronous factory method that builds Dartdoc with a generator
/// determined by the given context.
static Future<Dartdoc> fromContext(
DartdocGeneratorOptionContext context,
PackageBuilder packageBuilder,
) async {
Generator generator;
switch (context.format) {
case 'html':
generator = await initHtmlGenerator(context);
break;
case 'md':
generator = await initMarkdownGenerator(context);
break;
default:
throw DartdocFailure('Unsupported output format: ${context.format}');
}
return Dartdoc._(
context,
generator,
packageBuilder,
);
}
Stream<String> get onCheckProgress => _onCheckProgress.stream;
PackageGraph packageGraph;
/// Generate Dartdoc documentation.
///
/// [DartdocResults] is returned if dartdoc succeeds. [DartdocFailure] is
/// thrown if dartdoc fails in an expected way, for example if there is an
/// analysis error in the code.
Future<DartdocResults> generateDocsBase() async {
var _stopwatch = Stopwatch()..start();
double seconds;
packageGraph = await packageBuilder.buildPackageGraph();
seconds = _stopwatch.elapsedMilliseconds / 1000.0;
var libs = packageGraph.libraries.length;
logInfo("Initialized dartdoc with ${libs} librar${libs == 1 ? 'y' : 'ies'} "
'in ${seconds.toStringAsFixed(1)} seconds');
_stopwatch.reset();
final generator = this.generator;
if (generator != null) {
// Create the out directory.
if (!outputDir.exists) outputDir.create();
var writer = DartdocFileWriter(outputDir.path, config.resourceProvider);
await generator.generate(packageGraph, writer);
writtenFiles.addAll(writer.writtenFiles);
if (config.validateLinks && writtenFiles.isNotEmpty) {
validateLinks(packageGraph, outputDir.path);
}
}
var warnings = packageGraph.packageWarningCounter.warningCount;
var errors = packageGraph.packageWarningCounter.errorCount;
if (warnings == 0 && errors == 0) {
logInfo('no issues found');
} else {
logWarning("found ${warnings} ${pluralize('warning', warnings)} "
"and ${errors} ${pluralize('error', errors)}");
}
seconds = _stopwatch.elapsedMilliseconds / 1000.0;
libs = packageGraph.localPublicLibraries.length;
logInfo("Documented ${libs} public librar${libs == 1 ? 'y' : 'ies'} "
'in ${seconds.toStringAsFixed(1)} seconds');
return DartdocResults(config.topLevelPackageMeta, packageGraph, outputDir);
}
Future<DartdocResults> generateDocs() async {
try {
logInfo('Documenting ${config.topLevelPackageMeta}...');
var dartdocResults = await generateDocsBase();
if (dartdocResults.packageGraph.localPublicLibraries.isEmpty) {
throw DartdocFailure(
'dartdoc could not find any libraries to document');
}
final errorCount =
dartdocResults.packageGraph.packageWarningCounter.errorCount;
if (errorCount > 0) {
throw DartdocFailure(
'dartdoc encountered $errorCount errors while processing.');
}
var outDirPath = config.resourceProvider.pathContext
.absolute(dartdocResults.outDir.path);
logInfo('Success! Docs generated into $outDirPath');
return dartdocResults;
} finally {
// Clear out any cached tool snapshots and temporary directories.
// ignore: unawaited_futures
SnapshotCache.instance?.dispose();
// ignore: unawaited_futures
ToolTempFileTracker.instance?.dispose();
}
}
/// Warn on file paths.
void _warn(PackageGraph packageGraph, PackageWarning kind, String warnOn,
String origin,
{String referredFrom}) {
// Ordinarily this would go in [Package.warn], but we don't actually know what
// ModelElement to warn on yet.
Warnable warnOnElement;
var referredFromElements = <Warnable>{};
Set<Warnable> warnOnElements;
// Make all paths relative to origin.
if (path.isWithin(origin, warnOn)) {
warnOn = path.relative(warnOn, from: origin);
}
if (referredFrom != null) {
if (path.isWithin(origin, referredFrom)) {
referredFrom = path.relative(referredFrom, from: origin);
}
// Source paths are always relative.
if (_hrefs[referredFrom] != null) {
referredFromElements.addAll(_hrefs[referredFrom]);
}
}
warnOnElements = _hrefs[warnOn];
if (referredFromElements.any((e) => e.isCanonical)) {
referredFromElements.removeWhere((e) => !e.isCanonical);
}
if (warnOnElements != null) {
if (warnOnElements.any((e) => e.isCanonical)) {
warnOnElement = warnOnElements.firstWhere((e) => e.isCanonical);
} else {
// If we don't have a canonical element, just pick one.
warnOnElement = warnOnElements.isEmpty ? null : warnOnElements.first;
}
}
if (referredFromElements.isEmpty && referredFrom == 'index.html') {
referredFromElements.add(packageGraph.defaultPackage);
}
var message = warnOn;
if (referredFrom == 'index.json') message = '$warnOn (from index.json)';
packageGraph.warnOnElement(warnOnElement, kind,
message: message, referredFrom: referredFromElements);
}
void _doOrphanCheck(
PackageGraph packageGraph, String origin, Set<String> visited) {
var normalOrigin = path.normalize(origin);
var staticAssets = path.joinAll([normalOrigin, 'static-assets', '']);
var indexJson = path.joinAll([normalOrigin, 'index.json']);
var foundIndexJson = false;
void checkDirectory(Folder dir) {
for (var f in dir.getChildren()) {
if (f is Folder) {
checkDirectory(f);
continue;
}
var fullPath = path.normalize(f.path);
if (fullPath.startsWith(staticAssets)) {
continue;
}
if (path.equals(fullPath, indexJson)) {
foundIndexJson = true;
_onCheckProgress.add(fullPath);
continue;
}
if (visited.contains(fullPath)) continue;
var relativeFullPath = path.relative(fullPath, from: normalOrigin);
if (!writtenFiles.contains(relativeFullPath)) {
// This isn't a file we wrote (this time); don't claim we did.
_warn(
packageGraph, PackageWarning.unknownFile, fullPath, normalOrigin);
} else {
// Error messages are orphaned by design and do not appear in the search
// index.
if (<String>['__404error.html', 'categories.json']
.contains(fullPath)) {
_warn(packageGraph, PackageWarning.orphanedFile, fullPath,
normalOrigin);
}
}
_onCheckProgress.add(fullPath);
}
}
checkDirectory(config.resourceProvider.getFolder(normalOrigin));
if (!foundIndexJson) {
_warn(packageGraph, PackageWarning.brokenLink, indexJson, normalOrigin);
_onCheckProgress.add(indexJson);
}
}
// This is extracted to save memory during the check; be careful not to hang
// on to anything referencing the full file and doc tree.
Tuple2<Iterable<String>, String> _getStringLinksAndHref(String fullPath) {
var file = config.resourceProvider.getFile('$fullPath');
if (!file.exists) {
return null;
}
// TODO(srawlins): It is possible that instantiating an HtmlParser using
// `lowercaseElementName: false` and `lowercaseAttrName: false` may save
// time or memory.
var doc = parse(file.readAsBytesSync());
var base = doc.querySelector('base');
String baseHref;
if (base != null) {
baseHref = base.attributes['href'];
}
var links = doc.querySelectorAll('a');
var stringLinks = links
.map((link) => link.attributes['href'])
.where((href) => href != null)
.toList();
return Tuple2(stringLinks, baseHref);
}
void _doSearchIndexCheck(
PackageGraph packageGraph, String origin, Set<String> visited) {
var fullPath = path.joinAll([origin, 'index.json']);
var indexPath = path.joinAll([origin, 'index.html']);
var file = config.resourceProvider.getFile('$fullPath');
if (!file.exists) {
return null;
}
var decoder = JsonDecoder();
List<Object> jsonData = decoder.convert(file.readAsStringSync());
var found = <String>{};
found.add(fullPath);
// The package index isn't supposed to be in the search, so suppress the
// warning.
found.add(indexPath);
for (Map<String, dynamic> entry in jsonData) {
if (entry.containsKey('href')) {
var entryPath = path.joinAll([origin, entry['href']]);
if (!visited.contains(entryPath)) {
_warn(packageGraph, PackageWarning.brokenLink, entryPath,
path.normalize(origin),
referredFrom: fullPath);
}
found.add(entryPath);
}
}
// Missing from search index
var missing_from_search = visited.difference(found);
for (var s in missing_from_search) {
_warn(packageGraph, PackageWarning.missingFromSearchIndex, s,
path.normalize(origin),
referredFrom: fullPath);
}
}
void _doCheck(PackageGraph packageGraph, String origin, Set<String> visited,
String pathToCheck,
[String source, String fullPath]) {
if (fullPath == null) {
fullPath = path.joinAll([origin, pathToCheck]);
fullPath = path.normalize(fullPath);
}
var stringLinksAndHref = _getStringLinksAndHref(fullPath);
if (stringLinksAndHref == null) {
_warn(packageGraph, PackageWarning.brokenLink, pathToCheck,
path.normalize(origin),
referredFrom: source);
_onCheckProgress.add(pathToCheck);
// Remove so that we properly count that the file doesn't exist for
// the orphan check.
visited.remove(fullPath);
return null;
}
visited.add(fullPath);
var stringLinks = stringLinksAndHref.item1;
var baseHref = stringLinksAndHref.item2;
// Prevent extremely large stacks by storing the paths we are using
// here instead -- occasionally, very large jobs have overflowed
// the stack without this.
// (newPathToCheck, newFullPath)
var toVisit = <Tuple2<String, String>>{};
final ignoreHyperlinks = RegExp(r'^(https:|http:|mailto:|ftp:)');
for (var href in stringLinks) {
if (!href.startsWith(ignoreHyperlinks)) {
Uri uri;
try {
uri = Uri.parse(href);
} on FormatException {
// ignore
}
if (uri == null || !uri.hasAuthority && !uri.hasFragment) {
String full;
if (baseHref != null) {
full = '${path.dirname(pathToCheck)}/$baseHref/$href';
} else {
full = '${path.dirname(pathToCheck)}/$href';
}
var newPathToCheck = path.normalize(full);
var newFullPath = path.joinAll([origin, newPathToCheck]);
newFullPath = path.normalize(newFullPath);
if (!visited.contains(newFullPath)) {
toVisit.add(Tuple2(newPathToCheck, newFullPath));
visited.add(newFullPath);
}
}
}
}
for (var visitPaths in toVisit) {
_doCheck(packageGraph, origin, visited, visitPaths.item1, pathToCheck,
visitPaths.item2);
}
_onCheckProgress.add(pathToCheck);
}
Map<String, Set<ModelElement>> _hrefs;
/// Don't call this method more than once, and only after you've
/// generated all docs for the Package.
void validateLinks(PackageGraph packageGraph, String origin) {
assert(_hrefs == null);
_hrefs = packageGraph.allHrefs;
final visited = <String>{};
final start = 'index.html';
logInfo('Validating docs...');
_doCheck(packageGraph, origin, visited, start);
_doOrphanCheck(packageGraph, origin, visited);
_doSearchIndexCheck(packageGraph, origin, visited);
}
/// Runs [generateDocs] function and properly handles the errors.
///
/// Passing in a [postProcessCallback] to do additional processing after
/// the documentation is generated.
void executeGuarded([
Future<void> Function(DartdocOptionContext) postProcessCallback,
]) {
onCheckProgress.listen(logProgress);
// This function should *never* await `runZonedGuarded` because the errors
// thrown in generateDocs are uncaught. We want this because uncaught errors
// cause IDE debugger to automatically stop at the exception.
//
// If you await the zone, the code that comes after the await is not
// executed if the zone dies due to uncaught error. To avoid this confusion,
// never await `runZonedGuarded` and never change the return value of
// [executeGuarded].
runZonedGuarded(
() async {
await generateDocs();
await postProcessCallback?.call(config);
},
(e, chain) {
if (e is DartdocFailure) {
stderr.writeln('\ndartdoc failed: ${e}.');
if (config.verboseWarnings) {
stderr.writeln(chain);
}
exitCode = 1;
} else {
stderr.writeln('\ndartdoc failed: ${e}\n${chain}');
exitCode = 255;
}
},
zoneSpecification: ZoneSpecification(
print: (_, __, ___, String line) => logPrint(line),
),
);
}
}
/// This class is returned if dartdoc fails in an expected way (for instance, if
/// there is an analysis error in the library).
class DartdocFailure {
final String message;
DartdocFailure(this.message);
@override
String toString() => message;
}
/// The results of a [Dartdoc.generateDocs] call.
class DartdocResults {
final PackageMeta packageMeta;
final PackageGraph packageGraph;
final Folder outDir;
DartdocResults(this.packageMeta, this.packageGraph, this.outDir);
}