-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.ts
executable file
·334 lines (307 loc) · 10.3 KB
/
github.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
import map from 'lodash/map';
import { resolve } from 'path';
import omit from 'lodash/omit';
import find from 'lodash/find';
import split from 'lodash/split';
import { exec } from 'child_process';
import replace from 'lodash/replace';
import includes from 'lodash/includes';
import { configHandler, cliux as ux } from '@contentstack/cli-utilities';
import { print } from '../util';
import BaseClass from './base-class';
import { getRemoteUrls } from '../util/create-git-meta';
import { repositoriesQuery, userConnectionsQuery, importProjectMutation } from '../graphql';
import { DeploymentStatus } from '../types';
export default class GitHub extends BaseClass {
/**
* @method run - initialization function
*
* @return {*} {Promise<void>}
* @memberof GitHub
*/
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(environmentUid:string): Promise<void> {
await this.initApolloClient();
const redeployLastUpload = this.config['redeploy-last-upload'];
const redeployLatest = this.config['redeploy-latest'];
if (redeployLastUpload) {
this.log('redeploy-last-upload flag is not supported for Github Project.', 'error');
this.exit(1);
}
if(!redeployLatest && !redeployLastUpload){
await this.confirmLatestRedeployment();
}
await this.createNewDeployment(false, environmentUid);
}
private async confirmLatestRedeployment(): Promise<void> {
const deployLatestCommit = await ux.inquire({
type: 'confirm',
name: 'deployLatestCommit',
message: 'Redeploy latest commit?',
});
if (!deployLatestCommit) {
this.log('Cannot create a new project because its an existing project.', 'info');
this.exit(1);
}
}
private async handleNewProject(): Promise<void> {
// NOTE Step 1: Check is Github connected
if (await this.checkGitHubConnected()) {
// NOTE Step 2: check is the git remote available in the user's repo list
if (await this.checkGitRemoteAvailableAndValid()) {
if (await this.checkUserGitHubAccess()) {
// NOTE Step 3: check is the user has proper git access
await this.prepareForNewProjectCreation();
}
}
}
await this.createNewProject();
}
/**
* @method createNewProject - Create new launch project
*
* @return {*} {Promise<void>}
* @memberof GitHub
*/
async createNewProject(): Promise<void> {
const {
branch,
framework,
repository,
projectName,
buildCommand,
selectedStack,
outputDirectory,
environmentName,
provider: gitProvider,
serverCommand,
} = this.config;
const username = split(repository?.fullName, '/')[0];
await this.apolloClient
.mutate({
mutation: importProjectMutation,
variables: {
project: {
name: projectName,
cmsStackApiKey: selectedStack?.api_key || '',
repository: {
username,
repositoryUrl: repository?.url,
repositoryName: repository?.fullName,
gitProviderMetadata: { gitProvider },
},
environment: {
gitBranch: branch,
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,
},
},
},
})
.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();
}
});
}
/**
* @method prepareForNewProjectCreation - Preparing all the data for new project creation
*
* @return {*} {Promise<void>}
* @memberof BaseClass
*/
async prepareForNewProjectCreation(): Promise<void> {
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;
await this.selectOrg();
print([
{ message: '?', color: 'green' },
{ message: 'Repository', bold: true },
{ message: this.config.repository?.fullName, color: 'cyan' },
]);
await this.selectBranch();
this.config.projectName =
name ||
(await ux.inquire({
type: 'input',
name: 'projectName',
message: 'Project Name',
default: this.config.repository?.name,
validate: this.inquireRequireValidation,
}));
this.config.environmentName =
environment ||
(await ux.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 ux.inquire({
type: 'input',
name: 'buildCommand',
message: 'Build Command',
default: this.config.framework === 'OTHER' ? '' : 'npm run build',
}));
this.config.outputDirectory =
outputDirectory ||
(await ux.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 ux.inquire({
type: 'input',
name: 'serverCommand',
message: 'Server Command',
}));
}
this.config.variableType = variableType as unknown as string;
this.config.envVariables = envVariables;
await this.handleEnvImportFlow();
}
/**
* @method checkGitHubConnected - GitHub connection validation
*
* @return {*} {(Promise<{
* userUid: string;
* provider: string;
* } | void>)}
* @memberof GitHub
*/
async checkGitHubConnected(): Promise<{
userUid: string;
provider: string;
} | void> {
const userConnections = await this.apolloClient
.query({ query: userConnectionsQuery })
.then(({ data: { userConnections } }) => userConnections)
.catch((error) => this.log(error, 'error'));
const userConnection = find(userConnections, {
provider: this.config.provider,
});
if (userConnection) {
this.log('GitHub connection identified!', 'info');
this.config.userConnection = userConnection;
} else {
this.log('GitHub connection not found!', 'warn');
await this.connectToAdapterOnUi();
}
return this.config.userConnection;
}
/**
* @method checkGitRemoteAvailableAndValid - GitHub repository verification
*
* @return {*} {(Promise<boolean | void>)}
* @memberof GitHub
*/
async checkGitRemoteAvailableAndValid(): Promise<boolean | void> {
const localRemoteUrl = (await getRemoteUrls(resolve(this.config.projectBasePath, '.git/config')))?.origin || '';
if (!localRemoteUrl) {
this.log('GitHub project not identified!', 'error');
await this.connectToAdapterOnUi();
}
const repositories = await this.apolloClient
.query({ query: repositoriesQuery })
.then(({ data: { repositories } }) => repositories)
.catch((error) => this.log(error, 'error'));
this.config.repository = find(repositories, {
url: replace(localRemoteUrl, '.git', ''),
});
if (!this.config.repository) {
this.log('Repository not found in the list!', 'error');
this.exit(1);
}
return true;
}
/**
* @method checkUserGitHubAccess - GitHub user access validation
*
* @return {*} {Promise<boolean>}
* @memberof GitHub
*/
async checkUserGitHubAccess(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const self = this;
const defaultBranch = this.config.repository?.defaultBranch;
if (!defaultBranch) return reject('Branch not found');
exec(
`git push -u origin ${defaultBranch} --dry-run`,
{ cwd: this.config.projectBasePath },
function (err, stdout, stderr) {
if (err) {
self.log(err, 'error');
}
if (
includes(stderr, 'Everything up-to-date') &&
includes(stdout, `Would set upstream of '${defaultBranch}' to '${defaultBranch}' of 'origin'`)
) {
self.log('User access verified', 'info');
return resolve(true);
}
self.log('You do not have write access for the selected repo', 'error');
self.exit(0);
},
);
});
}
}