generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
inspect.ts
408 lines (368 loc) · 14.2 KB
/
inspect.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
398
399
400
401
402
403
404
405
406
407
408
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/* eslint-disable no-await-in-loop */
import os from 'node:os';
import path from 'node:path';
import util from 'node:util';
import fs from 'node:fs/promises';
import fg from 'fast-glob';
import shelljs from 'shelljs';
import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
import { Messages, SfError } from '@salesforce/core';
import chalk from 'chalk';
import { ensure, entriesOf } from '@salesforce/ts-types';
import { parseJson } from '@salesforce/kit';
import { Interfaces } from '@oclif/core';
import { PackageJson } from '../../../package.js';
import { CLI } from '../../../types.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-release-management', 'cli.versions.inspect');
const LEGACY_PATH = 'https://developer.salesforce.com/media/salesforce-cli/sfdx-cli/channels/stable';
const LEGACY_TOP_LEVEL_PATH = 'https://developer.salesforce.com/media/salesforce-cli';
const SALESFORCE_DEP_GLOBS = ['@salesforce/**/*', 'salesforce-alm', 'salesforcedx'];
export type Info = {
origin: string;
version: string;
channel: Channel;
location: Location;
dependencies: Dependency[];
};
export type InspectResult = Info[];
export type Dependency = {
name: string;
version: string;
};
export enum Channel {
LEGACY = 'legacy',
STABLE = 'stable',
STABLE_RC = 'stable-rc',
LATEST = 'latest',
LATEST_RC = 'latest-rc',
NIGHTLY = 'nightly',
}
export enum Location {
ARCHIVE = 'archive',
NPM = 'npm',
}
type ArchiveChannel = Extract<Channel, Channel.STABLE | Channel.STABLE_RC | Channel.NIGHTLY | Channel.LEGACY>;
type Archives = Record<ArchiveChannel, string[]>;
type ChannelMapping = Record<Location, Record<Channel, Channel>>;
const ARCHIVES: Archives = {
[Channel.STABLE]: [
'%s/%s-darwin-x64.tar.gz',
'%s/%s-darwin-x64.tar.xz',
'%s/%s-darwin-arm64.tar.gz',
'%s/%s-darwin-arm64.tar.xz',
'%s/%s-linux-arm.tar.gz',
'%s/%s-linux-arm.tar.xz',
'%s/%s-linux-x64.tar.gz',
'%s/%s-linux-x64.tar.xz',
'%s/%s-win32-x64.tar.gz',
'%s/%s-win32-x64.tar.xz',
'%s/%s-win32-x86.tar.gz',
'%s/%s-win32-x86.tar.xz',
],
[Channel.STABLE_RC]: [
'%s/%s-darwin-x64.tar.gz',
'%s/%s-darwin-x64.tar.xz',
'%s/%s-darwin-arm64.tar.gz',
'%s/%s-darwin-arm64.tar.xz',
'%s/%s-linux-arm.tar.gz',
'%s/%s-linux-arm.tar.xz',
'%s/%s-linux-x64.tar.gz',
'%s/%s-linux-x64.tar.xz',
'%s/%s-win32-x64.tar.gz',
'%s/%s-win32-x64.tar.xz',
'%s/%s-win32-x86.tar.gz',
'%s/%s-win32-x86.tar.xz',
],
[Channel.NIGHTLY]: [
'%s/%s-darwin-x64.tar.gz',
'%s/%s-darwin-x64.tar.xz',
'%s/%s-darwin-arm64.tar.gz',
'%s/%s-darwin-arm64.tar.xz',
'%s/%s-linux-arm.tar.gz',
'%s/%s-linux-arm.tar.xz',
'%s/%s-linux-x64.tar.gz',
'%s/%s-linux-x64.tar.xz',
'%s/%s-win32-x64.tar.gz',
'%s/%s-win32-x64.tar.xz',
'%s/%s-win32-x86.tar.gz',
'%s/%s-win32-x86.tar.xz',
],
[Channel.LEGACY]: [
`${LEGACY_PATH}/%s-darwin-x64.tar.gz`, // sfdx-cli
`${LEGACY_PATH}/%s-darwin-x64.tar.xz`, // sfdx-cli
`${LEGACY_PATH}/%s-linux-arm.tar.gz`, // sfdx-cli
`${LEGACY_PATH}/%s-linux-arm.tar.xz`, // sfdx-cli
`${LEGACY_PATH}/%s-linux-x64.tar.gz`, // sfdx-cli
`${LEGACY_PATH}/%s-linux-x64.tar.xz`, // sfdx-cli
`${LEGACY_PATH}/%s-windows-x64.tar.gz`, // sfdx-cli
`${LEGACY_PATH}/%s-windows-x64.tar.xz`, // sfdx-cli
`${LEGACY_PATH}/%s-windows-x86.tar.gz`, // sfdx-cli
`${LEGACY_PATH}/%s-windows-x86.tar.xz`, // sfdx-cli
`${LEGACY_TOP_LEVEL_PATH}/%s-linux-amd64.tar.gz`,
`${LEGACY_TOP_LEVEL_PATH}/%s-linux-amd64.tar.xz`,
],
};
const CHANNEL_MAPPING: ChannelMapping = {
[Location.NPM]: {
[Channel.STABLE_RC]: Channel.LATEST_RC,
[Channel.STABLE]: Channel.LATEST,
[Channel.LATEST_RC]: Channel.LATEST_RC,
[Channel.NIGHTLY]: Channel.NIGHTLY,
[Channel.LATEST]: Channel.LATEST,
[Channel.LEGACY]: Channel.LEGACY,
},
[Location.ARCHIVE]: {
[Channel.LATEST_RC]: Channel.STABLE_RC,
[Channel.LATEST]: Channel.STABLE,
[Channel.STABLE_RC]: Channel.STABLE_RC,
[Channel.NIGHTLY]: Channel.NIGHTLY,
[Channel.STABLE]: Channel.STABLE,
[Channel.LEGACY]: Channel.LEGACY,
},
};
const CLI_META = {
[CLI.SFDX]: {
npm: 'https://www.npmjs.com/package/sfdx-cli',
repoName: 'sfdx-cli',
packageName: 'sfdx-cli',
},
[CLI.SF]: {
npm: 'https://www.npmjs.com/package/@salesforce/cli',
repoName: 'cli',
packageName: '@salesforce/cli',
},
};
export default class Inspect extends SfCommand<InspectResult> {
public static readonly summary = messages.getMessage('description');
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessages('examples');
public static readonly flags = {
dependencies: Flags.string({
summary: messages.getMessage('flags.dependencies.summary'),
char: 'd',
multiple: true,
}),
salesforce: Flags.boolean({
summary: messages.getMessage('flags.salesforce.summary'),
char: 's',
default: false,
}),
channels: Flags.string({
summary: messages.getMessage('flags.channels.summary'),
char: 'c',
options: Object.values(Channel),
required: true,
multiple: true,
}),
locations: Flags.string({
summary: messages.getMessage('flags.locations.summary'),
char: 'l',
options: Object.values(Location),
required: true,
multiple: true,
}),
cli: Flags.custom<CLI>({
options: Object.values(CLI),
})({
summary: messages.getMessage('flags.cli.summary'),
default: CLI.SFDX,
required: true,
}),
};
public workingDir = path.join(os.tmpdir(), 'cli_inspection');
public archives?: Archives;
private flags!: Interfaces.InferredFlags<typeof Inspect.flags>;
public async run(): Promise<InspectResult> {
const { flags } = await this.parse(Inspect);
this.flags = flags;
const locations = this.flags.locations as Location[];
const channels = this.flags.channels as Channel[];
if (this.flags.cli === CLI.SF && channels.includes(Channel.LEGACY)) {
throw new SfError('the sf CLI does not have a legacy channel');
}
this.log(`Working Directory: ${this.workingDir}`);
// ensure that we are starting with a clean directory
try {
await fs.rm(this.workingDir, { recursive: true, force: true });
} catch {
// error means that folder doesn't exist which is okay
}
await fs.mkdir(this.workingDir, { recursive: true });
this.initArchives();
const results = [
...(locations.includes(Location.ARCHIVE) ? await this.inspectArchives(channels) : []),
...(locations.includes(Location.NPM) ? await this.inspectNpm(channels) : []),
];
this.logResults(results, locations, channels);
return results;
}
private initArchives(): void {
const cli = ensure<CLI>(this.flags.cli);
const stablePath = `https://developer.salesforce.com/media/salesforce-cli/${cli}/channels/stable`;
const stableRcPath = `https://developer.salesforce.com/media/salesforce-cli/${cli}/channels/stable-rc`;
const nightlyPath = `https://developer.salesforce.com/media/salesforce-cli/${cli}/channels/nightly`;
this.archives = {} as Archives;
for (const [channel, paths] of entriesOf(ARCHIVES)) {
if (channel === Channel.LEGACY && cli === CLI.SFDX) {
this.archives[channel] = paths.map((p) => {
if (p.includes('amd64')) {
return util.format(p, this.flags.cli);
} else {
return util.format(p, CLI_META[this.flags.cli].packageName);
}
});
} else if (channel === Channel.STABLE) {
this.archives[channel] = paths.map((p) => util.format(p, stablePath, this.flags.cli));
} else if (channel === Channel.STABLE_RC) {
this.archives[channel] = paths.map((p) => util.format(p, stableRcPath, this.flags.cli));
} else if (channel === Channel.NIGHTLY) {
this.archives[channel] = paths.map((p) => util.format(p, nightlyPath, this.flags.cli));
}
}
}
private async inspectArchives(channels: Channel[]): Promise<Info[]> {
const tarDir = await mkdir(this.workingDir, 'tar');
const pathsByChannel = Object.fromEntries(
channels
// the enums are not smart enough to know that they'll definitely be archive channels
.map((c) => CHANNEL_MAPPING[Location.ARCHIVE][c] as ArchiveChannel)
.map((c) => [c, this.archives?.[CHANNEL_MAPPING[Location.ARCHIVE][c] as ArchiveChannel]])
);
const results: Info[] = [];
for (const channel of Object.keys(pathsByChannel) as Channel[]) {
this.log(`---- ${Location.ARCHIVE} ${channel} ----`);
for (const archivePath of pathsByChannel[channel] ?? []) {
this.spinner.start(`Downloading: ${chalk.cyan(archivePath)}`);
const curlResult = shelljs.exec(`curl ${archivePath} -Os`, { cwd: tarDir });
this.spinner.stop();
if (curlResult.code !== 0) {
this.log(chalk.red('Download failed. That is a big deal. Investigate immediately.'));
continue;
}
const filename = path.basename(archivePath);
const unpackedDir = await mkdir(this.workingDir, 'unpacked', filename);
this.spinner.start(`Unpacking: ${chalk.cyan(unpackedDir)}`);
const tarResult = shelljs.exec(`tar -xf ${filename} -C ${unpackedDir} --strip-components 1`, { cwd: tarDir });
this.spinner.stop();
if (tarResult.code !== 0) {
this.log(chalk.red('Failed to unpack. Skipping...'));
continue;
}
const pkgJson = await readPackageJson(unpackedDir);
results.push({
dependencies: await this.getDependencies(unpackedDir),
origin: archivePath,
channel,
location: Location.ARCHIVE,
version: pkgJson.version,
});
}
}
return results;
}
private async inspectNpm(channels: Channel[]): Promise<Info[]> {
const cliMeta = CLI_META[this.flags.cli];
const npmDir = await mkdir(this.workingDir, 'npm');
const results: Info[] = [];
const tags = channels.map((c) => CHANNEL_MAPPING[Location.NPM][c]).filter((c) => c !== Channel.LEGACY);
for (const tag of tags) {
this.log(`---- ${Location.NPM} ${tag} ----`);
const installDir = await mkdir(npmDir, tag);
const name = `${cliMeta.packageName}@${tag}`;
this.spinner.start(`Installing: ${chalk.cyan(name)}`);
shelljs.exec(`npm install ${name}`, { cwd: installDir, silent: true });
this.spinner.stop();
const pkgJson = await readPackageJson(path.join(installDir, 'node_modules', cliMeta.repoName));
results.push({
dependencies: await this.getDependencies(installDir),
origin: `${cliMeta.npm}/v/${pkgJson.version}`,
channel: tag,
location: Location.NPM,
version: pkgJson.version,
});
}
return results;
}
private async getDependencies(directory: string): Promise<Dependency[]> {
const depGlobs: string[] = [];
if (this.flags.dependencies) {
const globPatterns = this.flags.dependencies.map((d) => `${directory}/node_modules/${d}`);
depGlobs.push(...globPatterns);
}
if (this.flags.salesforce) {
const globPatterns = SALESFORCE_DEP_GLOBS.map((d) => `${directory}/node_modules/${d}`);
depGlobs.push(...globPatterns);
}
const dependencyPaths = await fg(depGlobs, { onlyDirectories: true, deep: 1 });
const dependencies: Dependency[] = [];
for (const dep of dependencyPaths) {
const pkg = await readPackageJson(dep);
dependencies.push({
name: pkg.name,
version: pkg.version,
});
}
return dependencies;
}
private logResults(results: Info[], locations: Location[], channels: Channel[]): void {
let allMatch: boolean | undefined;
let npmAndArchivesMatch: boolean | undefined;
this.log();
results.forEach((result) => {
this.log(chalk.bold(`${result.origin}: ${chalk.green(result.version)}`));
result.dependencies.forEach((dep) => {
this.log(` ${dep.name}: ${dep.version}`);
});
});
this.log();
if (locations.includes(Location.ARCHIVE)) {
const archivesMatch =
new Set(results.filter((r) => r.location === Location.ARCHIVE).map((r) => r.version)).size === 1;
this.log(`${'All archives match?'} ${archivesMatch ? chalk.green(archivesMatch) : chalk.yellow(archivesMatch)}`);
channels.forEach((channel) => {
allMatch = new Set(results.filter((r) => r.channel === channel).map((r) => r.version)).size === 1;
this.log(
`${`All ${Location.ARCHIVE}@${channel} versions match?`} ${
allMatch ? chalk.green(allMatch) : chalk.red(allMatch)
}`
);
});
}
if (locations.includes(Location.NPM) && locations.includes(Location.ARCHIVE)) {
channels
.filter((c) => c !== Channel.LEGACY)
.forEach((channel) => {
const npmChannel = CHANNEL_MAPPING[Location.NPM][channel];
const archiveChannel = CHANNEL_MAPPING[Location.ARCHIVE][channel];
npmAndArchivesMatch =
new Set(
results.filter((r) => r.channel === npmChannel || r.channel === archiveChannel).map((r) => r.version)
).size === 1;
const match = npmAndArchivesMatch ? chalk.green(true) : chalk.red(false);
this.log(
`${Location.NPM}@${npmChannel} and all ${Location.ARCHIVE}@${archiveChannel} versions match? ${match}`
);
});
}
// npmAndArchivesMatch can be undefined
if ((npmAndArchivesMatch !== undefined && !npmAndArchivesMatch) || !allMatch) {
throw new SfError('Version Mismatch');
}
}
}
const readPackageJson = async (pkgDir: string): Promise<PackageJson> => {
const fileData = await fs.readFile(path.join(pkgDir, 'package.json'), 'utf8');
return parseJson(fileData, path.join(pkgDir, 'package.json'), false) as PackageJson;
};
const mkdir = async (...parts: string[]): Promise<string> => {
const dir = path.resolve(path.join(...parts));
await fs.mkdir(dir, { recursive: true });
return dir;
};