-
Notifications
You must be signed in to change notification settings - Fork 682
Expand file tree
/
Copy pathbuild.ts
More file actions
299 lines (259 loc) · 10.1 KB
/
build.ts
File metadata and controls
299 lines (259 loc) · 10.1 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
import { CommandLineInputs, CommandLineOptions, MetadataGroup } from '@ionic/cli-framework';
import { LOGGER_LEVELS } from '@ionic/cli-framework-output';
import { sleep } from '@ionic/utils-process';
import { tmpfilepath } from '@ionic/utils-fs';
import { columnar } from '@ionic/utils-terminal';
import * as chalk from 'chalk';
import * as Debug from 'debug';
import * as fs from 'fs';
import { CommandMetadata } from '../../definitions';
import { isSuperAgentError } from '../../guards';
import { input, strong, weak } from '../../lib/color';
import { Command } from '../../lib/command';
import { FatalException } from '../../lib/errors';
import { fileUtils } from '../../lib/utils/file';
import { createRequest, download } from '../../lib/utils/http';
const debug = Debug('ionic:commands:deploy:build');
interface DeployBuild {
artifact_name: string;
job_id: number;
id: string;
caller_id: number;
created: string;
finished: string;
state: string;
commit: any;
automation_id: number;
environment_id: number;
native_config_id: number;
automation_name: string;
environment_name: string;
job: any;
pending_channels: string[];
}
interface DownloadUrl {
url: string | null;
}
export class BuildCommand extends Command {
async getMetadata(): Promise<CommandMetadata> {
const dashUrl = this.env.config.getDashUrl();
return {
name: 'build',
type: 'project',
groups: [MetadataGroup.PAID],
summary: 'Create a deploy build on Appflow',
description: `
This command creates a deploy build on Appflow. While the build is running, it prints the remote build log to the terminal. If the build is successful, it downloads the created web build zip file in the current directory. Downloading build artifacts can be skipped by supplying the flag ${input('skip-download')}.
Apart from ${input('--commit')}, every option can be specified using the full name setup within the Appflow Dashboard[^dashboard].
Customizing the build:
- The ${input('--environment')} and ${input('--channel')} options can be used to customize the groups of values exposed to the build.
`,
footnotes: [
{
id: 'dashboard',
url: dashUrl,
},
],
exampleCommands: [
'',
'--environment="My Custom Environment Name"',
'--commit=2345cd3305a1cf94de34e93b73a932f25baac77c',
'--channel="Master"',
'--channel="Master" --skip-download',
'--channel="Master" --channel="My Custom Channel"',
],
options: [
{
name: 'environment',
summary: 'The group of environment variables exposed to your build',
type: String,
spec: { value: 'name' },
},
{
name: 'channel',
summary: 'The channel you want to auto deploy the build to. This can be repeated multiple times if multiple channels need to be specified.',
type: String,
spec: { value: 'name' },
},
{
name: 'commit',
summary: 'Commit (defaults to HEAD)',
type: String,
groups: [MetadataGroup.ADVANCED],
spec: { value: 'sha1' },
},
{
name: 'skip-download',
summary: `Skip downloading build artifacts after command succeeds.`,
type: Boolean,
spec: { value: 'name' },
default: false,
},
{
name: 'build-file-name',
summary: 'An optional name for the downloaded web artifacts.',
type: String,
spec: { value: 'name' },
},
],
};
}
async run(inputs: CommandLineInputs, options: CommandLineOptions): Promise<void> {
if (!this.project) {
throw new FatalException(`Cannot run ${input('ionic deploy build')} outside a project directory.`);
}
const token = await this.env.session.getUserToken();
const appflowId = await this.project.requireAppflowId();
if (!options.commit) {
options.commit = (await this.env.shell.output('git', ['rev-parse', 'HEAD'], { cwd: this.project.directory })).trim();
debug(`Commit hash: ${strong(options.commit)}`);
}
let build = await this.createDeployBuild(appflowId, token, options);
const buildId = build.job_id;
const details = columnar([
['App ID', strong(appflowId)],
['Build ID', strong(buildId.toString())],
['Commit', strong(`${build.commit.sha.substring(0, 6)} ${build.commit.note}`)],
['Environment', build.environment_name ? strong(build.environment_name) : weak('not set')],
['Channels', build.pending_channels.length ? build.pending_channels.map(v => strong(`"${v}"`)).join(', ') : weak('not set')],
], { vsep: ':' });
this.env.log.ok(
`Build created\n` +
details + '\n\n'
);
build = await this.tailBuildLog(appflowId, buildId, token);
if (build.state !== 'success') {
throw new Error(`Build ${build.state}`);
}
if (options['skip-download']) {
return;
}
const url = await this.getDownloadUrl(appflowId, buildId, token);
if (!url.url) {
throw new Error('Missing URL in response');
}
let buildFilename = build.artifact_name;
if (options['build-file-name']) {
buildFilename = await this.sanitizeString(options['build-file-name']);
}
const filename = await this.downloadBuild(url.url, buildFilename);
this.env.log.ok(`Artifact downloaded: ${filename}`);
}
async createDeployBuild(appflowId: string, token: string, options: CommandLineOptions): Promise<DeployBuild> {
const { req } = await this.env.client.make('POST', `/apps/${appflowId}/deploys/verbose_post`);
let channels: string[] = [];
if (options.channel) {
if (typeof(options.channel) === 'string') {
channels.push(String(options.channel));
} else if (typeof(options.channel) === 'object') {
channels = channels.concat(options.channel);
}
}
req.set('Authorization', `Bearer ${token}`).send({
commit_sha: options.commit,
environment_name: options.environment,
channel_names: channels ? channels : undefined,
});
try {
const res = await this.env.client.do(req);
return res.data as DeployBuild;
} catch (e) {
if (isSuperAgentError(e)) {
if (e.response.status === 401) {
this.env.log.error('Try logging out and back in again.');
}
const apiErrorMessage = (e.response.body.error && e.response.body.error.message) ? e.response.body.error.message : 'Api Error';
throw new FatalException(`Unable to create build: ` + apiErrorMessage);
} else {
throw e;
}
}
}
async tailBuildLog(appflowId: string, buildId: number, token: string): Promise<DeployBuild> {
let build;
let start = 0;
const ws = this.env.log.createWriteStream(LOGGER_LEVELS.INFO, false);
let isCreatedMessage = false;
let errorsEncountered = 0;
while (!(build && ['success', 'failed', 'canceled'].includes(build.state))) {
try {
await sleep(5000);
build = await this.getDeployBuild(appflowId, buildId, token);
if (build && build.state === 'created' && !isCreatedMessage) {
ws.write(chalk.yellow('Concurrency limit reached: build will start as soon as other builds finish.'));
isCreatedMessage = true;
}
const trace = build.job.trace;
if (trace.length > start) {
ws.write(trace.substring(start));
start = trace.length;
}
errorsEncountered = 0;
} catch (e) {
// Retry up to 3 times in the case of an error.
errorsEncountered++;
ws.write(chalk.yellow(`Encountered error: ${e} while fetching build data retrying.`));
if (errorsEncountered >= 3) {
ws.write(chalk.red(`Encountered ${errorsEncountered} errors in a row. Job will now fail.`));
throw e;
}
}
}
ws.end();
return build;
}
async getDeployBuild(appflowId: string, buildId: number, token: string): Promise<DeployBuild> {
const { req } = await this.env.client.make('GET', `/apps/${appflowId}/deploys/${buildId}`);
req.set('Authorization', `Bearer ${token}`).send();
try {
const res = await this.env.client.do(req);
return res.data as DeployBuild;
} catch (e) {
if (isSuperAgentError(e)) {
if (e.response.status === 401) {
this.env.log.error('Try logging out and back in again.');
}
const apiErrorMessage = (e.response.body.error && e.response.body.error.message) ? e.response.body.error.message : 'Api Error';
throw new FatalException(`Unable to get build ${buildId}: ` + apiErrorMessage);
} else {
throw e;
}
}
}
async getDownloadUrl(appflowId: string, buildId: number, token: string): Promise<DownloadUrl> {
const { req } = await this.env.client.make('GET', `/apps/${appflowId}/packages/${buildId}/download?artifact_type=WWW_ZIP`);
req.set('Authorization', `Bearer ${token}`).send();
try {
const res = await this.env.client.do(req);
return res.data as DownloadUrl;
} catch (e) {
if (isSuperAgentError(e)) {
if (e.response.status === 401) {
this.env.log.error('Try logging out and back in again.');
}
const apiErrorMessage = (e.response.body.error && e.response.body.error.message) ? e.response.body.error.message : 'Api Error';
throw new FatalException(`Unable to get download URL for build ${buildId}: ` + apiErrorMessage);
} else {
throw e;
}
}
}
async downloadBuild(url: string, filename: string): Promise<string> {
const { req } = await createRequest('GET', url, this.env.config.getHTTPConfig());
const tmpFile = tmpfilepath('ionic-package-build');
const ws = fs.createWriteStream(tmpFile);
await download(req, ws, {});
fs.copyFileSync(tmpFile, filename);
fs.unlinkSync(tmpFile);
return filename;
}
async sanitizeString(value: string | string[] | boolean | null | undefined): Promise<string> {
if (!value || typeof (value) !== 'string') {
return '';
}
if (!fileUtils.isValidFileName(value)) {
throw new FatalException(`${strong(String(value))} is not a valid file name`);
}
return String(value);
}
}