generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdeploy.ts
More file actions
341 lines (302 loc) · 12.6 KB
/
deploy.ts
File metadata and controls
341 lines (302 loc) · 12.6 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
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
/*
* 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 { relative } from 'node:path';
import { ConfigAggregator, Messages, Org, SfError, SfProject } from '@salesforce/core';
import { Duration } from '@salesforce/kit';
import { Nullable } from '@salesforce/ts-types';
import {
ComponentSet,
ComponentSetBuilder,
ComponentStatus,
DeployResult,
DestructiveChangesType,
FileResponseSuccess,
MetadataApiDeploy,
MetadataApiDeployOptions,
RegistryAccess,
RequestStatus,
} from '@salesforce/source-deploy-retrieve';
import { SourceTracking } from '@salesforce/source-tracking';
import ConfigMeta, { ConfigVars } from '../configMeta.js';
import { getPackageDirs, getSourceApiVersion } from './project.js';
import { API, PathInfo, TestLevel } from './types.js';
import { DEPLOY_STATUS_CODES } from './errorCodes.js';
import { DeployCache } from './deployCache.js';
import { writeManifest } from './manifestCache.js';
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
export const cacheMessages = Messages.loadMessages('@salesforce/plugin-deploy-retrieve', 'cache');
const deployMessages = Messages.loadMessages('@salesforce/plugin-deploy-retrieve', 'deploy.metadata');
export type DeployOptions = {
api: API;
'target-org': string;
'test-level': TestLevel;
async?: boolean;
'api-version'?: string;
'dry-run'?: boolean;
'ignore-conflicts'?: boolean;
'ignore-errors'?: boolean;
'ignore-warnings'?: boolean;
manifest?: string;
metadata?: string[];
'metadata-dir'?: PathInfo;
'source-dir'?: string[];
tests?: string[];
wait?: Duration;
verbose?: boolean;
concise?: boolean;
'single-package'?: boolean;
status?: RequestStatus;
'pre-destructive-changes'?: string;
'post-destructive-changes'?: string;
'purge-on-delete'?: boolean;
};
/** Manifest is expected. You cannot pass metadata and source-dir array--use those to get a manifest */
export type CachedOptions = Omit<DeployOptions, 'wait' | 'metadata' | 'source-dir'> & {
wait: number;
/** whether the user passed in anything for metadata-dir (could be a folder, could be a zip) */
isMdapi: boolean;
} & Partial<Pick<DeployOptions, 'manifest'>>;
export function validateTests(testLevel: TestLevel | undefined, tests: Nullable<string[]>): boolean {
return !(testLevel === TestLevel.RunSpecifiedTests && (tests ?? []).length === 0);
}
export async function resolveApi(existingConfigAggregator?: ConfigAggregator): Promise<API> {
const agg = existingConfigAggregator ?? (await ConfigAggregator.create({ customConfigMeta: ConfigMeta }));
const restDeployConfig = agg.getInfo(ConfigVars.ORG_METADATA_REST_DEPLOY)?.value;
return restDeployConfig === 'true' ? API.REST : API.SOAP;
}
export async function buildComponentSet(opts: Partial<DeployOptions>, stl?: SourceTracking): Promise<ComponentSet> {
// if you specify nothing, you'll get the changes, like sfdx push, as long as there's an stl
if (!opts['source-dir'] && !opts.manifest && !opts.metadata && stl) {
/** localChangesAsComponentSet returned an array to support multiple sequential deploys.
* `sf` chooses not to support this so we force one ComponentSet
*/
const cs = (await stl.localChangesAsComponentSet(false))[0] ?? new ComponentSet(undefined, stl.registry);
// stl produces a cs with api version already set. command might have specified a version.
if (opts['api-version']) {
cs.apiVersion = opts['api-version'];
cs.sourceApiVersion = opts['api-version'];
}
return cs;
}
return ComponentSetBuilder.build({
apiversion: opts['api-version'],
sourceapiversion: await getSourceApiVersion(),
sourcepath: opts['source-dir'],
...(opts.manifest
? {
manifest: {
manifestPath: opts.manifest,
directoryPaths: await getPackageDirs(),
destructiveChangesPre: opts['pre-destructive-changes'],
destructiveChangesPost: opts['post-destructive-changes'],
},
}
: {}),
...(opts.metadata ? { metadata: { metadataEntries: opts.metadata, directoryPaths: await getPackageDirs() } } : {}),
projectDir: stl?.projectPath,
});
}
export async function executeDeploy(
opts: Partial<DeployOptions>,
project?: SfProject,
id?: string,
throwOnEmpty?: true
): Promise<{ deploy: MetadataApiDeploy; componentSet?: ComponentSet }>;
export async function executeDeploy(
opts: Partial<DeployOptions>,
project?: SfProject,
id?: string,
throwOnEmpty = false
): Promise<{ deploy?: MetadataApiDeploy; componentSet?: ComponentSet }> {
const apiOptions = buildApiOptions(opts);
let deploy: MetadataApiDeploy | undefined;
let componentSet: ComponentSet | undefined;
let registry: RegistryAccess | undefined;
const org = await Org.create({ aliasOrUsername: opts['target-org'] });
// for mdapi deploys, use the passed in api-version.
const usernameOrConnection = org.getConnection(opts['metadata-dir'] ? opts['api-version'] : undefined);
if (opts['metadata-dir']) {
if (id) {
deploy = new MetadataApiDeploy({ id, usernameOrConnection });
} else {
const key = opts['metadata-dir'].type === 'directory' ? 'mdapiPath' : 'zipPath';
deploy = new MetadataApiDeploy({
[key]: opts['metadata-dir'].path,
usernameOrConnection,
apiOptions: { ...apiOptions, singlePackage: opts['single-package'] ?? false },
});
await deploy.start();
}
} else {
// instantiate source tracking
// stl will decide, based on the org's properties, what needs to be done
const stl = await SourceTracking.create({
org,
// mdapi format deploys don't require a project, but at this point we need one
project: project ?? (await SfProject.resolve()),
subscribeSDREvents: !opts['dry-run'] || !(await org.tracksSource()),
ignoreConflicts: opts['ignore-conflicts'],
});
registry = stl.registry;
componentSet = await buildComponentSet(opts, stl);
if (componentSet.size === 0) {
if (opts['source-dir'] ?? opts.manifest ?? opts.metadata ?? throwOnEmpty) {
// the user specified something to deploy, but there isn't anything
throw new SfError(
deployMessages.getMessage('error.nothingToDeploy'),
'NothingToDeploy',
deployMessages.getMessages('error.nothingToDeploy.Actions')
);
} else {
// this is a push-like "deploy changes" but there aren't any.
// users unanimously think this should not be an error https://github.com/forcedotcom/cli/discussions/2065
return {};
}
}
deploy = id
? new MetadataApiDeploy({ id, usernameOrConnection, components: componentSet })
: await componentSet.deploy({
usernameOrConnection,
apiOptions,
});
}
if (!deploy.id) {
throw new SfError('The deploy id is not available.');
}
// does not apply to mdapi deploys
const manifestPath = componentSet
? await writeManifest(deploy.id, componentSet, registry ?? new RegistryAccess())
: undefined;
await DeployCache.set(deploy.id, { ...opts, manifest: manifestPath });
return { deploy, componentSet };
}
export async function cancelDeploy(opts: Partial<DeployOptions>, id: string): Promise<DeployResult> {
const org = await Org.create({ aliasOrUsername: opts['target-org'] });
const usernameOrConnection = org.getUsername() ?? org.getConnection();
const deploy = new MetadataApiDeploy({ usernameOrConnection, id });
if (!deploy.id) {
throw new SfError('The deploy id is not available.');
}
await DeployCache.set(deploy.id, { ...opts });
await deploy.cancel();
return deploy.pollStatus({
frequency: Duration.seconds(1),
timeout: opts.wait ?? Duration.minutes(33),
});
}
export async function cancelDeployAsync(opts: Partial<DeployOptions>, id: string): Promise<{ id: string }> {
const org = await Org.create({ aliasOrUsername: opts['target-org'] });
const usernameOrConnection = org.getUsername() ?? org.getConnection();
const deploy = new MetadataApiDeploy({ usernameOrConnection, id });
await deploy.cancel();
if (!deploy.id) {
throw new SfError('The deploy id is not available.');
}
return { id: deploy.id };
}
export function determineExitCode(result: DeployResult, async = false): number {
if (async) {
return result.response.status === RequestStatus.Succeeded ? 0 : 1;
}
return DEPLOY_STATUS_CODES.get(result.response.status) ?? 1;
}
export const isNotResumable = (status?: RequestStatus): boolean =>
status !== undefined &&
[RequestStatus.Succeeded, RequestStatus.Failed, RequestStatus.SucceededPartial, RequestStatus.Canceled].includes(
status
);
/** apply some defaults to the DeployOptions object */
const buildApiOptions = (opts: Partial<DeployOptions>): MetadataApiDeployOptions['apiOptions'] => ({
checkOnly: opts['dry-run'] ?? false,
ignoreWarnings: opts['ignore-warnings'] ?? false,
rest: opts.api === API['REST'],
rollbackOnError: !opts['ignore-errors'] || false,
...(opts.tests ? { runTests: opts.tests } : {}),
...(opts['test-level'] ? { testLevel: opts['test-level'] } : {}),
purgeOnDelete: opts['purge-on-delete'] ?? false,
});
export function buildDeployUrl(org: Org, deployId: string): string {
const orgInstanceUrl = String(org.getField(Org.Fields.INSTANCE_URL));
return `${orgInstanceUrl}/lightning/setup/DeployStatus/page?address=%2Fchangemgmt%2FmonitorDeploymentsDetails.apexp%3FasyncId%3D${deployId}%26retURL%3D%252Fchangemgmt%252FmonitorDeployment.apexp`;
}
/**
* Creates synthetic FileResponse objects for components in pre-destructive changes.
* This ensures all file paths (e.g., .cls and .xml for ApexClass, or all LWC bundle files)
* are shown in the deployment results table. This is needed because pre-destructive files
* are deleted BEFORE the deploy, so getFileResponses() cannot access them.
*
* @param componentSet - The ComponentSet from the deployment (before deploy executes)
* @param project - The SfProject to resolve file paths from
* @returns Array of synthetic FileResponseSuccess objects representing pre-deleted files
*/
export async function buildPreDestructiveFileResponses(
componentSet?: ComponentSet,
project?: SfProject
): Promise<FileResponseSuccess[]> {
if (!componentSet || !project) {
return [];
}
const fileResponses: FileResponseSuccess[] = [];
// Get all source components and filter for pre-destructive ones
const allComponents = componentSet.getSourceComponents().toArray();
const preDestructiveComponents = allComponents.filter(
(component) => component.getDestructiveChangesType() === DestructiveChangesType.PRE
);
if (preDestructiveComponents.length === 0) {
return [] as FileResponseSuccess[];
}
// Build metadata entries for ComponentSetBuilder
const metadataEntries = preDestructiveComponents.map((comp) => `${comp.type.name}:${comp.fullName}`);
// Resolve the components from the project to get their file paths
try {
const resolvedComponentSet = await ComponentSetBuilder.build({
metadata: {
metadataEntries,
directoryPaths: await getPackageDirs(),
},
projectDir: project.getPath(),
});
const resolvedComponents = resolvedComponentSet.getSourceComponents().toArray();
preDestructiveComponents.length = 0;
preDestructiveComponents.push(...resolvedComponents);
} catch (error) {
// If this's not resolve, try to resolve with registry only
}
for (const component of preDestructiveComponents) {
// Get all file paths for this component (metadata XML + content files)
const filePaths: string[] = [];
const projectPath = project.getPath();
if (component.xml) {
const relativePath = relative(projectPath, component.xml);
filePaths.push(relativePath);
}
// Add all content files (for bundles, this includes all files in the directory)
const contentPaths = component.walkContent();
for (const contentPath of contentPaths) {
const relativePath = relative(projectPath, contentPath);
filePaths.push(relativePath);
}
for (const filePath of filePaths) {
fileResponses.push({
fullName: component.fullName,
type: component.type.name,
state: ComponentStatus.Deleted,
filePath,
});
}
}
return fileResponses;
}