-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
info.ts
397 lines (309 loc) Β· 14.5 KB
/
info.ts
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
import {BaseCommand, WorkspaceRequiredError} from '@yarnpkg/cli';
import {Configuration, Project, structUtils, Workspace, LocatorHash, Package, formatUtils, miscUtils, Locator, Cache, FetchOptions, ThrowReport, Manifest, treeUtils} from '@yarnpkg/core';
import {xfs} from '@yarnpkg/fslib';
import {Command, Option, Usage, UsageError} from 'clipanion';
import mm from 'micromatch';
import {Hooks} from '..';
// eslint-disable-next-line arca/no-default-export
export default class InfoCommand extends BaseCommand {
static paths = [
[`info`],
];
static usage: Usage = Command.Usage({
description: `see information related to packages`,
details: `
This command prints various information related to the specified packages, accepting glob patterns.
By default, if the locator reference is missing, Yarn will default to print the information about all the matching direct dependencies of the package for the active workspace. To instead print all versions of the package that are direct dependencies of any of your workspaces, use the \`-A,--all\` flag. Adding the \`-R,--recursive\` flag will also report transitive dependencies.
Some fields will be hidden by default in order to keep the output readable, but can be selectively displayed by using additional options (\`--dependents\`, \`--manifest\`, \`--virtuals\`, ...) described in the option descriptions.
Note that this command will only print the information directly related to the selected packages - if you wish to know why the package is there in the first place, use \`yarn why\` which will do just that (it also provides a \`-R,--recursive\` flag that may be of some help).
`,
examples: [[
`Show information about Lodash`,
`$0 info lodash`,
]],
});
all = Option.Boolean(`-A,--all`, false, {
description: `Print versions of a package from the whole project`,
});
recursive = Option.Boolean(`-R,--recursive`, false, {
description: `Print information for all packages, including transitive dependencies`,
});
extra = Option.Array(`-X,--extra`, [], {
description: `An array of requests of extra data provided by plugins`,
});
cache = Option.Boolean(`--cache`, false, {
description: `Print information about the cache entry of a package (path, size, checksum)`,
});
dependents = Option.Boolean(`--dependents`, false, {
description: `Print all dependents for each matching package`,
});
manifest = Option.Boolean(`--manifest`, false, {
description: `Print data obtained by looking at the package archive (license, homepage, ...)`,
});
nameOnly = Option.Boolean(`--name-only`, false, {
description: `Only print the name for the matching packages`,
});
virtuals = Option.Boolean(`--virtuals`, false, {
description: `Print each instance of the virtual packages`,
});
json = Option.Boolean(`--json`, false, {
description: `Format the output as an NDJSON stream`,
});
patterns = Option.Rest();
async execute() {
const configuration = await Configuration.find(this.context.cwd, this.context.plugins);
const {project, workspace} = await Project.find(configuration, this.context.cwd);
const cache = await Cache.find(configuration);
if (!workspace && !this.all)
throw new WorkspaceRequiredError(project.cwd, this.context.cwd);
await project.restoreInstallState();
const extraSet = new Set(this.extra);
if (this.cache)
extraSet.add(`cache`);
if (this.dependents)
extraSet.add(`dependents`);
if (this.manifest)
extraSet.add(`manifest`);
const traverseWorkspace = (workspace: Workspace, {recursive}: {recursive: boolean}) => {
const initialHash = workspace.anchoredLocator.locatorHash;
const seen = new Map<LocatorHash, Package>();
const pass = [initialHash];
while (pass.length > 0) {
const hash = pass.shift()!;
if (seen.has(hash))
continue;
const pkg = project.storedPackages.get(hash);
if (typeof pkg === `undefined`)
throw new Error(`Assertion failed: Expected the package to be registered`);
seen.set(hash, pkg);
if (structUtils.isVirtualLocator(pkg))
pass.push(structUtils.devirtualizeLocator(pkg).locatorHash);
if (!recursive && hash !== initialHash)
continue;
for (const dependency of pkg.dependencies.values()) {
const resolution = project.storedResolutions.get(dependency.descriptorHash);
if (typeof resolution === `undefined`)
throw new Error(`Assertion failed: Expected the resolution to be registered`);
pass.push(resolution);
}
}
return seen.values();
};
const traverseAllWorkspaces = ({recursive}: {recursive: boolean}) => {
const aggregate = new Map<LocatorHash, Package>();
for (const workspace of project.workspaces)
for (const pkg of traverseWorkspace(workspace, {recursive}))
aggregate.set(pkg.locatorHash, pkg);
return aggregate.values();
};
const getLookupSet = ({all, recursive}: {all: boolean, recursive: boolean}) => {
// Optimization: if both -A and -R are set, it means we care about the
// whole set of packages, no need for filtering
if (all && recursive)
return project.storedPackages.values();
if (all) {
return traverseAllWorkspaces({recursive});
} else {
return traverseWorkspace(workspace!, {recursive});
}
};
const findSelectedSet = ({all, recursive}: {all: boolean, recursive: boolean}) => {
const lookupSet = getLookupSet({all, recursive});
const matchers = this.patterns.map(pattern => {
const patternLocator = structUtils.parseLocator(pattern);
const identRegex = mm.makeRe(structUtils.stringifyIdent(patternLocator));
const patternIsVirtual = structUtils.isVirtualLocator(patternLocator);
const uvPatternLocator = patternIsVirtual
? structUtils.devirtualizeLocator(patternLocator)
: patternLocator;
return (pkg: Package) => {
const stringifiedIdent = structUtils.stringifyIdent(pkg);
if (!identRegex.test(stringifiedIdent))
return false;
if (patternLocator.reference === `unknown`)
return true;
const pkgIsVirtual = structUtils.isVirtualLocator(pkg);
const uvPkgLocator = pkgIsVirtual
? structUtils.devirtualizeLocator(pkg)
: pkg;
// If the pattern is explicitly virtual, we only accept this one virtual package, never the others
if (patternIsVirtual && pkgIsVirtual && patternLocator.reference !== pkg.reference)
return false;
// We only accept that belong to the current reference (or its base if it's a virtual package)
if (uvPatternLocator.reference !== uvPkgLocator.reference)
return false;
return true;
};
});
const sortedLookup = miscUtils.sortMap([...lookupSet], pkg => {
return structUtils.stringifyLocator(pkg);
});
const selection = sortedLookup.filter(pkg => {
return matchers.length === 0 || matchers.some(matcher => matcher(pkg));
});
return {selection, sortedLookup};
};
const {selection, sortedLookup} = findSelectedSet({
all: this.all,
recursive: this.recursive,
});
if (selection.length === 0)
throw new UsageError(`No package matched your request`);
const dependentMap = new Map<LocatorHash, Array<Locator>>();
if (this.dependents) {
for (const pkg of sortedLookup) {
for (const dependency of pkg.dependencies.values()) {
const resolution = project.storedResolutions.get(dependency.descriptorHash);
if (typeof resolution === `undefined`)
throw new Error(`Assertion failed: Expected the resolution to be registered`);
miscUtils.getArrayWithDefault(dependentMap, resolution).push(pkg);
}
}
}
const allInstances = new Map<LocatorHash, Array<Package>>();
for (const pkg of sortedLookup) {
if (!structUtils.isVirtualLocator(pkg))
continue;
const base = structUtils.devirtualizeLocator(pkg);
miscUtils.getArrayWithDefault(allInstances, base.locatorHash).push(pkg);
}
const infoTreeChildren: treeUtils.TreeMap = {};
const infoTree: treeUtils.TreeNode = {children: infoTreeChildren};
const fetcher = configuration.makeFetcher();
const fetcherOptions: FetchOptions = {project, fetcher, cache, checksums: project.storedChecksums, report: new ThrowReport(), cacheOptions: {skipIntegrityCheck: true}};
const builtinInfoBuilders: Array<Exclude<Hooks['fetchPackageInfo'], undefined>> = [
// Manifest fields
async (pkg, extra, registerData) => {
if (!extra.has(`manifest`))
return;
const fetchResult = await fetcher.fetch(pkg, fetcherOptions);
let manifest;
try {
manifest = await Manifest.find(fetchResult.prefixPath, {baseFs: fetchResult.packageFs});
} finally {
fetchResult.releaseFs?.();
}
registerData(`Manifest`, {
[`License`]: formatUtils.tuple(formatUtils.Type.NO_HINT, manifest.license),
[`Homepage`]: formatUtils.tuple(formatUtils.Type.URL, manifest.raw.homepage ?? null),
});
},
// Cache info
async (pkg, extra, registerData) => {
if (!extra.has(`cache`))
return;
const checksum = project.storedChecksums.get(pkg.locatorHash) ?? null;
const cachePath = cache.getLocatorPath(pkg, checksum);
let stat;
if (cachePath !== null) {
try {
stat = await xfs.statPromise(cachePath);
} catch {}
}
const size = typeof stat !== `undefined`
? [stat.size, formatUtils.Type.SIZE] as const
: undefined;
registerData(`Cache`, {
[`Checksum`]: formatUtils.tuple(formatUtils.Type.NO_HINT, checksum),
[`Path`]: formatUtils.tuple(formatUtils.Type.PATH, cachePath),
[`Size`]: size,
});
},
];
for (const pkg of selection) {
const isVirtual = structUtils.isVirtualLocator(pkg);
if (!this.virtuals && isVirtual)
continue;
const nodeChildren: treeUtils.TreeMap = {};
const node: treeUtils.TreeNode = {
value: [pkg, formatUtils.Type.LOCATOR],
children: nodeChildren,
};
infoTreeChildren[structUtils.stringifyLocator(pkg)] = node;
if (this.nameOnly) {
delete node.children;
continue;
}
const instances = allInstances.get(pkg.locatorHash);
if (typeof instances !== `undefined`) {
nodeChildren.Instances = {
label: `Instances`,
value: formatUtils.tuple(formatUtils.Type.NUMBER, instances.length),
};
}
nodeChildren.Version = {
label: `Version`,
value: formatUtils.tuple(formatUtils.Type.NO_HINT, pkg.version),
};
const registerData = (namespace: string, info: Array<formatUtils.Tuple> | {[key: string]: formatUtils.Tuple | undefined}) => {
const namespaceNode: treeUtils.TreeNode = {};
nodeChildren[namespace] = namespaceNode;
if (Array.isArray(info)) {
namespaceNode.children = info.map(value => ({value}));
} else {
const namespaceChildren: treeUtils.TreeMap = {};
namespaceNode.children = namespaceChildren;
for (const [key, value] of Object.entries(info)) {
if (typeof value === `undefined`)
continue;
namespaceChildren[key] = {
label: key,
value,
};
}
}
};
if (!isVirtual) {
for (const infoBuilder of builtinInfoBuilders)
await infoBuilder(pkg, extraSet, registerData);
await configuration.triggerHook((hooks: Hooks) => {
return hooks.fetchPackageInfo;
}, pkg, extraSet, registerData);
}
if (pkg.bin.size > 0 && !isVirtual) {
registerData(`Exported Binaries`, [...pkg.bin.keys()].map(name => {
return formatUtils.tuple(formatUtils.Type.PATH, name);
}));
}
const dependents = dependentMap.get(pkg.locatorHash);
if (typeof dependents !== `undefined` && dependents.length > 0) {
registerData(`Dependents`, dependents.map(dependent => {
return formatUtils.tuple(formatUtils.Type.LOCATOR, dependent);
}));
}
if (pkg.dependencies.size > 0 && !isVirtual) {
registerData(`Dependencies`, [...pkg.dependencies.values()].map(dependency => {
const resolutionHash = project.storedResolutions.get(dependency.descriptorHash);
const resolution = typeof resolutionHash !== `undefined`
? project.storedPackages.get(resolutionHash) ?? null
: null;
return formatUtils.tuple(formatUtils.Type.RESOLUTION, {
descriptor: dependency,
locator: resolution,
});
}));
}
if (pkg.peerDependencies.size > 0 && isVirtual) {
registerData(`Peer dependencies`, [...pkg.peerDependencies.values()].map(peerDependency => {
const dependency = pkg.dependencies.get(peerDependency.identHash);
const resolutionHash = typeof dependency !== `undefined`
? project.storedResolutions.get(dependency.descriptorHash) ?? null
: null;
const resolution = resolutionHash !== null
? project.storedPackages.get(resolutionHash) ?? null
: null;
return formatUtils.tuple(formatUtils.Type.RESOLUTION, {
descriptor: peerDependency,
locator: resolution,
});
}));
}
}
treeUtils.emitTree(infoTree, {
configuration,
json: this.json,
stdout: this.context.stdout,
separators: this.nameOnly ? 0 : 2,
});
}
}