This repository was archived by the owner on Mar 25, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathretrieve.ts
More file actions
302 lines (281 loc) · 10.5 KB
/
retrieve.ts
File metadata and controls
302 lines (281 loc) · 10.5 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
/*
* 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 { Lifecycle, Messages, Org, SfError, SfProject } from '@salesforce/core';
import { Duration } from '@salesforce/kit';
import {
ComponentSetBuilder,
MetadataApiRetrieve,
RequestStatus,
RetrieveResult,
RetrieveVersionData,
} from '@salesforce/source-deploy-retrieve';
import { Optional, ensure, ensureString } from '@salesforce/ts-types';
import { Flags, loglevel, requiredOrgFlagWithDeprecations, Ux } from '@salesforce/sf-plugins-core';
import { Interfaces } from '@oclif/core';
import { resolveZipFileName, SourceCommand } from '../../../sourceCommand.js';
import { Stash } from '../../../stash.js';
import {
RetrieveCommandAsyncResult,
RetrieveCommandResult,
RetrieveResultFormatter,
} from '../../../formatters/mdapi/retrieveResultFormatter.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-source', 'md.retrieve');
const spinnerMessages = Messages.loadMessages('@salesforce/plugin-source', 'spinner');
const retrieveMessages = Messages.loadMessages('@salesforce/plugin-source', 'retrieve');
export type RetrieveCommandCombinedResult = RetrieveCommandResult | RetrieveCommandAsyncResult;
const replacement = 'project retrieve start';
export class Retrieve extends SourceCommand {
public static readonly state = 'deprecated';
public static readonly deprecationOptions = {
to: replacement,
message: messages.getMessage('deprecation', [replacement]),
};
public static readonly hidden = true;
public static readonly summary = messages.getMessage('retrieve.summary');
public static readonly description = messages.getMessage('retrieve.description');
public static readonly examples = messages.getMessages('retrieve.examples');
public static readonly flags = {
loglevel,
'target-org': requiredOrgFlagWithDeprecations,
retrievetargetdir: Flags.directory({
char: 'r',
summary: messages.getMessage('flags.retrievetargetdir.summary'),
required: true,
}),
unpackaged: Flags.file({
char: 'k',
summary: messages.getMessage('flags.unpackaged.summary'),
exclusive: ['sourcedir', 'packagenames'],
}),
sourcedir: Flags.directory({
char: 'd',
summary: messages.getMessage('flags.sourcedir.summary'),
exclusive: ['unpackaged', 'packagenames'],
}),
packagenames: Flags.string({
multiple: true,
delimiter: ',',
char: 'p',
summary: messages.getMessage('flags.packagenames.summary'),
exclusive: ['sourcedir', 'unpackaged'],
}),
singlepackage: Flags.boolean({
char: 's',
description: messages.getMessage('flags.singlepackage.description'),
summary: messages.getMessage('flags.singlepackage.summary'),
}),
zipfilename: Flags.string({
char: 'n',
summary: messages.getMessage('flags.zipfilename.summary'),
}),
unzip: Flags.boolean({
char: 'z',
summary: messages.getMessage('flags.unzip.summary'),
}),
wait: Flags.duration({
char: 'w',
unit: 'minutes',
summary: messages.getMessage('flags.wait.summary'),
default: Duration.minutes(1440), // 24 hours is a reasonable default versus -1 (no timeout)
}),
apiversion: Flags.string({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore force char override for backward compat
char: 'a',
description: messages.getMessage('flags.apiversion.description'),
summary: messages.getMessage('flags.apiversion.summary'),
}),
verbose: Flags.boolean({
summary: messages.getMessage('flags.verbose.summary'),
}),
};
protected retrieveResult: RetrieveResult | undefined;
private sourceDir: string | undefined;
private retrieveTargetDir!: string;
private zipFileName: string | undefined;
private unzip: boolean | undefined;
// will be set to `flags.wait` (which has a default value) when executed.
private wait!: Duration;
private isAsync: boolean | undefined;
private mdapiRetrieve: MetadataApiRetrieve | undefined;
private flags!: Interfaces.InferredFlags<typeof Retrieve.flags>;
private org!: Org | undefined;
public async run(): Promise<RetrieveCommandCombinedResult> {
this.flags = (await this.parse(Retrieve)).flags;
this.retrieveTargetDir = this.resolveOutputDir(this.flags.retrievetargetdir);
this.org = this.flags['target-org'];
await this.retrieve();
this.resolveSuccess();
return this.formatResult();
}
protected async retrieve(): Promise<void> {
const packagenames = this.flags.packagenames;
if (packagenames === this.unzip && !this.flags.unpackaged) {
this.sourceDir = this.resolveRootDir(this.flags.sourcedir);
}
this.retrieveTargetDir = this.resolveOutputDir(this.flags.retrievetargetdir);
const manifest = this.resolveManifest(this.flags.unpackaged);
const singlePackage = this.flags.singlepackage;
this.zipFileName = resolveZipFileName(this.flags.zipfilename);
this.unzip = this.flags.unzip;
const waitFlag = this.flags.wait;
this.wait = waitFlag.minutes === -1 ? Duration.days(7) : waitFlag;
this.isAsync = this.wait.quantity === 0;
if (singlePackage && packagenames?.length) {
throw new SfError(messages.getMessage('InvalidPackageNames', [packagenames.toString()]), 'InvalidPackageNames');
}
this.spinner.start(spinnerMessages.getMessage('retrieve.main', [this.org?.getUsername()]));
this.spinner.status = spinnerMessages.getMessage('retrieve.componentSetBuild');
this.componentSet = await ComponentSetBuilder.build({
// use the apiVersion if provided.
// Manifests default to their specified apiVersion(ComponentSetBuilder handles this)
// and not specifying the apiVersion will use the max for the org/Connection
apiversion: this.flags.apiversion,
packagenames,
sourcepath: this.sourceDir ? [this.sourceDir] : undefined,
manifest: manifest
? {
manifestPath: manifest,
directoryPaths: [],
}
: undefined,
});
await Lifecycle.getInstance().emit('preretrieve', { packageXmlPath: manifest });
const username = this.org?.getUsername() ?? '';
// eslint-disable-next-line @typescript-eslint/require-await
Lifecycle.getInstance().on('apiVersionRetrieve', async (apiData: RetrieveVersionData) => {
this.log(
retrieveMessages.getMessage('apiVersionMsgDetailed', [
'Retrieving',
apiData.manifestVersion,
username,
apiData.apiVersion,
])
);
});
this.spinner.status = spinnerMessages.getMessage('retrieve.sendingRequest');
this.mdapiRetrieve = await this.componentSet.retrieve({
usernameOrConnection: username,
output: this.retrieveTargetDir,
packageOptions: this.flags.packagenames,
format: 'metadata',
singlePackage,
zipFileName: this.zipFileName,
unzip: this.unzip,
});
Stash.set('MDAPI_RETRIEVE', {
jobid: this.mdapiRetrieve.id ?? '',
retrievetargetdir: this.retrieveTargetDir,
zipfilename: this.zipFileName,
unzip: this.unzip,
});
this.log(`Retrieve ID: ${this.mdapiRetrieve.id ?? ''}`);
if (this.isAsync) {
this.spinner.stop('queued');
} else {
this.spinner.status = spinnerMessages.getMessage('retrieve.polling');
this.retrieveResult = await this.mdapiRetrieve.pollStatus({
frequency: Duration.milliseconds(1000),
timeout: this.wait,
});
this.spinner.stop();
}
}
protected resolveSuccess(): void {
const StatusCodeMap = new Map<RequestStatus, number>([
[RequestStatus.Succeeded, 0],
[RequestStatus.Canceled, 1],
[RequestStatus.Failed, 1],
[RequestStatus.InProgress, 69],
[RequestStatus.Pending, 69],
[RequestStatus.Canceling, 69],
]);
if (!this.isAsync) {
this.setExitCode(StatusCodeMap.get(this.retrieveResult?.response.status as RequestStatus) ?? 1);
}
}
protected formatResult(): RetrieveCommandResult | RetrieveCommandAsyncResult {
// async result
if (this.isAsync) {
const targetUsername = this.flags['target-org'].getUsername();
const cmdFlags = `--jobid ${ensureString(this.mdapiRetrieve?.id)} --retrievetargetdir ${this.retrieveTargetDir}${
targetUsername ? ` --targetusername ${targetUsername}` : ''
}`;
this.log('');
this.log(messages.getMessage('checkStatus', [cmdFlags]));
return {
done: false,
id: this.mdapiRetrieve?.id ?? '',
state: 'Queued',
status: 'Queued',
timedOut: true,
};
} else {
const formatterOptions = {
waitTime: this.wait.quantity,
verbose: this.flags.verbose ?? false,
retrieveTargetDir: this.retrieveTargetDir ?? '',
zipFileName: this.zipFileName,
unzip: this.unzip,
};
const formatter = new RetrieveResultFormatter(
new Ux({ jsonEnabled: this.jsonEnabled() }),
formatterOptions,
ensure(this.retrieveResult)
);
if (!this.jsonEnabled()) {
formatter.display();
}
return formatter.getJson();
}
}
private resolveProjectPath(): string {
try {
return SfProject.getInstance().getDefaultPackage().fullPath;
} catch (error) {
this.debug('No SFDX project found for default package directory');
}
return '';
}
private resolveRootDir(rootDir?: string): string {
return rootDir
? this.ensureFlagPath({
flagName: 'sourcedir',
path: rootDir,
type: 'dir',
throwOnENOENT: true,
})
: this.resolveProjectPath();
}
private resolveOutputDir(outputDir?: string): string {
return this.ensureFlagPath({
flagName: 'retrievetargetdir',
path: outputDir,
type: 'dir',
});
}
private resolveManifest(manifestPath?: string): Optional<string> {
if (manifestPath?.length) {
return this.ensureFlagPath({
flagName: 'unpackaged',
path: manifestPath,
type: 'file',
throwOnENOENT: true,
});
}
}
}