generated from salesforcecli/plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 18
/
deploy.ts
285 lines (267 loc) · 11.5 KB
/
deploy.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
/*
* 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
*/
import * as os from 'os';
import { flags, FlagsConfig } from '@salesforce/command';
import { Messages } from '@salesforce/core';
import { Duration, env } from '@salesforce/kit';
import { SourceTracking } from '@salesforce/source-tracking';
import { ComponentSetBuilder } from '@salesforce/source-deploy-retrieve';
import { DeployCommand, getVersionMessage, reportsFormatters, TestLevel } from '../../../deployCommand';
import { DeployCommandResult, DeployResultFormatter } from '../../../formatters/deployResultFormatter';
import {
DeployAsyncResultFormatter,
DeployCommandAsyncResult,
} from '../../../formatters/source/deployAsyncResultFormatter';
import { ProgressFormatter } from '../../../formatters/progressFormatter';
import { DeployProgressBarFormatter } from '../../../formatters/deployProgressBarFormatter';
import { DeployProgressStatusFormatter } from '../../../formatters/deployProgressStatusFormatter';
import { filterConflictsByComponentSet, trackingSetup, updateTracking } from '../../../trackingFunctions';
import { ResultFormatterOptions } from '../../../formatters/resultFormatter';
Messages.importMessagesDirectory(__dirname);
const messages = Messages.loadMessages('@salesforce/plugin-source', 'deploy');
// One of these flags must be specified for a valid deploy.
const xorFlags = ['manifest', 'metadata', 'sourcepath', 'validateddeployrequestid'];
export class Deploy extends DeployCommand {
public static readonly description = messages.getMessage('description');
public static readonly examples = messages.getMessage('examples').split(os.EOL);
public static readonly requiresProject = true;
public static readonly requiresUsername = true;
public static readonly flagsConfig: FlagsConfig = {
checkonly: flags.boolean({
char: 'c',
description: messages.getMessage('flags.checkonly'),
longDescription: messages.getMessage('flagsLong.checkonly'),
}),
soapdeploy: flags.boolean({
default: false,
description: messages.getMessage('flags.soapDeploy'),
}),
wait: flags.minutes({
char: 'w',
default: Duration.minutes(Deploy.DEFAULT_WAIT_MINUTES),
min: Duration.minutes(0), // wait=0 means deploy is asynchronous
description: messages.getMessage('flags.wait'),
longDescription: messages.getMessage('flagsLong.wait'),
}),
testlevel: flags.enum({
char: 'l',
description: messages.getMessage('flags.testLevel'),
longDescription: messages.getMessage('flagsLong.testLevel'),
options: ['NoTestRun', 'RunSpecifiedTests', 'RunLocalTests', 'RunAllTestsInOrg'],
}),
runtests: flags.array({
char: 'r',
description: messages.getMessage('flags.runTests'),
longDescription: messages.getMessage('flagsLong.runTests'),
}),
ignoreerrors: flags.boolean({
char: 'o',
description: messages.getMessage('flags.ignoreErrors'),
longDescription: messages.getMessage('flagsLong.ignoreErrors'),
}),
ignorewarnings: flags.boolean({
char: 'g',
description: messages.getMessage('flags.ignoreWarnings'),
longDescription: messages.getMessage('flagsLong.ignoreWarnings'),
}),
purgeondelete: flags.boolean({
description: messages.getMessage('flags.purgeOnDelete'),
dependsOn: ['manifest'],
}),
validateddeployrequestid: flags.id({
char: 'q',
description: messages.getMessage('flags.validateDeployRequestId'),
longDescription: messages.getMessage('flagsLong.validateDeployRequestId'),
exactlyOne: xorFlags,
exclusive: ['checkonly', 'testlevel', 'runtests', 'tracksource'],
validate: DeployCommand.isValidDeployId,
}),
verbose: flags.builtin({
description: messages.getMessage('flags.verbose'),
}),
metadata: flags.array({
char: 'm',
description: messages.getMessage('flags.metadata'),
longDescription: messages.getMessage('flagsLong.metadata'),
exactlyOne: xorFlags,
}),
sourcepath: flags.array({
char: 'p',
description: messages.getMessage('flags.sourcePath'),
longDescription: messages.getMessage('flagsLong.sourcePath'),
exactlyOne: xorFlags,
}),
manifest: flags.filepath({
char: 'x',
description: messages.getMessage('flags.manifest'),
longDescription: messages.getMessage('flagsLong.manifest'),
exactlyOne: xorFlags,
}),
predestructivechanges: flags.filepath({
description: messages.getMessage('flags.predestructivechanges'),
dependsOn: ['manifest'],
}),
postdestructivechanges: flags.filepath({
description: messages.getMessage('flags.postdestructivechanges'),
dependsOn: ['manifest'],
}),
tracksource: flags.boolean({
char: 't',
description: messages.getMessage('flags.tracksource'),
exclusive: ['checkonly', 'validateddeployrequestid'],
}),
forceoverwrite: flags.boolean({
char: 'f',
description: messages.getMessage('flags.forceoverwrite'),
dependsOn: ['tracksource'],
}),
resultsdir: flags.directory({
description: messages.getMessage('flags.resultsDir'),
}),
coverageformatters: flags.array({
description: messages.getMessage('flags.coverageFormatters'),
options: reportsFormatters,
helpValue: reportsFormatters.join(','),
}),
junit: flags.boolean({ description: messages.getMessage('flags.junit') }),
};
protected readonly lifecycleEventNames = ['predeploy', 'postdeploy'];
protected tracking: SourceTracking;
public async run(): Promise<DeployCommandResult | DeployCommandAsyncResult> {
await this.preChecks();
await this.deploy();
this.resolveSuccess();
await this.maybeUpdateTracking();
return this.formatResult();
}
protected async preChecks(): Promise<void> {
if (this.flags.tracksource) {
this.tracking = await trackingSetup({
commandName: 'force:source:deploy',
// we'll check ACTUAL conflicts once we get a componentSet built
ignoreConflicts: true,
org: this.org,
project: this.project,
ux: this.ux,
});
}
}
// There are 3 types of deploys:
// 1. synchronous - deploy metadata and wait for the deploy to complete.
// 2. asynchronous - deploy metadata and immediately return.
// 3. recent validation - deploy metadata that's already been validated by the org
protected async deploy(): Promise<void> {
const waitDuration = this.getFlag<Duration>('wait');
this.isAsync = waitDuration.quantity === 0;
this.isRest = this.isRestDeploy();
if (this.isAsync && (this.flags.coverageformatters || this.flags.junit)) {
this.warn(messages.getMessage('asyncCoverageJunitWarning'));
}
if (this.flags.validateddeployrequestid) {
this.deployResult = await this.deployRecentValidation();
} else {
this.componentSet = await ComponentSetBuilder.build({
apiversion: this.getFlag<string>('apiversion'),
sourceapiversion: await this.getSourceApiVersion(),
sourcepath: this.getFlag<string[]>('sourcepath'),
manifest: this.flags.manifest && {
manifestPath: this.getFlag<string>('manifest'),
directoryPaths: this.getPackageDirs(),
destructiveChangesPre: this.getFlag<string>('predestructivechanges'),
destructiveChangesPost: this.getFlag<string>('postdestructivechanges'),
},
metadata: this.flags.metadata && {
metadataEntries: this.getFlag<string[]>('metadata'),
directoryPaths: this.getPackageDirs(),
},
});
if (this.getFlag<boolean>('tracksource')) {
// will throw if conflicts exist
if (!this.getFlag<boolean>('forceoverwrite')) {
await filterConflictsByComponentSet({ tracking: this.tracking, components: this.componentSet, ux: this.ux });
}
const localDeletes = await this.tracking.getChanges<string>({
origin: 'local',
state: 'delete',
format: 'string',
});
if (localDeletes.length) {
this.ux.warn(messages.getMessage('deployWontDelete'));
}
}
// fire predeploy event for sync and async deploys
await this.lifecycle.emit('predeploy', this.componentSet.toArray());
this.ux.log(getVersionMessage('Deploying', this.componentSet, this.isRest));
const deploy = await this.componentSet.deploy({
usernameOrConnection: this.org.getUsername(),
apiOptions: {
...{
purgeOnDelete: this.getFlag<boolean>('purgeondelete', false),
ignoreWarnings: this.getFlag<boolean>('ignorewarnings', false),
rollbackOnError: !this.getFlag<boolean>('ignoreerrors', false),
checkOnly: this.getFlag<boolean>('checkonly', false),
rest: this.isRest,
},
// if runTests is defaulted as 'NoTestRun' and deploying to prod, you'll get this error
// https://github.com/forcedotcom/cli/issues/1542
// add additional properties conditionally ()
...(this.getFlag<string>('testlevel') ? { testLevel: this.getFlag<TestLevel>('testlevel') } : {}),
...(this.getFlag<string[]>('runtests') ? { runTests: this.getFlag<string[]>('runtests') } : {}),
},
});
this.asyncDeployResult = { id: deploy.id };
this.updateDeployId(deploy.id);
if (!this.isAsync) {
// we're not print JSON output
if (!this.isJsonOutput()) {
const progressFormatter: ProgressFormatter = env.getBoolean('SFDX_USE_PROGRESS_BAR', true)
? new DeployProgressBarFormatter(this.logger, this.ux)
: new DeployProgressStatusFormatter(this.logger, this.ux);
progressFormatter.progress(deploy);
}
this.deployResult = await deploy.pollStatus({ timeout: waitDuration });
}
}
if (this.deployResult) {
// Only fire the postdeploy event when we have results. I.e., not async.
await this.lifecycle.emit('postdeploy', this.deployResult);
}
}
protected formatResult(): DeployCommandResult | DeployCommandAsyncResult {
this.resultsDir = this.resolveOutputDir(
this.getFlag<string[]>('coverageformatters', undefined),
this.getFlag<boolean>('junit'),
this.getFlag<string>('resultsdir'),
this.deployResult?.response?.id,
false
);
const formatterOptions: ResultFormatterOptions = {
verbose: this.getFlag<boolean>('verbose', false),
username: this.org.getUsername(),
coverageOptions: this.getCoverageFormattersOptions(this.getFlag<string[]>('coverageformatters', undefined)),
junitTestResults: this.flags.junit as boolean,
resultsDir: this.resultsDir,
testsRan: this.getFlag<string>('testlevel', 'NoTestRun') !== 'NoTestRun',
};
const formatter = this.isAsync
? new DeployAsyncResultFormatter(this.logger, this.ux, formatterOptions, this.asyncDeployResult)
: new DeployResultFormatter(this.logger, this.ux, formatterOptions, this.deployResult);
if (!this.isAsync) {
this.maybeCreateRequestedReports();
}
// Only display results to console when JSON flag is unset.
if (!this.isJsonOutput()) {
formatter.display();
}
return formatter.getJson();
}
private async maybeUpdateTracking(): Promise<void> {
if (this.getFlag<boolean>('tracksource', false)) {
return updateTracking({ ux: this.ux, result: this.deployResult, tracking: this.tracking });
}
}
}