From f733321fce165bbd3fee92a24a5d474042dbc4ab Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Mon, 12 Mar 2018 15:09:58 -0700 Subject: [PATCH 01/21] Fix or disable miscellaneous lints in dartdoc --- bin/dartdoc.dart | 28 +++++++++++----------------- lib/src/html/resource_loader.dart | 4 ++-- lib/src/io_utils.dart | 2 +- lib/src/markdown_processor.dart | 12 ++++++------ lib/src/model.dart | 6 +++--- test/compare_output_test.dart | 2 +- testing/test_package/lib/fake.dart | 16 ++++++++++++---- tool/doc_packages.dart | 14 +++++++------- 8 files changed, 43 insertions(+), 41 deletions(-) diff --git a/bin/dartdoc.dart b/bin/dartdoc.dart index 7fd31a94bf..bb7e9de144 100644 --- a/bin/dartdoc.dart +++ b/bin/dartdoc.dart @@ -144,7 +144,7 @@ main(List arguments) async { output['message'] = record.message; } - print(JSON.encode(output)); + print(json.encode(output)); }); } else { final stopwatch = new Stopwatch()..start(); @@ -311,29 +311,24 @@ ArgParser _createArgsParser() { help: 'Path to source directory.', defaultsTo: Directory.current.path); parser.addOption('output', help: 'Path to output directory.', defaultsTo: defaultOutDir); - parser.addOption('header', - allowMultiple: true, + parser.addMultiOption('header', splitCommas: true, help: 'paths to header files containing HTML text.'); - parser.addOption('footer', - allowMultiple: true, + parser.addMultiOption('footer', splitCommas: true, help: 'paths to footer files containing HTML text.'); - parser.addOption('footer-text', - allowMultiple: true, + parser.addMultiOption('footer-text', splitCommas: true, help: 'paths to footer-text files ' '(optional text next to the package name and version).'); - parser.addOption('exclude', - allowMultiple: true, splitCommas: true, help: 'Library names to ignore.'); - parser.addOption('exclude-packages', - allowMultiple: true, splitCommas: true, help: 'Package names to ignore.'); - parser.addOption('include', - allowMultiple: true, + parser.addMultiOption('exclude', + splitCommas: true, help: 'Library names to ignore.'); + parser.addMultiOption('exclude-packages', + splitCommas: true, help: 'Package names to ignore.'); + parser.addMultiOption('include', splitCommas: true, help: 'Library names to generate docs for.'); - parser.addOption('include-external', - allowMultiple: true, + parser.addMultiOption('include-external', help: 'Additional (external) dart files to include; use "dir/fileName", ' 'as in lib/material.dart.'); parser.addOption('hosted-url', @@ -353,10 +348,9 @@ ArgParser _createArgsParser() { help: 'Group libraries from the same package into categories.', negatable: false, defaultsTo: false); - parser.addOption('category-order', + parser.addMultiOption('category-order', help: 'A list of category names to place first when --use-categories is ' 'set. Unmentioned categories are sorted after these.', - allowMultiple: true, splitCommas: true); parser.addFlag('auto-include-dependencies', help: diff --git a/lib/src/html/resource_loader.dart b/lib/src/html/resource_loader.dart index 368665ce5d..2126e01cb2 100644 --- a/lib/src/html/resource_loader.dart +++ b/lib/src/html/resource_loader.dart @@ -11,7 +11,7 @@ library dartdoc.resource_loader; import 'dart:async' show Future; -import 'dart:convert' show UTF8; +import 'dart:convert' show utf8; import 'package:resource/resource.dart'; @@ -19,7 +19,7 @@ import 'package:resource/resource.dart'; Future loadAsString(String path) async { var bytes = await loadAsBytes(path); - return UTF8.decode(bytes); + return utf8.decode(bytes); } /// Loads a `package:` resource as an [List]. diff --git a/lib/src/io_utils.dart b/lib/src/io_utils.dart index 6554c1b22b..f99a69df22 100644 --- a/lib/src/io_utils.dart +++ b/lib/src/io_utils.dart @@ -77,7 +77,7 @@ class SubprocessLauncher { assert(prefix != null); if (filter == null) filter = (line) => [line]; stream - .transform(UTF8.decoder) + .transform(utf8.decoder) .transform(const LineSplitter()) .expand(filter) .listen((String line) { diff --git a/lib/src/markdown_processor.dart b/lib/src/markdown_processor.dart index 335de243a9..2be141840f 100644 --- a/lib/src/markdown_processor.dart +++ b/lib/src/markdown_processor.dart @@ -139,15 +139,15 @@ final RegExp notARealDocReference = new RegExp(r'''(^[^\w]|^[\d]|[,"'/]|^$)'''); final RegExp operatorPrefix = new RegExp(r'^operator[ ]*'); -final HtmlEscape htmlEscape = const HtmlEscape(HtmlEscapeMode.ELEMENT); +final HtmlEscape htmlEscape = const HtmlEscape(HtmlEscapeMode.element); final List _markdown_syntaxes = [ new _InlineCodeSyntax(), new _AutolinkWithoutScheme() -]..addAll(md.ExtensionSet.gitHub.inlineSyntaxes); +]..addAll(md.ExtensionSet.gitHubFlavored.inlineSyntaxes); final List _markdown_block_syntaxes = [] - ..addAll(md.ExtensionSet.gitHub.blockSyntaxes); + ..addAll(md.ExtensionSet.gitHubFlavored.blockSyntaxes); // Remove these schemas from the display text for hyperlinks. final RegExp _hide_schemes = new RegExp('^(http|https)://'); @@ -735,7 +735,7 @@ String _linkDocReference( // This would be linkedElement.linkedName, but link bodies are slightly // different for doc references. if (linkedElement.href == null) { - return '${HTML_ESCAPE.convert(label)}'; + return '${htmlEscape.convert(label)}'; } else { return '$label'; } @@ -744,7 +744,7 @@ String _linkDocReference( warnable.warn(PackageWarning.unresolvedDocReference, message: codeRef, referredFrom: warnable.documentationFrom); } - return '${HTML_ESCAPE.convert(label)}'; + return '${htmlEscape.convert(label)}'; } } @@ -992,7 +992,7 @@ class _InlineCodeSyntax extends md.InlineSyntax { @override bool onMatch(md.InlineParser parser, Match match) { - var element = new md.Element.text('code', HTML_ESCAPE.convert(match[1])); + var element = new md.Element.text('code', htmlEscape.convert(match[1])); parser.addNode(element); return true; } diff --git a/lib/src/model.dart b/lib/src/model.dart index 1a47583f39..e5d204505f 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -61,7 +61,7 @@ Map>>> get _crossdartJson { var crossdartFile = new File(p.join(config.inputDir.path, "crossdart.json")); if (crossdartFile.existsSync()) { - __crossdartJson = JSON.decode(crossdartFile.readAsStringSync()) + __crossdartJson = json.decode(crossdartFile.readAsStringSync()) as Map>>>; } else { __crossdartJson = {}; @@ -1544,7 +1544,7 @@ abstract class GetterSetterCombo implements ModelElement { String _buildConstantValueBase() { String result = constantInitializer?.toString() ?? ''; - return const HtmlEscape(HtmlEscapeMode.UNKNOWN).convert(result); + return const HtmlEscape(HtmlEscapeMode.unknown).convert(result); } String get constantValue => linkifyConstantValue(constantValueBase); @@ -3444,7 +3444,7 @@ abstract class ModelElement extends Canonicalization if (isPublicAndPackageDocumented) { warn(PackageWarning.noCanonicalFound); } - return HTML_ESCAPE.convert(name); + return htmlEscape.convert(name); } var classContent = isDeprecated ? ' class="deprecated"' : ''; diff --git a/test/compare_output_test.dart b/test/compare_output_test.dart index f682539b93..3a594d44e3 100644 --- a/test/compare_output_test.dart +++ b/test/compare_output_test.dart @@ -174,7 +174,7 @@ void main() { var jsonValues = LineSplitter .split(result.stdout) - .map((j) => JSON.decode(j) as Map) + .map((j) => json.decode(j) as Map) .toList(); expect(jsonValues, isNotEmpty, diff --git a/testing/test_package/lib/fake.dart b/testing/test_package/lib/fake.dart index 8ebb76963b..02713f33ae 100644 --- a/testing/test_package/lib/fake.dart +++ b/testing/test_package/lib/fake.dart @@ -47,13 +47,10 @@ library fake; import 'dart:async'; - import 'dart:collection'; -import 'example.dart'; - import 'css.dart' as css; - +import 'example.dart'; import 'two_exports.dart' show BaseClass; abstract class ImplementingThingy implements BaseThingy {} @@ -224,6 +221,7 @@ typedef int LotsAndLotsOfParameters(so, many, parameters, it, should, wrap, /// This class is cool! class Cool { + // ignore: missing_return Cool returnCool() {} } @@ -258,7 +256,9 @@ class SuperAwesomeClass { /// /// Another comment line. void fly(int height, Cool superCool, {String msg}) { + // ignore: unused_local_variable, avoid_init_to_null var x = null; + // ignore: unused_local_variable int i, y; for (int z = 0; z < 100; z++) { print('hi'); @@ -372,6 +372,7 @@ class ClassWithUnusualProperties extends ImplicitProperties { /// /// The rest of this is not in the first paragraph. @Annotation('value') +// ignore: deprecated_member_use class LongFirstLine extends SuperAwesomeClass with MixMeIn implements Interface, AnotherInterface { @@ -621,14 +622,18 @@ class HasGenericWithExtends {} /// Extends [ListBase] class SpecialList extends ListBase { + // ignore: annotate_overrides E operator [](int index) { return null; } + // ignore: annotate_overrides int get length => 0; + // ignore: annotate_overrides void set length(int length) {} + // ignore: annotate_overrides void operator []=(int index, E value) {} } @@ -648,6 +653,7 @@ class BaseForDocComments { /// /// Reference to another method in this class [anotherMethod] xx /// + // ignore: deprecated_member_use /// Reference to a top-level function in this library [topLevelFunction] xx /// /// Reference to a top-level function in another library that is imported into this library (example lib) [function1] xx @@ -743,6 +749,7 @@ class ReferringClass { abstract class MIEEMixinWithOverride = MIEEBase with _MIEEPrivateOverride; abstract class _MIEEPrivateOverride implements MIEEThing { + // ignore: annotate_overrides void operator[]=(K key, V value) { throw new UnsupportedError("Never use this"); } @@ -751,6 +758,7 @@ abstract class _MIEEPrivateOverride implements MIEEThing { abstract class MIEEBase extends MIEEMixin {} abstract class MIEEMixin implements MIEEThing { + // ignore: annotate_overrides operator []=(K key, V value); } diff --git a/tool/doc_packages.dart b/tool/doc_packages.dart index 63d4066ffb..0c31e56c52 100644 --- a/tool/doc_packages.dart +++ b/tool/doc_packages.dart @@ -6,7 +6,7 @@ library dartdoc.doc_packages; import 'dart:async'; -import 'dart:convert' show JSON, UTF8; +import 'dart:convert' show json, utf8; import 'dart:io'; import 'package:args/args.dart'; @@ -125,17 +125,17 @@ Future> _packageUrls(int page) { return http .get('https://pub.dartlang.org/packages.json?page=${page}') .then((response) { - return new List.from(JSON.decode(response.body)['packages']); + return new List.from(json.decode(response.body)['packages']); }); } Future> _getPackageInfos(List packageUrls) { var futures = packageUrls.map((String p) { return http.get(p).then((response) { - var json = JSON.decode(response.body); - String name = json['name']; + var decodedJson = json.decode(response.body); + String name = decodedJson['name']; List versions = new List.from( - json['versions'].map((v) => new Version.parse(v))); + decodedJson['versions'].map((v) => new Version.parse(v))); return new PackageInfo(name, Version.primary(versions)); }); }).toList(); @@ -200,8 +200,8 @@ Future _exec(String command, List args, .start(command, args, workingDirectory: cwd) .then((Process process) { if (!quiet) { - process.stdout.listen((bytes) => _log(UTF8.decode(bytes))); - process.stderr.listen((bytes) => _log(UTF8.decode(bytes))); + process.stdout.listen((bytes) => _log(utf8.decode(bytes))); + process.stderr.listen((bytes) => _log(utf8.decode(bytes))); } Future f = process.exitCode.then((code) { From 6fedd10ee263f4e6cc90b173cc6e8658199cc447 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 12:55:50 -0700 Subject: [PATCH 02/21] Clean up a few more lints. --- test/model_test.dart | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/test/model_test.dart b/test/model_test.dart index 60329f4ecc..5da284d534 100644 --- a/test/model_test.dart +++ b/test/model_test.dart @@ -1172,11 +1172,8 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, }); test('typedef params have proper signature', () { - // typedef void VoidCallback(); - // void addCallback(VoidCallback callback) { } ModelFunction function = fakeLibrary.functions.firstWhere((f) => f.name == 'addCallback'); - ElementType t = function.parameters.first.modelType; String params = function.linkedParams(); expect( params, @@ -1184,8 +1181,6 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, 'VoidCallback ' 'callback'); - // typedef int Callback2(String); - // void addCallback2(Callback2 callback) { } function = fakeLibrary.functions.firstWhere((f) => f.name == 'addCallback2'); params = function.linkedParams(); @@ -1216,7 +1211,6 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, .singleWhere((f) => f.name == 'explicitSetter'); // TODO(jcollins-g): really, these shouldn't be called "parameters" in // the span class. - ElementType t = explicitSetter.modelType; expect(explicitSetter.linkedReturnType, 'dynamic Function(int, Cool, List<int>)'); }); @@ -1293,7 +1287,6 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, Method aTypedefReturningMethodInterface = TemplatedInterface .allInstanceMethods .singleWhere((m) => m.name == 'aTypedefReturningMethodInterface'); - ElementType mt = aTypedefReturningMethodInterface.modelType; expect(aTypedefReturningMethodInterface.linkedReturnType, 'ParameterizedTypedef<List<String>>'); }); @@ -2240,7 +2233,6 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, }); test('anonymous nested functions inside typedefs are handled', () { - ElementType t = aComplexTypedef.modelType; expect(aComplexTypedef, isNotNull); expect(aComplexTypedef.linkedReturnType, startsWith('Function')); expect(aComplexTypedef.nameWithGenerics, @@ -2371,13 +2363,11 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, }); test('typedef param is linked and does not include types', () { - ElementType t = methodWithTypedefParam.parameters.first.modelType; var params = methodWithTypedefParam.linkedParams(); expect( params, equals( 'processMessage p')); - //expect(params, contains('')); }); }); From a32fd9819bbb16445a34905a146ade945e220ff3 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 12:37:22 -0700 Subject: [PATCH 03/21] Rename category to package in all remaining references --- bin/dartdoc.dart | 18 +++++++++++---- lib/dartdoc.dart | 4 ++-- lib/src/config.dart | 8 +++---- lib/src/html/html_generator.dart | 4 ++-- lib/src/html/template_data.dart | 6 ++--- lib/src/model.dart | 39 +++++++++++++++++--------------- lib/src/package_meta.dart | 12 +++++----- lib/src/warnings.dart | 6 ++--- lib/templates/index.html | 28 +++++++++++------------ lib/templates/library.html | 12 +++++----- pubspec.lock | 2 +- test/model_test.dart | 14 ++++++------ 12 files changed, 82 insertions(+), 71 deletions(-) diff --git a/bin/dartdoc.dart b/bin/dartdoc.dart index bb7e9de144..64dfc45dc6 100644 --- a/bin/dartdoc.dart +++ b/bin/dartdoc.dart @@ -190,7 +190,7 @@ main(List arguments) async { PackageMeta packageMeta = sdkDocs ? new PackageMeta.fromSdk(sdkDir, - sdkReadmePath: readme, useCategories: args['use-categories']) + sdkReadmePath: readme, displayAsPackages: args['use-categories'] || args['display-as-packages']) : new PackageMeta.fromDir(inputDir); if (!packageMeta.isValid) { @@ -217,7 +217,7 @@ main(List arguments) async { footerFilePaths: footerFilePaths, footerTextFilePaths: footerTextFilePaths, faviconPath: args['favicon'], - useCategories: args['use-categories'], + displayAsPackages: args['use-categories'], prettyIndexJson: args['pretty-index-json']); for (var generator in generators) { @@ -257,7 +257,7 @@ main(List arguments) async { inputDir: inputDir, sdkVersion: sdk.sdkVersion, autoIncludeDependencies: args['auto-include-dependencies'], - categoryOrder: args['category-order'], + packageOrder: args['package-order'].isEmpty ? args['category-order'] : args['package-order'], reexportMinConfidence: double.parse(args['ambiguous-reexport-scorer-min-confidence']), verboseWarnings: args['verbose-warnings'], @@ -345,11 +345,19 @@ ArgParser _createArgsParser() { parser.addOption('favicon', help: 'A path to a favicon for the generated docs.'); parser.addFlag('use-categories', - help: 'Group libraries from the same package into categories.', + help: 'Group libraries from the same package in the libraries sidebar. (deprecated, replaced by display-as-packages)', + negatable: false, + defaultsTo: false); + parser.addFlag('display-as-packages', + help: 'Group libraries from the same package in the libraries sidebar.', negatable: false, defaultsTo: false); parser.addMultiOption('category-order', - help: 'A list of category names to place first when --use-categories is ' + help: 'A list of category names to place first when --display-as-packages is ' + 'set. Unmentioned categories are sorted after these. (deprecated, replaced by package-order)', + splitCommas: true); + parser.addMultiOption('package-order', + help: 'A list of category names to place first when --display-as-packages is ' 'set. Unmentioned categories are sorted after these.', splitCommas: true); parser.addFlag('auto-include-dependencies', diff --git a/lib/dartdoc.dart b/lib/dartdoc.dart index 4ddaf91a89..1d1c0f7db9 100644 --- a/lib/dartdoc.dart +++ b/lib/dartdoc.dart @@ -46,14 +46,14 @@ Future> initGenerators(String url, String relCanonicalPrefix, List footerFilePaths, List footerTextFilePaths, String faviconPath, - bool useCategories: false, + bool displayAsPackages: false, bool prettyIndexJson: false}) async { var options = new HtmlGeneratorOptions( url: url, relCanonicalPrefix: relCanonicalPrefix, toolVersion: version, faviconPath: faviconPath, - useCategories: useCategories, + displayAsPackages: displayAsPackages, prettyIndexJson: prettyIndexJson); return [ diff --git a/lib/src/config.dart b/lib/src/config.dart index 95335371cb..ae08e10796 100644 --- a/lib/src/config.dart +++ b/lib/src/config.dart @@ -14,7 +14,7 @@ class Config { final bool includeSource; final String sdkVersion; final bool autoIncludeDependencies; - final List categoryOrder; + final List packageOrder; final double reexportMinConfidence; final bool verboseWarnings; final List dropTextFrom; @@ -28,7 +28,7 @@ class Config { this.includeSource, this.sdkVersion, this.autoIncludeDependencies, - this.categoryOrder, + this.packageOrder, this.reexportMinConfidence, this.verboseWarnings, this.dropTextFrom, @@ -47,7 +47,7 @@ void setConfig( bool includeSource: true, String sdkVersion, bool autoIncludeDependencies: false, - List categoryOrder, + List packageOrder, double reexportMinConfidence: 0.1, bool verboseWarnings: true, List dropTextFrom, @@ -61,7 +61,7 @@ void setConfig( includeSource, sdkVersion, autoIncludeDependencies, - categoryOrder ?? const [], + packageOrder ?? const [], reexportMinConfidence, verboseWarnings, dropTextFrom ?? const [], diff --git a/lib/src/html/html_generator.dart b/lib/src/html/html_generator.dart index cbe1385410..d8916ffa9b 100644 --- a/lib/src/html/html_generator.dart +++ b/lib/src/html/html_generator.dart @@ -116,7 +116,7 @@ class HtmlGeneratorOptions implements HtmlOptions { final bool prettyIndexJson; @override - final bool useCategories; + final bool displayAsPackages; @override final String relCanonicalPrefix; @@ -129,7 +129,7 @@ class HtmlGeneratorOptions implements HtmlOptions { this.relCanonicalPrefix, this.faviconPath, String toolVersion, - this.useCategories: false, + this.displayAsPackages: false, this.prettyIndexJson: false}) : this.toolVersion = toolVersion ?? 'unknown'; } diff --git a/lib/src/html/template_data.dart b/lib/src/html/template_data.dart index 05e57ecabf..badb39a22b 100644 --- a/lib/src/html/template_data.dart +++ b/lib/src/html/template_data.dart @@ -7,7 +7,7 @@ import '../model.dart'; abstract class HtmlOptions { String get relCanonicalPrefix; String get toolVersion; - bool get useCategories; + bool get displayAsPackages; } class Subnav { @@ -63,7 +63,7 @@ abstract class TemplateData { T get self; String get version => htmlOptions.toolVersion; String get relCanonicalPrefix => htmlOptions.relCanonicalPrefix; - bool get useCategories => htmlOptions.useCategories; + bool get displayAsPackages => htmlOptions.displayAsPackages; Iterable getSubNavItems() => []; @@ -113,7 +113,7 @@ class PackageTemplateData extends TemplateData { String get homepage => packageGraph.homepage; @override - String get kind => (useCategories || packageGraph.isSdk) ? '' : 'package'; + String get kind => (displayAsPackages || packageGraph.isSdk) ? '' : 'package'; /// `null` for packages because they are at the root – not needed @override diff --git a/lib/src/model.dart b/lib/src/model.dart index f0f0d112b5..5653b0f238 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -3991,9 +3991,9 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { warningMessage = "library says it is {@canonicalFor ${message}} but ${message} can't be canonical there"; break; - case PackageWarning.categoryOrderGivesMissingPackageName: + case PackageWarning.packageOrderGivesMissingPackageName: warningMessage = - "--category-order gives invalid package name: '${message}'"; + "--package-order gives invalid package name: '${message}'"; break; case PackageWarning.unresolvedDocReference: warningMessage = "unresolved doc reference [${message}]"; @@ -4063,17 +4063,20 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { return locatable.fullyQualifiedName.replaceFirst(':', '-'); } - List get categories { - // Help the user if they pass us a category that doesn't exist. - for (String categoryName in config.categoryOrder) { - if (!packages.containsKey(categoryName)) - warnOnElement(null, PackageWarning.categoryOrderGivesMissingPackageName, - message: "${categoryName}, categories: ${packages.keys.join(',')}"); + List _publicPackages; + List get publicPackages { + if (_publicPackages == null) { + // Help the user if they pass us a package that doesn't exist. + for (String packageName in config.packageOrder) { + if (!packages.containsKey(packageName)) + warnOnElement(null, PackageWarning.packageOrderGivesMissingPackageName, + message: "${packageName}, packages: ${packages.keys.join(',')}"); + } + _publicPackages = packages.values + .where((p) => p.libraries.any((l) => l.isPublic)) + .toList()..sort(); } - List publicPackages = packages.values - .where((p) => p.libraries.any((l) => l.isPublic)) - .toList(); - return publicPackages..sort(); + return _publicPackages; } Map> _libraryElementReexportedBy = new Map(); @@ -4200,7 +4203,7 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { String get name => packageMeta.name; String get kind => - (packageMeta.useCategories || packageGraph.isSdk) ? '' : 'package'; + (packageMeta.displayAsPackages || packageGraph.isSdk) ? '' : 'package'; @override String get oneLineDoc => ''; @@ -4492,14 +4495,14 @@ class Package implements Comparable { String toString() => name; /// Returns: - /// -1 if this category is listed in --category-order. - /// 0 if this category is the original package we are documenting. + /// -1 if this package is listed in --package-order. + /// 0 if this package is the original package we are documenting. /// 1 if this group represents the Dart SDK. /// 2 if this group has a name that contains the name of the original /// package we are documenting. /// 3 otherwise. int get _group { - if (config.categoryOrder.contains(name)) return -1; + if (config.packageOrder.contains(name)) return -1; if (name.toLowerCase() == packageGraph.name.toLowerCase()) return 0; if (name == "Dart Core") return 1; if (name.toLowerCase().contains(packageGraph.name.toLowerCase())) return 2; @@ -4510,8 +4513,8 @@ class Package implements Comparable { int compareTo(Package other) { if (_group == other._group) { if (_group == -1) { - return Comparable.compare(config.categoryOrder.indexOf(name), - config.categoryOrder.indexOf(other.name)); + return Comparable.compare(config.packageOrder.indexOf(name), + config.packageOrder.indexOf(other.name)); } else { return name.toLowerCase().compareTo(other.name.toLowerCase()); } diff --git a/lib/src/package_meta.dart b/lib/src/package_meta.dart index b14c007f00..e8f2739d72 100644 --- a/lib/src/package_meta.dart +++ b/lib/src/package_meta.dart @@ -13,15 +13,15 @@ import 'logging.dart'; abstract class PackageMeta { final Directory dir; - final bool useCategories; + final bool displayAsPackages; - PackageMeta(this.dir, {this.useCategories: false}); + PackageMeta(this.dir, {this.displayAsPackages: false}); factory PackageMeta.fromDir(Directory dir) => new _FilePackageMeta(dir); factory PackageMeta.fromSdk(Directory sdkDir, - {String sdkReadmePath, bool useCategories}) => + {String sdkReadmePath, bool displayAsPackages}) => new _SdkMeta(sdkDir, - sdkReadmePath: sdkReadmePath, useCategories: useCategories); + sdkReadmePath: sdkReadmePath, displayAsPackages: displayAsPackages); bool get isSdk; bool get needsPubGet => false; @@ -186,8 +186,8 @@ File _locate(Directory dir, List fileNames) { class _SdkMeta extends PackageMeta { final String sdkReadmePath; - _SdkMeta(Directory dir, {this.sdkReadmePath, bool useCategories}) - : super(dir, useCategories: useCategories); + _SdkMeta(Directory dir, {this.sdkReadmePath, bool displayAsPackages}) + : super(dir, displayAsPackages: displayAsPackages); @override bool get isSdk => true; diff --git a/lib/src/warnings.dart b/lib/src/warnings.dart index 77d8c4c710..fd30576749 100644 --- a/lib/src/warnings.dart +++ b/lib/src/warnings.dart @@ -52,8 +52,8 @@ final Map packageWarningText = const { PackageWarning.noLibraryLevelDocs, "no-library-level-docs", "There are no library level docs for this library"), - PackageWarning.categoryOrderGivesMissingPackageName: const PackageWarningHelpText( - PackageWarning.categoryOrderGivesMissingPackageName, + PackageWarning.packageOrderGivesMissingPackageName: const PackageWarningHelpText( + PackageWarning.packageOrderGivesMissingPackageName, "category-order-gives-missing-package-name", "The category-order flag on the command line was given the name of a nonexistent package"), PackageWarning.unresolvedDocReference: const PackageWarningHelpText( @@ -117,7 +117,7 @@ enum PackageWarning { ignoredCanonicalFor, noCanonicalFound, noLibraryLevelDocs, - categoryOrderGivesMissingPackageName, + packageOrderGivesMissingPackageName, unresolvedDocReference, unknownMacro, brokenLink, diff --git a/lib/templates/index.html b/lib/templates/index.html index fa12a1f4c9..56066b3f55 100644 --- a/lib/templates/index.html +++ b/lib/templates/index.html @@ -3,26 +3,26 @@
@@ -30,8 +30,8 @@
{{self.name}} {{self.kind}}
{{>documentation}} {{/packageGraph}} - {{#useCategories}} - {{#packageGraph.categories}} + {{#displayAsPackages}} + {{#packageGraph.publicPackages}}

{{name}}

@@ -45,11 +45,11 @@

{{name}}

{{/libraries}}
- {{/packageGraph.categories}} + {{/packageGraph.publicPackages}} - {{/useCategories}} + {{/displayAsPackages}} - {{^useCategories}} + {{^displayAsPackages}}

Libraries

@@ -63,7 +63,7 @@

Libraries

{{/packageGraph.publicLibraries}}
- {{/useCategories}} + {{/displayAsPackages}}
diff --git a/lib/templates/library.html b/lib/templates/library.html index ec14b7795b..951611fc7b 100644 --- a/lib/templates/library.html +++ b/lib/templates/library.html @@ -2,25 +2,25 @@
diff --git a/pubspec.lock b/pubspec.lock index 24097f014d..2b01741fee 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -408,4 +408,4 @@ packages: source: hosted version: "2.1.13" sdks: - dart: ">=2.0.0-dev.23.0 <=2.0.0-dev.36.0" + dart: ">=2.0.0-dev.23.0 <=2.0.0-dev.38.0" diff --git a/test/model_test.dart b/test/model_test.dart index 5da284d534..149df8eb50 100644 --- a/test/model_test.dart +++ b/test/model_test.dart @@ -66,23 +66,23 @@ void main() { }); test('categories', () { - expect(packageGraph.categories, hasLength(1)); + expect(packageGraph.publicPackages, hasLength(1)); - Package category = packageGraph.categories.first; + Package category = packageGraph.publicPackages.first; expect(category.name, 'test_package'); expect(category.libraries, hasLength(8)); }); test('multiple categories, sorted default', () { - expect(ginormousPackageGraph.categories, hasLength(3)); - expect(ginormousPackageGraph.categories.first.name, + expect(ginormousPackageGraph.publicPackages, hasLength(3)); + expect(ginormousPackageGraph.publicPackages.first.name, equals('test_package')); }); test('multiple categories, specified sort order', () { - setConfig(categoryOrder: ['meta', 'test_package']); - expect(ginormousPackageGraph.categories, hasLength(3)); - expect(ginormousPackageGraph.categories.first.name, equals('meta')); + setConfig(packageOrder: ['meta', 'test_package']); + expect(ginormousPackageGraph.publicPackages, hasLength(3)); + expect(ginormousPackageGraph.publicPackages.first.name, equals('meta')); }); test('is documented in library', () { From b59a4df2a0154c421380b650153ad21507128cf9 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 12:37:49 -0700 Subject: [PATCH 04/21] dartfmt --- lib/src/model.dart | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/src/model.dart b/lib/src/model.dart index 5653b0f238..9be0f9b5f5 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -4069,12 +4069,14 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { // Help the user if they pass us a package that doesn't exist. for (String packageName in config.packageOrder) { if (!packages.containsKey(packageName)) - warnOnElement(null, PackageWarning.packageOrderGivesMissingPackageName, + warnOnElement( + null, PackageWarning.packageOrderGivesMissingPackageName, message: "${packageName}, packages: ${packages.keys.join(',')}"); } _publicPackages = packages.values .where((p) => p.libraries.any((l) => l.isPublic)) - .toList()..sort(); + .toList() + ..sort(); } return _publicPackages; } From bc64d2c619cee4ee5a4de51e2b17262ad2c20ecb Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 13:10:21 -0700 Subject: [PATCH 05/21] Review comments --- pubspec.lock | 2 +- pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index 24097f014d..2b01741fee 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -408,4 +408,4 @@ packages: source: hosted version: "2.1.13" sdks: - dart: ">=2.0.0-dev.23.0 <=2.0.0-dev.36.0" + dart: ">=2.0.0-dev.23.0 <=2.0.0-dev.38.0" diff --git a/pubspec.yaml b/pubspec.yaml index 1c3118b354..0b74dcfed5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -7,7 +7,7 @@ homepage: https://github.com/dart-lang/dartdoc # For development, recommend 1.25.0-dev.0.0 or higher to allow # dartanalyzer to work on dartdoc itself. environment: - sdk: '>=1.23.0-dev.11.5 <2.0.0' + sdk: '>=2.0.0-dev.9.0 <3.0.0' dependencies: analyzer: '0.31.2-alpha.0' args: '>=0.13.0 <2.0.0' From 6afc18ba369609a9276f171ce757484996e92e37 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 10:23:20 -0700 Subject: [PATCH 06/21] Intermediate state --- lib/src/config.dart | 33 ++++++++ lib/src/dartdoc_options.dart | 148 +++++++++++++++++++++++++++++++++++ lib/src/model.dart | 75 +++++++++++++++++- 3 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 lib/src/dartdoc_options.dart diff --git a/lib/src/config.dart b/lib/src/config.dart index ae08e10796..4e48af1322 100644 --- a/lib/src/config.dart +++ b/lib/src/config.dart @@ -6,6 +6,39 @@ library dartdoc.config; import 'dart:io'; +import 'package:analyzer/dart/element/element.dart'; +import 'package:dartdoc/dartdoc.dart'; +import 'package:path/path.dart' as p; + +import 'model.dart'; + +/// Class representing values possibly local to a particular [ModelElement]. +class LocalConfig { + final Map> categoryMap; + final PackageMeta packageMeta; + + LocalConfig._(this.categoryMap, this.packageMeta); + + factory LocalConfig.fromLibrary(LibraryElement element) { + return new LocalConfig._({}, getPackageMeta(element)); + } + + static PackageMeta getPackageMeta(LibraryElement element) { + String sourcePath = element.source.fullName; + File file = new File(p.canonicalize(sourcePath)); + Directory dir = file.parent; + while (dir.parent.path != dir.path && dir.existsSync()) { + File pubspec = new File(p.join(dir.path, 'pubspec.yaml')); + if (pubspec.existsSync()) { + return new PackageMeta.fromDir(dir); + } + dir = dir.parent; + } + return null; + } + +} + class Config { final Directory inputDir; final bool showWarnings; diff --git a/lib/src/dartdoc_options.dart b/lib/src/dartdoc_options.dart new file mode 100644 index 0000000000..f311f238f2 --- /dev/null +++ b/lib/src/dartdoc_options.dart @@ -0,0 +1,148 @@ +// 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. + +library dartdoc.dartdoc_options; + +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:yaml/yaml.dart'; + +import 'logging.dart'; + + +Map _dartdocOptionsCache = {}; + +/// dartdoc_options.yaml handling. +abstract class DartdocOptions { + /// The parent of this DartdocOptions object, or null if there is none. + final DartdocOptions parent; + + DartdocOptions(this.parent); + + /// Path to the dartdoc options file, or '' if this object is the + /// default setting. Intended for printing only. + String get _path; + + /// A map of library name to subcategory name. + Map get subCategoryMap; + + /// A list indicating the preferred subcategory sorting order. + List get subCategoryOrder; + + factory DartdocOptions.fromDir(Directory dir) { + if (!_dartdocOptionsCache.containsKey(dir.absolute.path)) { + _dartdocOptionsCache[dir.absolute.path] = new DartdocOptions._fromDir(dir); + } + return _dartdocOptionsCache[dir.absolute.path]; + } + + /// Search for a dartdoc_options file in this and parent directories. + /// Refuses to cross a package boundary (demarcated by pubspec.yaml). + factory DartdocOptions._fromDir(Directory dir) { + if (!dir.existsSync()) return new _DefaultDartdocOptions(); + + File f, pb; + dir = dir.absolute; + + while(true) { + f = new File(p.join(dir.path, 'dartdoc_options.yaml')); + pb = new File(p.join(dir.path, 'pubspec.yaml')); + if (f.existsSync() || pb.existsSync() || dir.parent.path == dir.path) + break; + dir = dir.parent.absolute; + } + + DartdocOptions parent; + if (dir.parent.path != dir.path && !pb.existsSync()) { + parent = new DartdocOptions.fromDir(dir.parent); + } else { + parent = new _DefaultDartdocOptions(); + } + if (f.existsSync()) { + return new _FileDartdocOptions(parent, f); + } + return parent; + } +} + +class _DefaultDartdocOptions extends DartdocOptions { + _DefaultDartdocOptions() : super(null); + + @override + String get _path => ''; + + @override + Map get subCategoryMap => new Map.unmodifiable({}); + + @override + List get subCategoryOrder => new List.unmodifiable([]); +} + +class _FileDartdocOptions extends DartdocOptions { + File dartdocOptionsFile; + Map _dartdocOptions; + _FileDartdocOptions(DartdocOptions parent, this.dartdocOptionsFile) : super(parent) { + Map allDartdocOptions = loadYaml(dartdocOptionsFile.readAsStringSync()); + if (allDartdocOptions.containsKey('dartdoc')) { + _dartdocOptions = allDartdocOptions['dartdoc']; + } else { + _dartdocOptions = {}; + logWarning("${dartdocOptionsFile.path}: must contain 'dartdoc' section"); + } + } + + @override + String get _path => dartdocOptionsFile.path; + + List _subCategoryOrder; + @override + /// subCategoryOrder overrides parents. + List get subCategoryOrder { + if (_subCategoryOrder == null) { + _subCategoryOrder = []; + if (_dartdocOptions.containsKey('subCategoryOrder')) { + if (_dartdocOptions['subCategoryOrder'] is YamlList) { + if (parent.subCategoryOrder.isNotEmpty) { + logWarning('${dartdocOptionsFile.path}: subCategoryOrder can not override from ${parent._path}'); + } else { + _subCategoryOrder.addAll(_dartdocOptions['subCategoryOrder']); + } + } else { + logWarning("${dartdocOptionsFile.path}: subCategoryOrder must be a list (ignoring)"); + _subCategoryOrder = parent.subCategoryOrder; + } + } else { + _subCategoryOrder = parent.subCategoryOrder; + } + _subCategoryOrder = new List.unmodifiable(_subCategoryOrder); + } + return _subCategoryOrder; + } + + List _allSubCategories; + List allSubCategories; + Map _subCategoryMap; + @override + /// subCategoryMap adds to parents. + Map get subCategoryMap { + if (_subCategoryMap == null) { + _subCategoryMap = new Map(); + if (parent != null) _subCategoryMap.addAll(parent.subCategoryMap); + if (_dartdocOptions.containsKey('subcategories')) { + for (String key in _dartdocOptions['subcategories'].keys()) { + if (_dartdocOptions['subcategories'][key] is YamlList) { + for (var value in _dartdocOptions['subcategories'][key]) { + _subCategoryMap[value] = key; + } + } else { + logWarning('${dartdocOptionsFile.path}: subcategory "$key" must be a list (ignoring)'); + } + } + } + _subCategoryMap = new Map.unmodifiable(_subCategoryMap); + } + return _subCategoryMap; + } +} \ No newline at end of file diff --git a/lib/src/model.dart b/lib/src/model.dart index 9be0f9b5f5..61c18991bd 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -36,6 +36,7 @@ import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember, Member, ParameterMember; import 'package:analyzer/src/dart/analysis/driver.dart'; import 'package:collection/collection.dart'; +import 'package:dartdoc/src/dartdoc_options.dart'; import 'package:dartdoc/src/io_utils.dart'; import 'package:front_end/src/byte_store/byte_store.dart'; import 'package:front_end/src/base/performance_logger.dart'; @@ -1760,6 +1761,7 @@ class Library extends ModelElement { .toList(growable: false); } + SdkLibrary get sdkLib { if (packageGraph.sdkLibrarySources.containsKey(element.librarySource)) { return packageGraph.sdkLibrarySources[element.librarySource]; @@ -4482,17 +4484,88 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { } } +class SubCategory implements Comparable { + Package package; + final String name; + final List libraries; + + SubCategory(this.name, this.package, this.libraries) {} + + static List buildSubCategories(Package package) { + Map> libraryLists; + for (Library lib in package.libraries) { + + } + } + + + Iterable get publicLibraries => filterNonPublic(libraries); +} + class Package implements Comparable { final String name; + + // Initialized by [PackageGraph.PackageGraph]. final List _libraries = []; PackageGraph packageGraph; Package(this.name, this.packageGraph); + + DartdocOptions _dartdocOptions; + DartdocOptions get dartdocOptions { + if (_dartdocOptions == null) { + _dartdocOptions = new DartdocOptions.fromDir(new Directory(packagePath)); + } + return _dartdocOptions; + } + + bool get isSdk => packageMeta.isSdk; + + String _packagePath; + String get packagePath { + if (_packagePath == null) { + if (isSdk) { + _packagePath = packageMeta.resolvedDir; + } else { + assert(_libraries.isNotEmpty); + File file = new File(p.canonicalize(_libraries.first.element.source.fullName)); + Directory dir = file.parent; + while (dir.parent.path != dir.path && dir.existsSync()) { + File pubspec = new File(p.join(dir.path, 'pubspec.yaml')); + if (pubspec.existsSync()) { + _packagePath = dir.absolute.path; + break; + } + dir = dir.parent; + } + } + } + return _packagePath; + } + List get libraries => _libraries; Iterable get publicLibraries => filterNonPublic(libraries); + PackageMeta _packageMeta; + // TODO(jcollins-g): packageMeta should be passed in with the object rather + // than calculated indirectly from libraries. + PackageMeta get packageMeta { + if (_packageMeta == null) { + _packageMeta = _libraries.first.packageMeta; + } + return _packageMeta; + } + + List _subCategories; + List get subCategories { + if (_subCategories == null) { + + } + return _subCategories; + } + @override String toString() => name; @@ -4905,7 +4978,7 @@ class TypeParameter extends ModelElement { String toString() => element.name; } -/// Everything you need to instantiate a Package object for documenting. +/// Everything you need to instantiate a PackageGraph object for documenting. class PackageBuilder { final bool autoIncludeDependencies; final List excludes; From 3ee7464284289acb92849d355a61b7829db2327e Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 15:03:03 -0700 Subject: [PATCH 07/21] basic dartdoc options now working --- lib/src/dartdoc_options.dart | 65 ++++++------------------ lib/src/model.dart | 30 +----------- test/dartdoc_options_test.dart | 90 ++++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+), 78 deletions(-) create mode 100644 test/dartdoc_options_test.dart diff --git a/lib/src/dartdoc_options.dart b/lib/src/dartdoc_options.dart index f311f238f2..e55a93b22a 100644 --- a/lib/src/dartdoc_options.dart +++ b/lib/src/dartdoc_options.dart @@ -25,11 +25,8 @@ abstract class DartdocOptions { /// default setting. Intended for printing only. String get _path; - /// A map of library name to subcategory name. - Map get subCategoryMap; - /// A list indicating the preferred subcategory sorting order. - List get subCategoryOrder; + List get categoryOrder; factory DartdocOptions.fromDir(Directory dir) { if (!_dartdocOptionsCache.containsKey(dir.absolute.path)) { @@ -74,10 +71,7 @@ class _DefaultDartdocOptions extends DartdocOptions { String get _path => ''; @override - Map get subCategoryMap => new Map.unmodifiable({}); - - @override - List get subCategoryOrder => new List.unmodifiable([]); + List get categoryOrder => new List.unmodifiable([]); } class _FileDartdocOptions extends DartdocOptions { @@ -96,53 +90,24 @@ class _FileDartdocOptions extends DartdocOptions { @override String get _path => dartdocOptionsFile.path; - List _subCategoryOrder; + List _categoryOrder; @override - /// subCategoryOrder overrides parents. - List get subCategoryOrder { - if (_subCategoryOrder == null) { - _subCategoryOrder = []; - if (_dartdocOptions.containsKey('subCategoryOrder')) { - if (_dartdocOptions['subCategoryOrder'] is YamlList) { - if (parent.subCategoryOrder.isNotEmpty) { - logWarning('${dartdocOptionsFile.path}: subCategoryOrder can not override from ${parent._path}'); - } else { - _subCategoryOrder.addAll(_dartdocOptions['subCategoryOrder']); - } + /// categoryOrder overrides parents. + List get categoryOrder { + if (_categoryOrder == null) { + _categoryOrder = []; + if (_dartdocOptions.containsKey('categoryOrder')) { + if (_dartdocOptions['categoryOrder'] is YamlList) { + _categoryOrder.addAll(_dartdocOptions['categoryOrder']); } else { - logWarning("${dartdocOptionsFile.path}: subCategoryOrder must be a list (ignoring)"); - _subCategoryOrder = parent.subCategoryOrder; + logWarning("${dartdocOptionsFile.path}: categoryOrder must be a list (ignoring)"); + _categoryOrder = parent.categoryOrder; } } else { - _subCategoryOrder = parent.subCategoryOrder; - } - _subCategoryOrder = new List.unmodifiable(_subCategoryOrder); - } - return _subCategoryOrder; - } - - List _allSubCategories; - List allSubCategories; - Map _subCategoryMap; - @override - /// subCategoryMap adds to parents. - Map get subCategoryMap { - if (_subCategoryMap == null) { - _subCategoryMap = new Map(); - if (parent != null) _subCategoryMap.addAll(parent.subCategoryMap); - if (_dartdocOptions.containsKey('subcategories')) { - for (String key in _dartdocOptions['subcategories'].keys()) { - if (_dartdocOptions['subcategories'][key] is YamlList) { - for (var value in _dartdocOptions['subcategories'][key]) { - _subCategoryMap[value] = key; - } - } else { - logWarning('${dartdocOptionsFile.path}: subcategory "$key" must be a list (ignoring)'); - } - } + _categoryOrder = parent.categoryOrder; } - _subCategoryMap = new Map.unmodifiable(_subCategoryMap); + _categoryOrder = new List.unmodifiable(_categoryOrder); } - return _subCategoryMap; + return _categoryOrder; } } \ No newline at end of file diff --git a/lib/src/model.dart b/lib/src/model.dart index 61c18991bd..e59b0f3da3 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -38,6 +38,7 @@ import 'package:analyzer/src/dart/analysis/driver.dart'; import 'package:collection/collection.dart'; import 'package:dartdoc/src/dartdoc_options.dart'; import 'package:dartdoc/src/io_utils.dart'; +import 'package:dartdoc/src/sdk.dart'; import 'package:front_end/src/byte_store/byte_store.dart'; import 'package:front_end/src/base/performance_logger.dart'; import 'package:path/path.dart' as p; @@ -4484,24 +4485,6 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { } } -class SubCategory implements Comparable { - Package package; - final String name; - final List libraries; - - SubCategory(this.name, this.package, this.libraries) {} - - static List buildSubCategories(Package package) { - Map> libraryLists; - for (Library lib in package.libraries) { - - } - } - - - Iterable get publicLibraries => filterNonPublic(libraries); -} - class Package implements Comparable { final String name; @@ -4511,7 +4494,6 @@ class Package implements Comparable { Package(this.name, this.packageGraph); - DartdocOptions _dartdocOptions; DartdocOptions get dartdocOptions { if (_dartdocOptions == null) { @@ -4526,7 +4508,7 @@ class Package implements Comparable { String get packagePath { if (_packagePath == null) { if (isSdk) { - _packagePath = packageMeta.resolvedDir; + _packagePath = getSdkDir().path; } else { assert(_libraries.isNotEmpty); File file = new File(p.canonicalize(_libraries.first.element.source.fullName)); @@ -4558,14 +4540,6 @@ class Package implements Comparable { return _packageMeta; } - List _subCategories; - List get subCategories { - if (_subCategories == null) { - - } - return _subCategories; - } - @override String toString() => name; diff --git a/test/dartdoc_options_test.dart b/test/dartdoc_options_test.dart new file mode 100644 index 0000000000..b725bfcae0 --- /dev/null +++ b/test/dartdoc_options_test.dart @@ -0,0 +1,90 @@ +// Copyright (c) 2018, 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. + +library dartdoc.options_test; + +import 'dart:io'; + +import 'package:dartdoc/src/dartdoc_options.dart'; +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +void main() { + Directory tempDir; + Directory firstDir; + Directory firstDirFirstSub; + Directory secondDir; + Directory secondDirFirstSub; + Directory secondDirSecondSub; + + File pubspecYamlOne; + File dartdocOptionsOne; + File dartdocOptionsTwo; + File dartdocOptionsTwoFirstSub; + + setUpAll(() { + tempDir = Directory.systemTemp.createTempSync('options_test'); + firstDir = new Directory(p.join(tempDir.path, 'firstDir'))..createSync(); + secondDir = new Directory(p.join(tempDir.path, 'secondDir'))..createSync(); + + firstDirFirstSub = new Directory(p.join(firstDir.path, 'firstSub'))..createSync(); + secondDirFirstSub = new Directory(p.join(secondDir.path, 'firstSub'))..createSync(); + secondDirSecondSub = new Directory(p.join(secondDir.path, 'secondSub'))..createSync(); + + dartdocOptionsOne = new File(p.join(firstDir.path, 'dartdoc_options.yaml')); + pubspecYamlOne = new File(p.join(firstDirFirstSub.path, 'pubspec.yaml')); + dartdocOptionsTwo = new File(p.join(secondDir.path, 'dartdoc_options.yaml')); + dartdocOptionsTwoFirstSub = new File(p.join(secondDirFirstSub.path, 'dartdoc_options.yaml')); + + pubspecYamlOne.writeAsStringSync('# Sentinel to block dartdoc options loading'); + dartdocOptionsOne.writeAsStringSync(''' +dartdoc: + categoryOrder: ['options_one'] + '''); + dartdocOptionsTwo.writeAsStringSync(''' +dartdoc: + categoryOrder: ['options_two'] + '''); + dartdocOptionsTwoFirstSub.writeAsStringSync(''' +dartdoc: + categoryOrder: ['options_two_first_sub'] + '''); + }); + + tearDownAll(() { + tempDir.deleteSync(recursive: true); + }); + + group('dartdoc options', () { + + group('options file finding and loading', () { + test('DartdocOptions loads defaults', () { + DartdocOptions options = new DartdocOptions.fromDir(tempDir); + expect(options.categoryOrder, isEmpty); + }); + + test('DartdocOptions loads defaults if blocked by pubspec.yaml', () { + DartdocOptions options = new DartdocOptions.fromDir(firstDirFirstSub); + expect(options.categoryOrder, isEmpty); + }); + + test('DartdocOptions loads a file', () { + DartdocOptions options = new DartdocOptions.fromDir(firstDir); + expect(options.categoryOrder, orderedEquals(['options_one'])); + }); + + test('DartdocOptions loads a file in parent directories', () { + DartdocOptions options = new DartdocOptions.fromDir(secondDirSecondSub); + expect(options.categoryOrder, orderedEquals(['options_two'])); + }); + + test('DartdocOptions loads the override file and valid parents', () { + DartdocOptions options = new DartdocOptions.fromDir(secondDirFirstSub); + expect(options.categoryOrder, orderedEquals(['options_two_first_sub'])); + expect(options.parent.categoryOrder, orderedEquals(['options_two'])); + expect(options.parent.parent.categoryOrder, isEmpty); + }); + }); + }); +} \ No newline at end of file From 5500887b656da1e4032378df3140c501074f879c Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 15:15:29 -0700 Subject: [PATCH 08/21] Fix test failure (accidentally caching config info) --- lib/src/model.dart | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/lib/src/model.dart b/lib/src/model.dart index 9be0f9b5f5..16cce3493e 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -4063,22 +4063,19 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { return locatable.fullyQualifiedName.replaceFirst(':', '-'); } - List _publicPackages; List get publicPackages { - if (_publicPackages == null) { - // Help the user if they pass us a package that doesn't exist. - for (String packageName in config.packageOrder) { - if (!packages.containsKey(packageName)) - warnOnElement( - null, PackageWarning.packageOrderGivesMissingPackageName, - message: "${packageName}, packages: ${packages.keys.join(',')}"); - } - _publicPackages = packages.values - .where((p) => p.libraries.any((l) => l.isPublic)) - .toList() - ..sort(); - } - return _publicPackages; + List _publicPackages; + // Help the user if they pass us a package that doesn't exist. + for (String packageName in config.packageOrder) { + if (!packages.containsKey(packageName)) + warnOnElement( + null, PackageWarning.packageOrderGivesMissingPackageName, + message: "${packageName}, packages: ${packages.keys.join(',')}"); + } + _publicPackages = packages.values + .where((p) => p.libraries.any((l) => l.isPublic)) + .toList(); + return _publicPackages..sort(); } Map> _libraryElementReexportedBy = new Map(); From 65d9d3802e7bfd7eaf140eb60263e861bd2f95e8 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 15:17:53 -0700 Subject: [PATCH 09/21] dartfmt --- bin/dartdoc.dart | 9 +++------ test/model_test.dart | 9 +++++++-- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/bin/dartdoc.dart b/bin/dartdoc.dart index bb7e9de144..ce6ef1317f 100644 --- a/bin/dartdoc.dart +++ b/bin/dartdoc.dart @@ -312,11 +312,9 @@ ArgParser _createArgsParser() { parser.addOption('output', help: 'Path to output directory.', defaultsTo: defaultOutDir); parser.addMultiOption('header', - splitCommas: true, - help: 'paths to header files containing HTML text.'); + splitCommas: true, help: 'paths to header files containing HTML text.'); parser.addMultiOption('footer', - splitCommas: true, - help: 'paths to footer files containing HTML text.'); + splitCommas: true, help: 'paths to footer files containing HTML text.'); parser.addMultiOption('footer-text', splitCommas: true, help: 'paths to footer-text files ' @@ -326,8 +324,7 @@ ArgParser _createArgsParser() { parser.addMultiOption('exclude-packages', splitCommas: true, help: 'Package names to ignore.'); parser.addMultiOption('include', - splitCommas: true, - help: 'Library names to generate docs for.'); + splitCommas: true, help: 'Library names to generate docs for.'); parser.addMultiOption('include-external', help: 'Additional (external) dart files to include; use "dir/fileName", ' 'as in lib/material.dart.'); diff --git a/test/model_test.dart b/test/model_test.dart index 5da284d534..3434e02ec7 100644 --- a/test/model_test.dart +++ b/test/model_test.dart @@ -2227,9 +2227,14 @@ String topLevelFunction(int param1, bool param2, Cool coolBeans, fakeLibrary.classes.firstWhere((t) => t.name == 'TypedefUsingClass'); }); - test('Typedefs with bound type parameters indirectly referred in parameters are displayed', () { + test( + 'Typedefs with bound type parameters indirectly referred in parameters are displayed', + () { Constructor theConstructor = TypedefUsingClass.constructors.first; - expect(theConstructor.linkedParams(), equals('ParameterizedTypedef<double> x')); + expect( + theConstructor.linkedParams(), + equals( + 'ParameterizedTypedef<double> x')); }); test('anonymous nested functions inside typedefs are handled', () { From a113ef8c7c4af71ccc9a93b626275223c0162b95 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Thu, 15 Mar 2018 15:18:34 -0700 Subject: [PATCH 10/21] dartfmt --- bin/dartdoc.dart | 17 ++++++++++++----- lib/src/model.dart | 3 +-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/bin/dartdoc.dart b/bin/dartdoc.dart index cd34ec5cc3..eb2131290e 100644 --- a/bin/dartdoc.dart +++ b/bin/dartdoc.dart @@ -190,7 +190,9 @@ main(List arguments) async { PackageMeta packageMeta = sdkDocs ? new PackageMeta.fromSdk(sdkDir, - sdkReadmePath: readme, displayAsPackages: args['use-categories'] || args['display-as-packages']) + sdkReadmePath: readme, + displayAsPackages: + args['use-categories'] || args['display-as-packages']) : new PackageMeta.fromDir(inputDir); if (!packageMeta.isValid) { @@ -257,7 +259,9 @@ main(List arguments) async { inputDir: inputDir, sdkVersion: sdk.sdkVersion, autoIncludeDependencies: args['auto-include-dependencies'], - packageOrder: args['package-order'].isEmpty ? args['category-order'] : args['package-order'], + packageOrder: args['package-order'].isEmpty + ? args['category-order'] + : args['package-order'], reexportMinConfidence: double.parse(args['ambiguous-reexport-scorer-min-confidence']), verboseWarnings: args['verbose-warnings'], @@ -342,7 +346,8 @@ ArgParser _createArgsParser() { parser.addOption('favicon', help: 'A path to a favicon for the generated docs.'); parser.addFlag('use-categories', - help: 'Group libraries from the same package in the libraries sidebar. (deprecated, replaced by display-as-packages)', + help: + 'Group libraries from the same package in the libraries sidebar. (deprecated, replaced by display-as-packages)', negatable: false, defaultsTo: false); parser.addFlag('display-as-packages', @@ -350,11 +355,13 @@ ArgParser _createArgsParser() { negatable: false, defaultsTo: false); parser.addMultiOption('category-order', - help: 'A list of category names to place first when --display-as-packages is ' + help: + 'A list of category names to place first when --display-as-packages is ' 'set. Unmentioned categories are sorted after these. (deprecated, replaced by package-order)', splitCommas: true); parser.addMultiOption('package-order', - help: 'A list of category names to place first when --display-as-packages is ' + help: + 'A list of category names to place first when --display-as-packages is ' 'set. Unmentioned categories are sorted after these.', splitCommas: true); parser.addFlag('auto-include-dependencies', diff --git a/lib/src/model.dart b/lib/src/model.dart index 16cce3493e..70dd661b2e 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -4068,8 +4068,7 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { // Help the user if they pass us a package that doesn't exist. for (String packageName in config.packageOrder) { if (!packages.containsKey(packageName)) - warnOnElement( - null, PackageWarning.packageOrderGivesMissingPackageName, + warnOnElement(null, PackageWarning.packageOrderGivesMissingPackageName, message: "${packageName}, packages: ${packages.keys.join(',')}"); } _publicPackages = packages.values From 4c57a00a268756adf9724499838451878eafbfd4 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Fri, 16 Mar 2018 13:48:59 -0700 Subject: [PATCH 11/21] one last rename --- bin/dartdoc.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/dartdoc.dart b/bin/dartdoc.dart index eb2131290e..27252db039 100644 --- a/bin/dartdoc.dart +++ b/bin/dartdoc.dart @@ -356,12 +356,12 @@ ArgParser _createArgsParser() { defaultsTo: false); parser.addMultiOption('category-order', help: - 'A list of category names to place first when --display-as-packages is ' + 'A list of package names to place first when --display-as-packages is ' 'set. Unmentioned categories are sorted after these. (deprecated, replaced by package-order)', splitCommas: true); parser.addMultiOption('package-order', help: - 'A list of category names to place first when --display-as-packages is ' + 'A list of package names to place first when --display-as-packages is ' 'set. Unmentioned categories are sorted after these.', splitCommas: true); parser.addFlag('auto-include-dependencies', From de913ddeca3fe9319ab54fbce9520b499599a8c8 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Mon, 19 Mar 2018 09:25:54 -0700 Subject: [PATCH 12/21] Remove overly complicated config inheritance; we can add it back if we truly need this --- lib/src/dartdoc_options.dart | 36 ++++++++++++++++------------------ test/dartdoc_options_test.dart | 15 +------------- 2 files changed, 18 insertions(+), 33 deletions(-) diff --git a/lib/src/dartdoc_options.dart b/lib/src/dartdoc_options.dart index e55a93b22a..43b460d6e1 100644 --- a/lib/src/dartdoc_options.dart +++ b/lib/src/dartdoc_options.dart @@ -2,6 +2,14 @@ // 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://www.dartlang.org/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. +/// library dartdoc.dartdoc_options; import 'dart:io'; @@ -14,12 +22,8 @@ import 'logging.dart'; Map _dartdocOptionsCache = {}; -/// dartdoc_options.yaml handling. abstract class DartdocOptions { - /// The parent of this DartdocOptions object, or null if there is none. - final DartdocOptions parent; - - DartdocOptions(this.parent); + DartdocOptions(); /// Path to the dartdoc options file, or '' if this object is the /// default setting. Intended for printing only. @@ -36,36 +40,34 @@ abstract class DartdocOptions { } /// Search for a dartdoc_options file in this and parent directories. - /// Refuses to cross a package boundary (demarcated by pubspec.yaml). factory DartdocOptions._fromDir(Directory dir) { if (!dir.existsSync()) return new _DefaultDartdocOptions(); - File f, pb; + File f; dir = dir.absolute; while(true) { f = new File(p.join(dir.path, 'dartdoc_options.yaml')); - pb = new File(p.join(dir.path, 'pubspec.yaml')); - if (f.existsSync() || pb.existsSync() || dir.parent.path == dir.path) + if (f.existsSync() || dir.parent.path == dir.path) break; dir = dir.parent.absolute; } DartdocOptions parent; - if (dir.parent.path != dir.path && !pb.existsSync()) { + if (dir.parent.path != dir.path) { parent = new DartdocOptions.fromDir(dir.parent); } else { parent = new _DefaultDartdocOptions(); } if (f.existsSync()) { - return new _FileDartdocOptions(parent, f); + return new _FileDartdocOptions(f); } return parent; } } class _DefaultDartdocOptions extends DartdocOptions { - _DefaultDartdocOptions() : super(null); + _DefaultDartdocOptions() : super(); @override String get _path => ''; @@ -77,13 +79,13 @@ class _DefaultDartdocOptions extends DartdocOptions { class _FileDartdocOptions extends DartdocOptions { File dartdocOptionsFile; Map _dartdocOptions; - _FileDartdocOptions(DartdocOptions parent, this.dartdocOptionsFile) : super(parent) { + _FileDartdocOptions(this.dartdocOptionsFile) : super() { Map allDartdocOptions = loadYaml(dartdocOptionsFile.readAsStringSync()); if (allDartdocOptions.containsKey('dartdoc')) { _dartdocOptions = allDartdocOptions['dartdoc']; } else { _dartdocOptions = {}; - logWarning("${dartdocOptionsFile.path}: must contain 'dartdoc' section"); + logWarning("${_path}: must contain 'dartdoc' section"); } } @@ -92,7 +94,6 @@ class _FileDartdocOptions extends DartdocOptions { List _categoryOrder; @override - /// categoryOrder overrides parents. List get categoryOrder { if (_categoryOrder == null) { _categoryOrder = []; @@ -100,11 +101,8 @@ class _FileDartdocOptions extends DartdocOptions { if (_dartdocOptions['categoryOrder'] is YamlList) { _categoryOrder.addAll(_dartdocOptions['categoryOrder']); } else { - logWarning("${dartdocOptionsFile.path}: categoryOrder must be a list (ignoring)"); - _categoryOrder = parent.categoryOrder; + logWarning("${_path}: categoryOrder must be a list (ignoring)"); } - } else { - _categoryOrder = parent.categoryOrder; } _categoryOrder = new List.unmodifiable(_categoryOrder); } diff --git a/test/dartdoc_options_test.dart b/test/dartdoc_options_test.dart index b725bfcae0..c2e3654bac 100644 --- a/test/dartdoc_options_test.dart +++ b/test/dartdoc_options_test.dart @@ -13,12 +13,10 @@ import 'package:test/test.dart'; void main() { Directory tempDir; Directory firstDir; - Directory firstDirFirstSub; Directory secondDir; Directory secondDirFirstSub; Directory secondDirSecondSub; - File pubspecYamlOne; File dartdocOptionsOne; File dartdocOptionsTwo; File dartdocOptionsTwoFirstSub; @@ -28,16 +26,13 @@ void main() { firstDir = new Directory(p.join(tempDir.path, 'firstDir'))..createSync(); secondDir = new Directory(p.join(tempDir.path, 'secondDir'))..createSync(); - firstDirFirstSub = new Directory(p.join(firstDir.path, 'firstSub'))..createSync(); secondDirFirstSub = new Directory(p.join(secondDir.path, 'firstSub'))..createSync(); secondDirSecondSub = new Directory(p.join(secondDir.path, 'secondSub'))..createSync(); dartdocOptionsOne = new File(p.join(firstDir.path, 'dartdoc_options.yaml')); - pubspecYamlOne = new File(p.join(firstDirFirstSub.path, 'pubspec.yaml')); dartdocOptionsTwo = new File(p.join(secondDir.path, 'dartdoc_options.yaml')); dartdocOptionsTwoFirstSub = new File(p.join(secondDirFirstSub.path, 'dartdoc_options.yaml')); - pubspecYamlOne.writeAsStringSync('# Sentinel to block dartdoc options loading'); dartdocOptionsOne.writeAsStringSync(''' dartdoc: categoryOrder: ['options_one'] @@ -57,18 +52,12 @@ dartdoc: }); group('dartdoc options', () { - group('options file finding and loading', () { test('DartdocOptions loads defaults', () { DartdocOptions options = new DartdocOptions.fromDir(tempDir); expect(options.categoryOrder, isEmpty); }); - test('DartdocOptions loads defaults if blocked by pubspec.yaml', () { - DartdocOptions options = new DartdocOptions.fromDir(firstDirFirstSub); - expect(options.categoryOrder, isEmpty); - }); - test('DartdocOptions loads a file', () { DartdocOptions options = new DartdocOptions.fromDir(firstDir); expect(options.categoryOrder, orderedEquals(['options_one'])); @@ -79,11 +68,9 @@ dartdoc: expect(options.categoryOrder, orderedEquals(['options_two'])); }); - test('DartdocOptions loads the override file and valid parents', () { + test('DartdocOptions loads the override file instead of parents', () { DartdocOptions options = new DartdocOptions.fromDir(secondDirFirstSub); expect(options.categoryOrder, orderedEquals(['options_two_first_sub'])); - expect(options.parent.categoryOrder, orderedEquals(['options_two'])); - expect(options.parent.parent.categoryOrder, isEmpty); }); }); }); From 76013a663f81be77fbe3907be45356535f8f93ac Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Mon, 19 Mar 2018 09:26:17 -0700 Subject: [PATCH 13/21] dartfmt --- lib/src/config.dart | 1 - lib/src/dartdoc_options.dart | 12 +++++------- lib/src/model.dart | 4 ++-- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/src/config.dart b/lib/src/config.dart index 4e48af1322..f6fd2800e2 100644 --- a/lib/src/config.dart +++ b/lib/src/config.dart @@ -36,7 +36,6 @@ class LocalConfig { } return null; } - } class Config { diff --git a/lib/src/dartdoc_options.dart b/lib/src/dartdoc_options.dart index 43b460d6e1..9570e20d33 100644 --- a/lib/src/dartdoc_options.dart +++ b/lib/src/dartdoc_options.dart @@ -2,7 +2,6 @@ // 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, @@ -19,7 +18,6 @@ import 'package:yaml/yaml.dart'; import 'logging.dart'; - Map _dartdocOptionsCache = {}; abstract class DartdocOptions { @@ -34,7 +32,8 @@ abstract class DartdocOptions { factory DartdocOptions.fromDir(Directory dir) { if (!_dartdocOptionsCache.containsKey(dir.absolute.path)) { - _dartdocOptionsCache[dir.absolute.path] = new DartdocOptions._fromDir(dir); + _dartdocOptionsCache[dir.absolute.path] = + new DartdocOptions._fromDir(dir); } return _dartdocOptionsCache[dir.absolute.path]; } @@ -46,10 +45,9 @@ abstract class DartdocOptions { File f; dir = dir.absolute; - while(true) { + while (true) { f = new File(p.join(dir.path, 'dartdoc_options.yaml')); - if (f.existsSync() || dir.parent.path == dir.path) - break; + if (f.existsSync() || dir.parent.path == dir.path) break; dir = dir.parent.absolute; } @@ -108,4 +106,4 @@ class _FileDartdocOptions extends DartdocOptions { } return _categoryOrder; } -} \ No newline at end of file +} diff --git a/lib/src/model.dart b/lib/src/model.dart index 89cc2b5f5b..2ca15fd707 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -1762,7 +1762,6 @@ class Library extends ModelElement { .toList(growable: false); } - SdkLibrary get sdkLib { if (packageGraph.sdkLibrarySources.containsKey(element.librarySource)) { return packageGraph.sdkLibrarySources[element.librarySource]; @@ -4507,7 +4506,8 @@ class Package implements Comparable { _packagePath = getSdkDir().path; } else { assert(_libraries.isNotEmpty); - File file = new File(p.canonicalize(_libraries.first.element.source.fullName)); + File file = + new File(p.canonicalize(_libraries.first.element.source.fullName)); Directory dir = file.parent; while (dir.parent.path != dir.path && dir.existsSync()) { File pubspec = new File(p.join(dir.path, 'pubspec.yaml')); From 687ea5aab55527af6988dd7740240c364a51924a Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Tue, 20 Mar 2018 08:26:06 -0700 Subject: [PATCH 14/21] Unify SDK PackageMeta construction and add cache --- bin/dartdoc.dart | 20 ++++++++++------- lib/src/model.dart | 2 +- lib/src/package_meta.dart | 44 ++++++++++++++++++++----------------- test/package_meta_test.dart | 3 ++- test/src/utils.dart | 2 +- 5 files changed, 40 insertions(+), 31 deletions(-) diff --git a/bin/dartdoc.dart b/bin/dartdoc.dart index 27252db039..ca9bfe5eb7 100644 --- a/bin/dartdoc.dart +++ b/bin/dartdoc.dart @@ -59,7 +59,15 @@ main(List arguments) async { exit(1); } - Directory inputDir = new Directory(args['input']); + Directory inputDir; + if (sdkDocs) { + inputDir = sdkDir; + } else if (args['input'] == null) { + inputDir = Directory.current; + } else { + inputDir = args['input']; + } + if (!inputDir.existsSync()) { stderr.writeln( " fatal error: unable to locate the input directory at ${inputDir @@ -188,12 +196,7 @@ main(List arguments) async { }); } - PackageMeta packageMeta = sdkDocs - ? new PackageMeta.fromSdk(sdkDir, - sdkReadmePath: readme, - displayAsPackages: - args['use-categories'] || args['display-as-packages']) - : new PackageMeta.fromDir(inputDir); + PackageMeta packageMeta = new PackageMeta.fromDir(inputDir); if (!packageMeta.isValid) { final String firstError = packageMeta.getInvalidReasons().first; @@ -211,6 +214,7 @@ main(List arguments) async { } } + logInfo("Generating documentation for '${packageMeta}' into " "${outputDir.absolute.path}${Platform.pathSeparator}"); @@ -312,7 +316,7 @@ ArgParser _createArgsParser() { help: 'Path to the SDK description file; use if generating Dart SDK docs.'); parser.addOption('input', - help: 'Path to source directory.', defaultsTo: Directory.current.path); + help: 'Path to source directory.'); parser.addOption('output', help: 'Path to output directory.', defaultsTo: defaultOutDir); parser.addMultiOption('header', diff --git a/lib/src/model.dart b/lib/src/model.dart index 2ca15fd707..b56333233a 100644 --- a/lib/src/model.dart +++ b/lib/src/model.dart @@ -4203,7 +4203,7 @@ class PackageGraph extends Canonicalization with Nameable, Warnable { String get name => packageMeta.name; String get kind => - (packageMeta.displayAsPackages || packageGraph.isSdk) ? '' : 'package'; + (publicPackages.length > 1 || packageGraph.isSdk) ? '' : 'package'; @override String get oneLineDoc => ''; diff --git a/lib/src/package_meta.dart b/lib/src/package_meta.dart index e8f2739d72..dca1ef9076 100644 --- a/lib/src/package_meta.dart +++ b/lib/src/package_meta.dart @@ -11,17 +11,26 @@ import 'package:yaml/yaml.dart'; import 'logging.dart'; + +Map _packageMetaCache = {}; + abstract class PackageMeta { final Directory dir; - final bool displayAsPackages; - - PackageMeta(this.dir, {this.displayAsPackages: false}); - factory PackageMeta.fromDir(Directory dir) => new _FilePackageMeta(dir); - factory PackageMeta.fromSdk(Directory sdkDir, - {String sdkReadmePath, bool displayAsPackages}) => - new _SdkMeta(sdkDir, - sdkReadmePath: sdkReadmePath, displayAsPackages: displayAsPackages); + PackageMeta(this.dir); + + factory PackageMeta.fromDir(Directory dir) { + if (!_packageMetaCache.containsKey(dir.absolute.path)) { + PackageMeta packageMeta; + if (path.join(dir.absolute.path, 'bin', path.split(Platform.resolvedExecutable).last) == Platform.resolvedExecutable) { + packageMeta = new _SdkMeta(dir); + } else { + packageMeta = new _FilePackageMeta(dir); + } + _packageMetaCache[dir.absolute.path] = packageMeta; + } + return _packageMetaCache[dir.absolute.path]; + } bool get isSdk; bool get needsPubGet => false; @@ -46,7 +55,7 @@ abstract class PackageMeta { FileContents getChangelogContents(); /// Returns true if we are a valid package, valid enough to generate docs. - bool get isValid; + bool get isValid => getInvalidReasons().isEmpty; /// Returns a list of reasons this package is invalid, or an /// empty list if no reasons found. @@ -151,8 +160,6 @@ class _FilePackageMeta extends PackageMeta { return _changelog; } - @override - bool get isValid => getInvalidReasons().isEmpty; /// Returns a list of reasons this package is invalid, or an /// empty list if no reasons found. @@ -184,10 +191,12 @@ File _locate(Directory dir, List fileNames) { } class _SdkMeta extends PackageMeta { - final String sdkReadmePath; + String sdkReadmePath; - _SdkMeta(Directory dir, {this.sdkReadmePath, bool displayAsPackages}) - : super(dir, displayAsPackages: displayAsPackages); + _SdkMeta(Directory dir) + : super(dir) { + sdkReadmePath = path.join(dir.path, 'lib', 'api_readme.md'); + } @override bool get isSdk => true; @@ -211,15 +220,10 @@ class _SdkMeta extends PackageMeta { @override FileContents getReadmeContents() { - File f = sdkReadmePath != null - ? new File(sdkReadmePath) - : new File(path.join(dir.path, 'lib', 'api_readme.md')); + File f = new File(path.join(dir.path, 'lib', 'api_readme.md')); return f.existsSync() ? new FileContents(f) : null; } - @override - bool get isValid => true; - @override List getInvalidReasons() => []; diff --git a/test/package_meta_test.dart b/test/package_meta_test.dart index 91d1d32b84..e89c8a3faf 100644 --- a/test/package_meta_test.dart +++ b/test/package_meta_test.dart @@ -76,7 +76,7 @@ void main() { }); group('PackageMeta.fromSdk', () { - PackageMeta p = new PackageMeta.fromSdk(getSdkDir()); + PackageMeta p = new PackageMeta.fromDir(getSdkDir()); test('has a name', () { expect(p.name, 'Dart SDK'); @@ -85,6 +85,7 @@ void main() { test('is valid', () { expect(p.isValid, isTrue); expect(p.getInvalidReasons(), isEmpty); + expect(p.isSdk, isTrue); }); test('has a version', () { diff --git a/test/src/utils.dart b/test/src/utils.dart index c8710c0336..0906309925 100644 --- a/test/src/utils.dart +++ b/test/src/utils.dart @@ -34,7 +34,7 @@ void delete(Directory dir) { init() async { sdkDir = getSdkDir(); - sdkPackageMeta = new PackageMeta.fromSdk(sdkDir); + sdkPackageMeta = new PackageMeta.fromDir(sdkDir); setConfig(); testPackageGraph = await bootBasicPackage( From 9d0d8c530294b6f2085efcf2f93fa2724791d537 Mon Sep 17 00:00:00 2001 From: Janice Collins Date: Tue, 20 Mar 2018 08:43:23 -0700 Subject: [PATCH 15/21] update test package docs --- .../anonymous_library/anonymous_library-library.html | 2 +- .../another_anonymous_lib/another_anonymous_lib-library.html | 2 +- .../code_in_comments/code_in_comments-library.html | 2 +- testing/test_package_docs/css/css-library.html | 2 +- testing/test_package_docs/ex/ex-library.html | 2 +- testing/test_package_docs/fake/fake-library.html | 2 +- testing/test_package_docs/index.html | 2 +- .../test_package_docs/is_deprecated/is_deprecated-library.html | 2 +- .../test_package_docs/reexport_one/reexport_one-library.html | 2 +- .../test_package_docs/reexport_two/reexport_two-library.html | 2 +- .../test_package_imported.main-library.html | 2 +- testing/test_package_docs/two_exports/two_exports-library.html | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/testing/test_package_docs/anonymous_library/anonymous_library-library.html b/testing/test_package_docs/anonymous_library/anonymous_library-library.html index 59b480c118..8bebd2ac43 100644 --- a/testing/test_package_docs/anonymous_library/anonymous_library-library.html +++ b/testing/test_package_docs/anonymous_library/anonymous_library-library.html @@ -35,7 +35,7 @@