-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-upload.ts
executable file
·411 lines (377 loc) · 13.3 KB
/
file-upload.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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import AdmZip from 'adm-zip';
import map from 'lodash/map';
import omit from 'lodash/omit';
import find from 'lodash/find';
import FormData from 'form-data';
import filter from 'lodash/filter';
import includes from 'lodash/includes';
import isEmpty from 'lodash/isEmpty';
import { basename, resolve } from 'path';
import { cliux, configHandler, HttpClient, ux } from '@contentstack/cli-utilities';
import { createReadStream, existsSync, PathLike, statSync, readFileSync } from 'fs';
import { print } from '../util';
import BaseClass from './base-class';
import { getFileList } from '../util/fs';
import { createSignedUploadUrlMutation, importProjectMutation } from '../graphql';
import { SignedUploadUrlData, FileUploadMethod, DeploymentStatus } from '../types/launch';
import config from '../config';
export default class FileUpload extends BaseClass {
/**
* @method run
*
* @return {*} {Promise<void>}
* @memberof FileUpload
*/
async run(): Promise<void> {
if (this.config.isExistingProject) {
const environment = await this.getEnvironment();
await this.handleExistingProject(environment.uid);
} else {
await this.handleNewProject();
}
this.prepareLaunchConfig();
await this.showLogs();
if(this.config.currentDeploymentStatus === DeploymentStatus.FAILED) {
this.exit(1);
}
this.showDeploymentUrl();
this.showSuggestion();
}
private async handleExistingProject(environment: string): Promise<void> {
await this.initApolloClient();
let redeployLatest = this.config['redeploy-latest'];
let redeployLastUpload = this.config['redeploy-last-upload'];
if (!redeployLatest && !redeployLastUpload) {
await this.confirmRedeployment();
const latestRedeploymentConfirmed = await this.confirmLatestRedeployment();
redeployLatest = latestRedeploymentConfirmed;
redeployLastUpload = !latestRedeploymentConfirmed;
}
if (redeployLastUpload && redeployLatest) {
this.log('redeploy-last-upload and redeploy-latest flags are not supported together.', 'error');
this.exit(1);
}
let uploadUid;
if (redeployLatest) {
const signedUploadUrlData = await this.createSignedUploadUrl();
uploadUid = signedUploadUrlData.uploadUid;
const { zipName, zipPath } = await this.archive();
await this.uploadFile(zipName, zipPath, signedUploadUrlData);
}
await this.createNewDeployment(true, environment, uploadUid);
}
private async confirmRedeployment(): Promise<void> {
const redeploy = await cliux.inquire({
type: 'confirm',
name: 'deployLatestCommit',
message: 'Do you want to redeploy this existing Launch project?',
});
if (!redeploy) {
this.log('Project redeployment aborted.', 'info');
this.exit(1);
}
}
private async confirmLatestRedeployment(): Promise<boolean | void> {
const choices = [
...map(config.supportedFileUploadMethods, (fileUploadMethod) => ({
value: fileUploadMethod,
name: `Redeploy with ${fileUploadMethod}`,
}))
];
const selectedFileUploadMethod: FileUploadMethod = await cliux.inquire({
choices: choices,
type: 'search-list',
name: 'fileUploadMethod',
message: 'Choose a redeploy method to proceed',
});
if (selectedFileUploadMethod === FileUploadMethod.LastFileUpload) {
return false;
}
return true;
}
private async handleNewProject(): Promise<void> {
const uploadUid = await this.prepareAndUploadNewProjectFile();
await this.createNewProject(uploadUid);
}
/**
* @method createNewProject - Create new launch project
*
* @return {*} {Promise<void>}
* @memberof FileUpload
*/
async createNewProject(uploadUid: string): Promise<void> {
const { framework, projectName, buildCommand, outputDirectory, environmentName, serverCommand } = this.config;
await this.apolloClient
.mutate({
mutation: importProjectMutation,
variables: {
project: {
projectType: 'FILEUPLOAD',
name: projectName,
fileUpload: { uploadUid },
environment: {
frameworkPreset: framework,
outputDirectory: outputDirectory,
name: environmentName || 'Default',
environmentVariables: map(this.envVariables, ({ key, value }) => ({ key, value })),
buildCommand: buildCommand === undefined || buildCommand === null ? 'npm run build' : buildCommand,
serverCommand: serverCommand === undefined || serverCommand === null ? 'npm run start' : serverCommand,
},
},
skipGitData: true,
},
})
.then(({ data: { project } }) => {
this.log('New project created successfully', 'info');
const [firstEnvironment] = project.environments;
this.config.currentConfig = project;
this.config.currentConfig.deployments = map(firstEnvironment.deployments.edges, 'node');
this.config.currentConfig.environments[0] = omit(this.config.currentConfig.environments[0], ['deployments']);
})
.catch(async (error) => {
const canRetry = await this.handleNewProjectCreationError(error);
if (canRetry) {
return this.createNewProject(uploadUid);
}
});
}
/**
* @method prepareForNewProjectCreation - prepare necessary data for new project creation
*
* @return {*} {Promise<void>}
* @memberof FileUpload
*/
async prepareAndUploadNewProjectFile(): Promise<string> {
const {
name,
framework,
environment,
'build-command': buildCommand,
'out-dir': outputDirectory,
'variable-type': variableType,
'env-variables': envVariables,
'server-command': serverCommand,
alias,
} = this.config.flags;
const { token, apiKey } = configHandler.get(`tokens.${alias}`) ?? {};
this.config.selectedStack = apiKey;
this.config.deliveryToken = token;
// this.fileValidation();
await this.selectOrg();
const signedUploadUrlData = await this.createSignedUploadUrl();
const { zipName, zipPath, projectName } = await this.archive();
await this.uploadFile(zipName, zipPath, signedUploadUrlData);
this.config.projectName =
name ||
(await cliux.inquire({
type: 'input',
name: 'projectName',
message: 'Project Name',
default: projectName,
validate: this.inquireRequireValidation,
}));
this.config.environmentName =
environment ||
(await cliux.inquire({
type: 'input',
default: 'Default',
name: 'environmentName',
message: 'Environment Name',
validate: this.inquireRequireValidation,
}));
if (framework) {
this.config.framework = ((
find(this.config.listOfFrameWorks, {
name: framework,
}) as Record<string, any>
).value || '') as string;
print([
{ message: '?', color: 'green' },
{ message: 'Framework Preset', bold: true },
{ message: this.config.framework, color: 'cyan' },
]);
} else {
await this.detectFramework();
}
this.config.buildCommand =
buildCommand ||
(await cliux.inquire({
type: 'input',
name: 'buildCommand',
message: 'Build Command',
default: this.config.framework === 'OTHER' ? null : 'npm run build',
}));
this.config.outputDirectory =
outputDirectory ||
(await cliux.inquire({
type: 'input',
name: 'outputDirectory',
message: 'Output Directory',
default: (this.config.outputDirectories as Record<string, string>)[this.config?.framework || 'OTHER'],
}));
if (this.config.framework && this.config.supportedFrameworksForServerCommands.includes(this.config.framework)) {
this.config.serverCommand =
serverCommand ||
(await cliux.inquire({
type: 'input',
name: 'serverCommand',
message: 'Server Command',
}));
}
this.config.variableType = variableType as unknown as string;
this.config.envVariables = envVariables;
await this.handleEnvImportFlow();
return signedUploadUrlData.uploadUid;
}
/**
* @method fileValidation - validate the working directory
*
* @memberof FileUpload
*/
fileValidation() {
const basePath = this.config.projectBasePath;
const packageJsonPath = resolve(basePath, 'package.json');
if (!existsSync(packageJsonPath)) {
this.log('Package.json file not found.', 'info');
this.exit(1);
}
}
/**
* @method archive - Archive the files and directory to be uploaded for launch project
*
* @return {*}
* @memberof FileUpload
*/
async archive() {
ux.action.start('Preparing zip file');
const projectName = basename(this.config.projectBasePath);
const zipName = `${Date.now()}_${projectName}.zip`;
const zipPath = resolve(this.config.projectBasePath, zipName);
const zip = new AdmZip();
const zipEntries = filter(
await getFileList(this.config.projectBasePath, true, true),
(entry) => !includes(this.config.fileUploadConfig.exclude, entry) && !includes(entry, '.zip'),
);
for (const entry of zipEntries) {
const entryPath = `${this.config.projectBasePath}/${entry}`;
const state = statSync(entryPath);
switch (true) {
case state.isDirectory(): // NOTE folder
zip.addLocalFolder(entryPath, entry);
break;
case state.isFile(): // NOTE check is file
zip.addLocalFile(entryPath);
break;
}
}
const status = await zip.writeZipPromise(zipPath).catch(() => {
this.log('Zipping project process failed! Please try again.');
this.exit(1);
});
if (!status) {
this.log('Zipping project process failed! Please try again.');
this.exit(1);
}
ux.action.stop();
return { zipName, zipPath, projectName };
}
/**
* @method createSignedUploadUrl - create pre signed url for file upload
*
* @return {*} {Promise<SignedUploadUrlData>}
* @memberof FileUpload
*/
async createSignedUploadUrl(): Promise<SignedUploadUrlData> {
try {
const result = await this.apolloClient.mutate({ mutation: createSignedUploadUrlMutation });
const signedUploadUrlData = result.data.signedUploadUrl;
this.config.uploadUid = signedUploadUrlData.uploadUid;
return signedUploadUrlData;
} catch (error) {
this.log('Something went wrong. Please try again.', 'warn');
if (error instanceof Error) {
this.log(error.message, 'error');
}
this.exit(1);
return {} as SignedUploadUrlData;
}
}
/**
* @method uploadFile - Upload file in to s3 bucket
*
* @param {string} fileName
* @param {PathLike} filePath
* @return {*} {Promise<void>}
* @memberof FileUpload
*/
async uploadFile(fileName: string, filePath: PathLike, signedUploadUrlData: SignedUploadUrlData): Promise<void> {
const { uploadUrl, fields, headers, method } = signedUploadUrlData;
const formData = new FormData();
if (!isEmpty(fields)) {
for (const { formFieldKey, formFieldValue } of fields) {
formData.append(formFieldKey, formFieldValue);
}
formData.append('file', createReadStream(filePath), fileName);
await this.submitFormData(formData, uploadUrl);
} else if (method === 'PUT') {
await this.uploadWithHttpClient(filePath, uploadUrl, headers);
}
}
private async submitFormData(formData: FormData, uploadUrl: string): Promise<void> {
ux.action.start('Starting file upload...');
try {
await new Promise<void>((resolve, reject) => {
formData.submit(uploadUrl, (error, res) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
ux.action.stop();
} catch (error) {
ux.action.stop('File upload failed!');
this.log('File upload failed. Please try again.', 'error');
if (error instanceof Error) {
this.log(error.message, 'error');
}
this.exit(1);
}
}
private async uploadWithHttpClient(
filePath: PathLike,
uploadUrl: string,
headers: Array<{ key: string; value: string }>,
): Promise<void> {
ux.action.start('Starting file upload...');
const httpClient = new HttpClient();
const file = readFileSync(filePath);
// Convert headers array to a headers object
const headerObject = headers?.reduce((acc, { key, value }) => {
acc[key] = value;
return acc;
}, {} as Record<string, string>);
try {
httpClient.headers({ 'Content-Type': 'application/zip' });
if (headerObject !== undefined) httpClient.headers(headerObject);
const response = (await httpClient.put(uploadUrl, file)) as any;
const { status } = response;
if (status >= 200 && status < 300) {
ux.action.stop();
} else {
ux.action.stop('File upload failed!');
this.log('File upload failed. Please try again.', 'error');
this.log(`Error: ${status}, ${response?.statusText}`, 'error');
this.exit(1);
}
} catch (error) {
ux.action.stop('File upload failed!');
this.log('File upload failed. Please try again.', 'error');
if (error instanceof Error) {
this.log(`Error: ${error.message}`, 'error');
}
this.exit(1);
}
}
}