Skip to content

Commit acc64ad

Browse files
authored
Simplify package_meta.dart (#3572)
1 parent ad99412 commit acc64ad

File tree

5 files changed

+57
-97
lines changed

5 files changed

+57
-97
lines changed

lib/src/generator/templates.runtime_renderers.dart

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17001,7 +17001,6 @@ const _invisibleGetters = {
1700117001
'isSdk',
1700217002
'isValid',
1700317003
'name',
17004-
'pathContext',
1700517004
'requiresFlutter',
1700617005
'resolvedDir',
1700717006
'resourceProvider',

lib/src/model/package_graph.dart

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,14 @@ class PackageGraph with CommentReferable, Nameable, ModelBuilder {
8080
var packageMeta =
8181
packageMetaProvider.fromElement(libraryElement, config.sdkDir);
8282
if (packageMeta == null) {
83-
throw DartdocFailure(packageMetaProvider.getMessageForMissingPackageMeta(
84-
libraryElement, config));
83+
var libraryPath = libraryElement.librarySource.fullName;
84+
var dartOrFlutter = config.flutterRoot == null ? 'dart' : 'flutter';
85+
throw DartdocFailure(
86+
"Unknown package for library: '$libraryPath'. Consider "
87+
'`$dartOrFlutter pub get` and/or '
88+
'`$dartOrFlutter pub global deactivate dartdoc` followed by '
89+
'`$dartOrFlutter pub global activate dartdoc` to fix. Also, be sure '
90+
'that `$dartOrFlutter analyze` completes without errors.');
8591
}
8692
var package = Package.fromPackageMeta(packageMeta, this);
8793
var lib = Library.fromLibraryResult(resolvedLibrary, this, package);

lib/src/package_meta.dart

Lines changed: 49 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import 'package:analyzer/file_system/file_system.dart';
1111
import 'package:analyzer/file_system/physical_file_system.dart';
1212
// ignore: implementation_imports
1313
import 'package:analyzer/src/generated/sdk.dart' show DartSdk;
14-
import 'package:dartdoc/src/dartdoc_options.dart';
1514
import 'package:dartdoc/src/failure.dart';
1615
import 'package:meta/meta.dart';
1716
import 'package:path/path.dart' as path;
@@ -23,9 +22,13 @@ class PackageMetaFailure extends DartdocFailure {
2322
PackageMetaFailure(super.message);
2423
}
2524

26-
/// For each list in this list, at least one of the given paths must exist
27-
/// for this to be detected as an SDK. Update `_writeMockSdkBinFiles` in
28-
/// `test/src/utils.dart` if removing any entries here.
25+
/// Various relative paths that indicate that a root direoctory is an SDK (Dart
26+
/// or Flutter).
27+
///
28+
/// For a given directory to be detected as an SDK, at least one of the given
29+
/// paths must exist, for each list of paths.
30+
// Update `_writeMockSdkBinFiles` in `test/src/utils.dart` if removing any
31+
// entries here.
2932
const List<List<String>> _sdkDirFilePathsPosix = [
3033
['bin/dart.bat', 'bin/dart.exe', 'bin/dart'],
3134
['include/dart_version.h'],
@@ -43,7 +46,6 @@ final PackageMetaProvider pubPackageMetaProvider = PackageMetaProvider(
4346
.parent
4447
.parent,
4548
Platform.environment,
46-
messageForMissingPackageMeta: PubPackageMeta.messageForMissingPackageMeta,
4749
);
4850

4951
/// Sets the supported way of constructing [PackageMeta] objects.
@@ -65,9 +67,6 @@ class PackageMetaProvider {
6567
final DartSdk? defaultSdk;
6668
final Map<String, String> environmentProvider;
6769

68-
final String Function(LibraryElement, DartdocOptionContext)
69-
_messageForMissingPackageMeta;
70-
7170
PackageMetaProvider(
7271
this._fromElement,
7372
this._fromFilename,
@@ -76,24 +75,12 @@ class PackageMetaProvider {
7675
this.defaultSdkDir,
7776
this.environmentProvider, {
7877
this.defaultSdk,
79-
String Function(LibraryElement, DartdocOptionContext)?
80-
messageForMissingPackageMeta,
81-
}) : _messageForMissingPackageMeta = messageForMissingPackageMeta ??
82-
_defaultMessageForMissingPackageMeta;
78+
});
8379

8480
PackageMeta? fromElement(LibraryElement library, String s) =>
8581
_fromElement(library, s, resourceProvider);
8682
PackageMeta? fromFilename(String s) => _fromFilename(s, resourceProvider);
8783
PackageMeta? fromDir(Folder dir) => _fromDir(dir, resourceProvider);
88-
89-
String getMessageForMissingPackageMeta(
90-
LibraryElement library, DartdocOptionContext optionContext) =>
91-
_messageForMissingPackageMeta(library, optionContext);
92-
93-
static String _defaultMessageForMissingPackageMeta(
94-
LibraryElement library, DartdocOptionContext optionContext) {
95-
return 'Unknown package for library: ${library.source.fullName}';
96-
}
9784
}
9885

9986
/// Describes a single package in the context of `dartdoc`.
@@ -104,6 +91,8 @@ class PackageMetaProvider {
10491
///
10592
/// Overriding this is typically done by overriding factories as rest of
10693
/// `dartdoc` creates this object by calling these static factories.
94+
// This class has a single direct subclass in this package, [PubPackageMeta],
95+
// but has other subclasses in google3.
10796
abstract class PackageMeta {
10897
final Folder dir;
10998

@@ -112,25 +101,22 @@ abstract class PackageMeta {
112101
PackageMeta(this.dir, this.resourceProvider);
113102

114103
@override
115-
bool operator ==(Object other) {
116-
if (other is! PackageMeta) return false;
117-
var otherMeta = other;
118-
return resourceProvider.pathContext.equals(dir.path, otherMeta.dir.path);
119-
}
104+
bool operator ==(Object other) =>
105+
other is PackageMeta && _pathContext.equals(dir.path, other.dir.path);
120106

121107
@override
122-
int get hashCode => pathContext.hash(pathContext.absolute(dir.path));
108+
int get hashCode => _pathContext.hash(_pathContext.absolute(dir.path));
123109

124-
path.Context get pathContext => resourceProvider.pathContext;
110+
path.Context get _pathContext => resourceProvider.pathContext;
125111

126-
/// Returns true if this represents a 'Dart' SDK.
112+
/// Whether this represents a 'Dart' SDK.
127113
///
128-
/// A package can be part of Dart and Flutter at the same time, but if we are
114+
/// A package can be part of Dart and Flutter at the same time, but if this is
129115
/// part of a Dart SDK, [sdkType] should never return null.
130116
bool get isSdk;
131117

132118
/// Returns 'Dart' or 'Flutter' (preferentially, 'Flutter' when the answer is
133-
/// "both"), or null if this package is not part of a SDK.
119+
/// "both"), or `null` if this package is not part of an SDK.
134120
String? sdkType(String? flutterRootPath);
135121

136122
bool get requiresFlutter;
@@ -147,14 +133,12 @@ abstract class PackageMeta {
147133

148134
File? getReadmeContents();
149135

150-
/// Returns true if we are a valid package, valid enough to generate docs.
136+
/// Whether this is a valid package (valid enough to generate docs).
151137
bool get isValid => getInvalidReasons().isEmpty;
152138

153-
/// Returns resolved directory.
154139
String get resolvedDir;
155140

156-
/// Returns a list of reasons this package is invalid, or an
157-
/// empty list if no reasons found.
141+
/// The list of reasons this package is invalid.
158142
///
159143
/// If the list is empty, this package is valid.
160144
List<String> getInvalidReasons();
@@ -179,8 +163,8 @@ abstract class PubPackageMeta extends PackageMeta {
179163

180164
static final _sdkDirParent = <String, Folder?>{};
181165

182-
/// If [folder] is inside a Dart SDK, returns the directory of the SDK, and `null`
183-
/// otherwise.
166+
/// If [folder] is inside a Dart SDK, returns the directory of the SDK, and
167+
/// `null` otherwise.
184168
static Folder? sdkDirParent(
185169
Folder folder, ResourceProvider resourceProvider) {
186170
var pathContext = resourceProvider.pathContext;
@@ -200,7 +184,7 @@ abstract class PubPackageMeta extends PackageMeta {
200184
return _sdkDirParent[dirPathCanonical];
201185
}
202186

203-
/// Use this instead of fromDir where possible.
187+
/// Use this instead of [fromDir] where possible.
204188
static PackageMeta? fromElement(LibraryElement libraryElement, String sdkDir,
205189
ResourceProvider resourceProvider) {
206190
if (libraryElement.isInSdk) {
@@ -223,64 +207,49 @@ abstract class PubPackageMeta extends PackageMeta {
223207

224208
/// This factory is guaranteed to return the same object for any given
225209
/// `dir.absolute.path`. Multiple `dir.absolute.path`s will resolve to the
226-
/// same object if they are part of the same package. Returns null
227-
/// if the directory is not part of a known package.
210+
/// same object if they are part of the same package. Returns `null` if the
211+
/// directory is not part of a known package.
228212
static PackageMeta? fromDir(
229213
Folder folder, ResourceProvider resourceProvider) {
230214
var pathContext = resourceProvider.pathContext;
231-
var original =
232-
resourceProvider.getFolder(pathContext.absolute(folder.path));
233-
folder = original;
234-
if (!original.exists) {
215+
folder = resourceProvider.getFolder(pathContext.absolute(folder.path));
216+
if (!folder.exists) {
235217
throw PackageMetaFailure(
236-
'fatal error: unable to locate the input directory at '
237-
"'${original.path}'.");
218+
'fatal error: unable to locate the input directory at '
219+
"'${folder.path}'.",
220+
);
238221
}
239222

240-
if (!_packageMetaCache.containsKey(folder.path)) {
241-
PackageMeta? packageMeta;
223+
return _packageMetaCache.putIfAbsent(pathContext.absolute(folder.path), () {
242224
// There are pubspec.yaml files inside the SDK. Ignore them.
243225
var parentSdkDir = sdkDirParent(folder, resourceProvider);
244226
if (parentSdkDir != null) {
245-
packageMeta = _SdkMeta(parentSdkDir, resourceProvider);
227+
return _SdkMeta(parentSdkDir, resourceProvider);
246228
} else {
247229
for (var dir in folder.withAncestors) {
248230
var pubspec = resourceProvider
249231
.getFile(pathContext.join(dir.path, 'pubspec.yaml'));
250232
if (pubspec.exists) {
251-
packageMeta = _FilePackageMeta(dir, resourceProvider);
252-
break;
233+
return _FilePackageMeta(dir, resourceProvider);
253234
}
254235
}
255236
}
256-
_packageMetaCache[pathContext.absolute(folder.path)] = packageMeta;
257-
}
258-
return _packageMetaCache[pathContext.absolute(folder.path)];
259-
}
260-
261-
/// Create a helpful user error message for a case where a package can not
262-
/// be found.
263-
static String messageForMissingPackageMeta(
264-
LibraryElement library, DartdocOptionContext optionContext) {
265-
var libraryString = library.librarySource.fullName;
266-
var dartOrFlutter = optionContext.flutterRoot == null ? 'dart' : 'flutter';
267-
return 'Unknown package for library: $libraryString. Consider `$dartOrFlutter pub get` and/or '
268-
'`$dartOrFlutter pub global deactivate dartdoc` followed by `$dartOrFlutter pub global activate dartdoc` to fix. '
269-
'Also, be sure that `$dartOrFlutter analyze` completes without errors.';
237+
return null;
238+
});
270239
}
271240

272241
@override
273242
String? sdkType(String? flutterRootPath) {
274243
if (flutterRootPath != null) {
275-
var flutterPackages = pathContext.join(flutterRootPath, 'packages');
276-
var flutterBinCache = pathContext.join(flutterRootPath, 'bin', 'cache');
244+
var flutterPackages = _pathContext.join(flutterRootPath, 'packages');
245+
var flutterBinCache = _pathContext.join(flutterRootPath, 'bin', 'cache');
277246

278247
/// Don't include examples or other non-SDK components as being the
279248
/// "Flutter SDK".
280-
var canonicalizedDir = pathContext
249+
var canonicalizedDir = _pathContext
281250
.canonicalize(resourceProvider.pathContext.absolute(dir.path));
282-
if (pathContext.isWithin(flutterPackages, canonicalizedDir) ||
283-
pathContext.isWithin(flutterBinCache, canonicalizedDir)) {
251+
if (_pathContext.isWithin(flutterPackages, canonicalizedDir) ||
252+
_pathContext.isWithin(flutterBinCache, canonicalizedDir)) {
284253
return 'Flutter';
285254
}
286255
}
@@ -313,17 +282,17 @@ class _FilePackageMeta extends PubPackageMeta {
313282
// possibly by calculating hosting directly from pubspec.yaml or importing
314283
// a pub library to do this.
315284
// People could have a pub cache at root with Windows drive mappings.
316-
if (pathContext.split(pathContext.canonicalize(dir.path)).length >= 3) {
285+
if (_pathContext.split(_pathContext.canonicalize(dir.path)).length >= 3) {
317286
var pubCacheRoot = dir.parent.parent.parent.path;
318287
// Check for directory structure too close to root.
319288
if (pubCacheRoot != dir.parent.parent.path) {
320-
var hosted = pathContext.canonicalize(dir.parent.parent.path);
321-
var hostname = pathContext.canonicalize(dir.parent.path);
322-
if (pathContext.basename(hosted) == 'hosted' &&
289+
var hosted = _pathContext.canonicalize(dir.parent.parent.path);
290+
var hostname = _pathContext.canonicalize(dir.parent.path);
291+
if (_pathContext.basename(hosted) == 'hosted' &&
323292
resourceProvider
324-
.getFolder(pathContext.join(pubCacheRoot, '_temp'))
293+
.getFolder(_pathContext.join(pubCacheRoot, '_temp'))
325294
.exists) {
326-
hostedAt = pathContext.basename(hostname);
295+
hostedAt = _pathContext.basename(hostname);
327296
}
328297
}
329298
}
@@ -360,13 +329,10 @@ class _FilePackageMeta extends PubPackageMeta {
360329
/// empty list if no reasons found.
361330
@override
362331
List<String> getInvalidReasons() {
363-
var reasons = <String>[];
364-
if (_pubspec.isEmpty) {
365-
reasons.add('no pubspec.yaml found');
366-
} else if (!_pubspec.containsKey('name')) {
367-
reasons.add('no name found in pubspec.yaml');
368-
}
369-
return reasons;
332+
return [
333+
if (_pubspec.isEmpty) 'no pubspec.yaml found',
334+
if (!_pubspec.containsKey('name')) "no 'name' field found in pubspec.yaml"
335+
];
370336
}
371337
}
372338

test/end2end/model_test.dart

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -118,16 +118,6 @@ void main() {
118118
packageGraph.libraries.firstWhere((lib) => lib.name == 'base_class');
119119
});
120120

121-
group('PackageMeta and PackageGraph integration', () {
122-
test('PackageMeta error messages generate correctly', () {
123-
var message = packageGraph.packageMetaProvider
124-
.getMessageForMissingPackageMeta(
125-
fakeLibrary.element, packageGraph.config);
126-
expect(message, contains('fake.dart'));
127-
expect(message, contains('pub global activate dartdoc'));
128-
});
129-
});
130-
131121
group('triple-shift', () {
132122
Library tripleShift;
133123
late final Class C, E, F;

test/src/utils.dart

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,6 @@ PackageMetaProvider get testPackageMetaProvider {
153153
sdkRoot,
154154
{},
155155
defaultSdk: FolderBasedDartSdk(resourceProvider, sdkRoot),
156-
messageForMissingPackageMeta: PubPackageMeta.messageForMissingPackageMeta,
157156
);
158157
}
159158

0 commit comments

Comments
 (0)