generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdoctor.ts
More file actions
313 lines (278 loc) · 9.88 KB
/
doctor.ts
File metadata and controls
313 lines (278 loc) · 9.88 KB
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
/*
* Copyright 2026, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import fs from 'node:fs';
import { join, dirname, basename } from 'node:path';
import { Messages, SfError } from '@salesforce/core';
import { Env, omit } from '@salesforce/kit';
import type { AnyJson, KeyValue } from '@salesforce/ts-types';
import Interfaces from '@oclif/core/interfaces';
import { Diagnostics, DiagnosticStatus } from './diagnostics.js';
export type SfDoctor = {
addCommandName(commandName: string): void;
addDiagnosticStatus(status: DiagnosticStatus): void;
addPluginData(pluginName: string, data: AnyJson): void;
addSuggestion(suggestion: string): void;
closeStderr(): void;
closeStdout(): void;
createStderrWriteStream(fullPath: string): void;
createStdoutWriteStream(fullPath: string): void;
diagnose(): Array<Promise<void>>;
getDiagnosis(): SfDoctorDiagnosis;
getDoctoredFilePath(filePath: string): string;
setExitCode(code: string | number): void;
writeFileSync(filePath: string, contents: string): string;
writeStderr(contents: string): Promise<boolean>;
writeStdout(contents: string): Promise<boolean>;
};
// oclif has some properties marked as optional in the Interface, but they will be present after Load() is called
type CliConfig = Partial<Interfaces.Config> & { nodeEngine: string } & Pick<
Required<Interfaces.Config>,
'windows' | 'userAgent' | 'shell' | 'channel'
>;
export type SfDoctorDiagnosis = {
versionDetail: Omit<Interfaces.VersionDetails, 'pluginVersions'> & { pluginVersions: string[] };
sfdxEnvVars: Array<KeyValue<string>>;
sfEnvVars: Array<KeyValue<string>>;
proxyEnvVars: Array<KeyValue<string>>;
cliConfig: CliConfig;
pluginSpecificData: { [pluginName: string]: AnyJson[] };
diagnosticResults: DiagnosticStatus[];
suggestions: string[];
commandName?: string;
commandExitCode?: string | number;
logFilePaths: string[];
};
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-info', 'doctor');
const PINNED_SUGGESTIONS = [
messages.getMessage('pinnedSuggestions.checkGitHubIssues'),
messages.getMessage('pinnedSuggestions.checkSfdcStatus'),
];
// private config from the CLI
// eslint-disable-next-line no-underscore-dangle
let __cliConfig: Interfaces.Config;
export class Doctor implements SfDoctor {
// singleton instance
private static instance: SfDoctor;
public readonly id: number;
// Contains all gathered data and results of diagnostics.
private readonly diagnosis: SfDoctorDiagnosis;
private stdoutWriteStream: fs.WriteStream | undefined;
private stderrWriteStream: fs.WriteStream | undefined;
private constructor(config: Interfaces.Config) {
this.id = Date.now();
__cliConfig = config;
const sfdxEnvVars = new Env().entries().filter((e) => e[0].startsWith('SFDX_'));
const sfEnvVars = new Env().entries().filter((e) => e[0].startsWith('SF_'));
const proxyEnvVars = new Env()
.entries()
.filter((e) => ['http_proxy', 'https_proxy', 'no_proxy'].includes(e[0].toLowerCase()));
const cliConfig = omit(config, [
'plugins',
'pjson',
'userPJSON',
'options',
'_commandIDs',
'rootPlugin',
]) as CliConfig;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
cliConfig.nodeEngine = config.pjson.engines.node as string;
const { pluginVersions, ...versionDetails } = config.versionDetails;
this.diagnosis = {
versionDetail: { ...versionDetails, pluginVersions: formatPlugins(config, pluginVersions ?? {}) },
sfdxEnvVars,
sfEnvVars,
proxyEnvVars,
cliConfig,
pluginSpecificData: {},
diagnosticResults: [],
suggestions: [...PINNED_SUGGESTIONS],
logFilePaths: [],
commandExitCode: 0,
};
}
/**
* Returns a singleton instance of an SfDoctor.
*/
public static getInstance(): SfDoctor {
if (!Doctor.instance) {
throw new SfError(messages.getMessage('doctorNotInitializedError'), 'SfDoctorInitError');
}
return Doctor.instance;
}
/**
* Returns true if Doctor has been initialized.
*/
public static isDoctorEnabled(): boolean {
return !!Doctor.instance;
}
/**
* Initializes a new instance of SfDoctor with CLI config data.
*
* @param config The oclif config for the CLI
* @param versionDetail The result of running a verbose version command
* @returns An instance of SfDoctor
*/
public static init(config: Interfaces.Config): SfDoctor {
if (Doctor.instance) {
return Doctor.instance;
}
Doctor.instance = new this(config);
return Doctor.instance;
}
/**
* Use the gathered data to discover potential problems by running all diagnostics.
*
* @returns An array of diagnostic promises.
*/
public diagnose(): Array<Promise<void>> {
return new Diagnostics(this, __cliConfig).run();
}
/**
* Add a suggestion in the form of:
* "Because of <this data point> we recommend to <suggestion>"
*
* @param suggestion A suggestion for the CLI user to try based on gathered data
*/
public addSuggestion(suggestion: string): void {
this.diagnosis.suggestions.push(suggestion);
}
/**
* Add a diagnostic test status.
*
* @param status a diagnostic test status
*/
public addDiagnosticStatus(status: DiagnosticStatus): void {
this.diagnosis.diagnosticResults.push(status);
}
/**
* Add diagnostic data that is specific to the passed plugin name.
*
* @param pluginName The name in the plugin's package.json
* @param data Any data to add to the doctor diagnosis that is specific
* to the plugin and a valid JSON value.
*/
public addPluginData(pluginName: string, data: AnyJson): void {
const pluginEntry = this.diagnosis.pluginSpecificData[pluginName];
if (pluginEntry) {
pluginEntry.push(data);
} else {
this.diagnosis.pluginSpecificData[pluginName] = [data];
}
}
/**
* Add a command name that the doctor will run to the diagnosis data for
* use by diagnostics.
*
* @param commandName The name of the command that the doctor will run. E.g., "force:org:list"
*/
public addCommandName(commandName: string): void {
this.diagnosis.commandName = commandName;
}
/**
* Returns all the data gathered, paths to doctor files, and recommendations.
*/
public getDiagnosis(): SfDoctorDiagnosis {
return { ...this.diagnosis };
}
/**
* Write a file with the provided path. The file name will be prepended
* with this doctor's id.
*
* E.g., `name = myContent.json` will write `1658350735579-myContent.json`
*
* @param filePath The path of the file to write.
* @param contents The string contents to write.
* @return The full path to the file.
*/
public writeFileSync(filePath: string, contents: string): string {
const fullPath = this.getDoctoredFilePath(filePath);
createOutputDir(fullPath);
this.diagnosis.logFilePaths.push(fullPath);
fs.writeFileSync(fullPath, contents);
return fullPath;
}
public writeStdout(contents: string): Promise<boolean> {
if (!this.stdoutWriteStream) {
throw new SfError(messages.getMessage('doctorNotInitializedError'), 'SfDoctorInitError');
}
return writeFile(this.stdoutWriteStream, contents);
}
public writeStderr(contents: string): Promise<boolean> {
if (!this.stderrWriteStream) {
throw new SfError(messages.getMessage('doctorNotInitializedError'), 'SfDoctorInitError');
}
return writeFile(this.stderrWriteStream, contents);
}
public createStdoutWriteStream(fullPath: string): void {
if (!this.stdoutWriteStream) {
createOutputDir(fullPath);
this.stdoutWriteStream = fs.createWriteStream(fullPath);
}
}
public createStderrWriteStream(fullPath: string): void {
if (!this.stderrWriteStream) {
createOutputDir(fullPath);
this.stderrWriteStream = fs.createWriteStream(join(fullPath));
}
}
public closeStderr(): void {
this.stderrWriteStream?.end();
this.stderrWriteStream?.close();
}
public closeStdout(): void {
this.stdoutWriteStream?.end();
this.stdoutWriteStream?.close();
}
public getDoctoredFilePath(filePath: string): string {
const dir = dirname(filePath);
const fileName = `${this.id}-${basename(filePath)}`;
const fullPath = join(dir, fileName);
this.diagnosis.logFilePaths.push(fullPath);
return fullPath;
}
public setExitCode(code: string | number): void {
this.diagnosis.commandExitCode = code;
}
}
export function formatPlugins(
config: Interfaces.Config,
plugins: Record<string, Interfaces.PluginVersionDetail>
): string[] {
function getFriendlyName(name: string): string {
const scope = config?.pjson?.oclif?.scope;
if (!scope) return name;
const match = name.match(`@${scope}/plugin-(.+)`);
if (!match) return name;
return match[1];
}
return Object.entries(plugins)
.map(([name, plugin]) => ({ name, ...plugin }))
.sort((a, b) => (a.name > b.name ? 1 : -1))
.map((plugin) =>
`${getFriendlyName(plugin.name)} ${plugin.version} (${plugin.type}) ${
plugin.type === 'link' ? plugin.root : ''
}`.trim()
);
}
const createOutputDir = (fullPath: string): void => {
const dir = dirname(fullPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
};
const writeFile = (stream: fs.WriteStream, contents: string): Promise<boolean> =>
Promise.resolve(stream.write(contents));