-
Notifications
You must be signed in to change notification settings - Fork 3
/
common.ts
394 lines (352 loc) · 9.46 KB
/
common.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
/**
* Copyright 2024 Google LLC
*
* 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
*
* https://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.
*/
const fs = require('fs-extra'); // tslint:disable-line
const os = require('os'); // tslint:disable-line
const path = require('path'); // tslint:disable-line
const replace = require('replace'); // tslint:disable-line
const spawn = require('cross-spawn'); // tslint:disable-line
/**
* Default Google Cloud Platform region.
*/
export const DEFAULT_GCP_REGION = 'us-central1';
/**
* Default Google Cloud Storage location.
*/
export const DEFAULT_GCS_LOCATION = 'us';
/**
* Default Pub/Sub topic.
*/
export const DEFAULT_PUBSUB_TOPIC = 'ariel-topic';
/**
* Google Cloud Storage bucket name suffix.
*/
export const GCS_BUCKET_NAME_SUFFIX = '-ariel';
/**
* Default value for configuring APIs and roles.
*/
export const DEFAULT_CONFIGURE_APIS_AND_ROLES = true;
/**
* Default value for using Cloud Build.
*/
export const DEFAULT_USE_CLOUD_BUILD = true;
interface ConfigReplace {
regex: string;
replacement: string;
path: string;
}
/**
* Interface for Prompts response.
*/
export interface PromptsResponse {
gcpProjectId: string;
gcpRegion?: string;
gcsLocation?: string;
pubsubTopic?: string;
gcsBucket?: string;
configureApisAndRoles?: boolean;
useCloudBuild?: boolean;
deployBackend?: boolean;
deployUi?: boolean;
}
/**
* Async function to check if the user is logged in via clasp.
*/
async function isClaspLoggedIn() {
return await fs.exists(path.join(os.homedir(), '.clasprc.json'));
}
/**
* Async function to login via clasp if the user is not logged in.
*/
async function loginClasp() {
const loggedIn = await isClaspLoggedIn();
if (!loggedIn) {
console.log('Logging in via clasp...');
spawn.sync('clasp', ['login'], { stdio: 'inherit' });
}
}
/**
* Async function to check if the clasp configuration exists.
*/
async function isClaspConfigured(rootDir: string) {
return (
(await fs.exists(path.join(rootDir, '.clasp-dev.json'))) ||
(await fs.exists(path.join(rootDir, 'dist', '.clasp.json')))
);
}
/**
* Function to extract the Google Sheets link from the clasp output.
*/
function extractSheetsLink(output: string) {
const sheetsLink = output.match(/Google Sheet: ([^\n]*)/);
return sheetsLink?.length ? sheetsLink[1] : 'Not found';
}
/**
* Function to extract the Google Sheets Add-on script link from the clasp output.
*/
function extractScriptLink(output: string) {
const scriptLink = output.match(/Google Sheets Add-on script: ([^\n]*)/);
return scriptLink?.length ? scriptLink[1] : 'Not found';
}
/**
* Async function to create a new Clasp project.
*/
async function createClaspProject(
title: string,
scriptRootDir: string,
filesRootDir: string
) {
fs.ensureDirSync(path.join(filesRootDir, scriptRootDir));
const res = spawn.sync(
'clasp',
[
'create',
'--type',
'sheets',
'--rootDir',
scriptRootDir,
'--title',
title,
],
{ encoding: 'utf-8' }
);
await fs.move(
path.join(scriptRootDir, '.clasp.json'),
path.join(filesRootDir, '.clasp-dev.json')
);
await fs.copyFile(
path.join(filesRootDir, '.clasp-dev.json'),
path.join(filesRootDir, '.clasp-prod.json')
);
await fs.remove(path.join(scriptRootDir, 'appsscript.json'));
const output = res.output.join();
return {
sheetLink: extractSheetsLink(output),
scriptLink: extractScriptLink(output),
};
}
/**
* Async function to check if the user is authenticated via gcloud.
*/
export async function checkGcloudAuth() {
const gcloudAuthExists = await fs.exists(
path.join(os.homedir(), '.config', 'gcloud', 'credentials.db')
);
const gcloudAppDefaultCredsExists = await fs.exists(
path.join(
os.homedir(),
'.config',
'gcloud',
'application_default_credentials.json'
)
);
if (!gcloudAuthExists) {
console.log('Logging in via gcloud...');
spawn.sync('gcloud auth login', { stdio: 'inherit', shell: true });
console.log();
}
if (!gcloudAppDefaultCredsExists) {
console.log('Setting Application Default Credentials (ADC) via gcloud...');
spawn.sync('gcloud auth application-default login', {
stdio: 'inherit',
shell: true,
});
console.log();
}
}
/**
* Function to deploy Google Cloud Platform components.
*/
export function deployGcpComponents() {
console.log('Deploying Ariel Backend onto Google Cloud Platform...');
const res = spawn.sync('npm run deploy-backend', {
stdio: 'inherit',
shell: true,
});
if (res.status !== 0) {
throw new Error('Failed to deploy GCP components.');
}
}
/**
* Async function to create an Apps Script project for the UI.
*/
export async function createScriptProject() {
console.log();
await loginClasp();
const claspConfigExists = await isClaspConfigured('./ui');
if (claspConfigExists) {
return;
}
console.log();
console.log('Creating Apps Script Project...');
const res = await createClaspProject('Ariel', './dist', './ui');
console.log();
console.log('IMPORTANT -> Google Sheets Link:', res.sheetLink);
console.log('IMPORTANT -> Apps Script Link:', res.scriptLink);
console.log();
}
/**
* Function to deploy the UI Web App.
*/
export function deployUi() {
console.log('Deploying the UI Web App...');
spawn.sync('npm run deploy-ui', { stdio: 'inherit', shell: true });
console.log();
}
/**
* Function to get the current user configuration.
*/
export function getCurrentConfig(): Config {
if (fs.existsSync('.config.json')) {
return JSON.parse(fs.readFileSync('.config.json'));
} else {
console.log('No config found, using default values');
return {
gcpRegion: DEFAULT_GCP_REGION,
gcsLocation: DEFAULT_GCS_LOCATION,
pubsubTopic: DEFAULT_PUBSUB_TOPIC,
configureApisAndRoles: DEFAULT_CONFIGURE_APIS_AND_ROLES,
useCloudBuild: DEFAULT_USE_CLOUD_BUILD,
deployBackend: true,
deployUi: true,
};
}
}
/**
* Interface for the deployment configuration.
*/
export interface Config {
gcpProjectId?: string;
gcpRegion: string;
gcsBucket?: string;
gcsLocation: string;
pubsubTopic: string;
configureApisAndRoles: boolean;
useCloudBuild: boolean;
deployBackend: boolean;
deployUi: boolean;
}
/**
* Function to save the user configuration.
*/
export function saveUserConfig(config: Config) {
fs.writeFileSync('.config.json', JSON.stringify(config));
}
/**
* Function to sanitize the user configuration.
* @param response The user response from the prompts.
* @return The sanitized user configuration.
*/
export function sanitizeUserConfig(response: PromptsResponse): Config {
const gcpRegion = response.gcpRegion || DEFAULT_GCP_REGION;
const gcsLocation = response.gcsLocation || DEFAULT_GCS_LOCATION;
const sanitizedProjectId = `${response.gcpProjectId
.replace('google.com:', '')
.replace('.', '-')
.replace(':', '-')}`;
const gcsBucket =
response.gcsBucket || `${sanitizedProjectId}${GCS_BUCKET_NAME_SUFFIX}`;
const pubsubTopic = response.pubsubTopic || DEFAULT_PUBSUB_TOPIC;
const configureApisAndRoles = response.configureApisAndRoles ?? true;
const useCloudBuild = response.useCloudBuild ?? true;
const deployUi = response.deployUi ?? true;
const deployBackend = response.deployBackend ?? true;
const config: Config = {
gcpProjectId: sanitizedProjectId,
gcpRegion,
gcsLocation,
pubsubTopic,
gcsBucket,
configureApisAndRoles,
useCloudBuild,
deployUi,
deployBackend,
};
return config;
}
/**
* Set of files that will need value replacements
*/
const TEMPLATE_FILES = [
'./backend/deploy-config.sh.TEMPLATE',
'./ui/src/config.ts.TEMPLATE',
];
function copyFreshTemplateFiles() {
TEMPLATE_FILES.forEach((file) => {
fs.copySync(file, file.replace('.TEMPLATE', ''));
});
}
function configReplace(config: ConfigReplace) {
replace({
regex: config.regex,
replacement: config.replacement,
paths: [config.path],
recursive: false,
silent: true,
});
}
/**
* Injects config values into templated config files.
*/
export function setUserConfig(config: Config) {
console.log();
console.log('Setting user configuration...');
copyFreshTemplateFiles();
if (config.deployBackend) {
configReplace({
regex: '<gcp-project-id>',
replacement: config.gcpProjectId!,
path: './backend/deploy-config.sh',
});
configReplace({
regex: '<gcp-region>',
replacement: config.gcpRegion,
path: './backend/deploy-config.sh',
});
configReplace({
regex: '<gcs-location>',
replacement: config.gcsLocation,
path: './backend/deploy-config.sh',
});
configReplace({
regex: '<gcs-bucket>',
replacement: config.gcsBucket!,
path: './backend/deploy-config.sh',
});
configReplace({
regex: '<pubsub-topic>',
replacement: config.pubsubTopic,
path: './backend/deploy-config.sh',
});
configReplace({
regex: '<configure-apis-and-roles>',
replacement: config.configureApisAndRoles ? 'true' : 'false',
path: './backend/deploy-config.sh',
});
configReplace({
regex: '<use-cloud-build>',
replacement: config.useCloudBuild ? 'true' : 'false',
path: './backend/deploy-config.sh',
});
}
if (config.deployUi) {
configReplace({
regex: '<gcs-bucket>',
replacement: config.gcsBucket!,
path: './ui/src/config.ts',
});
}
console.log();
}