-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.mjs
More file actions
582 lines (519 loc) · 17.3 KB
/
interactive.mjs
File metadata and controls
582 lines (519 loc) · 17.3 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import {
getLagoonInstances,
getProjectsWithDetails,
getEnvironments,
getUsers,
deleteEnvironment,
generateLoginLink,
clearDrupalCache,
gitUrlToGithubUrl,
extractPrNumber,
getGitBranches,
deployBranch
} from './lagoon-api';
import { logAction } from './logger';
import { configureSshKey } from './lagoon-ssh-key-configurator';
// Register the autocomplete prompt with inquirer
try {
const autocompletePrompt = (await import('inquirer-autocomplete-prompt')).default;
inquirer.registerPrompt('autocomplete', autocompletePrompt);
} catch (error) {
console.log(chalk.yellow('Autocomplete prompt not available, falling back to standard list selection.'));
}
/**
* Launches the interactive Lagoon CLI wrapper, allowing users to manage projects and environments through a guided command-line interface.
*
* Presents menus for selecting Lagoon instances and projects, and provides options to list environments or users, delete environments, generate login links, clear Drupal cache, configure SSH keys, and change selections. Handles errors gracefully and logs major actions throughout the session.
*/
export async function startInteractiveMode() {
console.log(chalk.green('Welcome to the Lagoon CLI Wrapper!'));
logAction('Application Start', 'N/A', 'Interactive mode started');
let exit = false;
let currentInstance = null;
let currentProject = null;
let currentProjectDetails = null;
let githubBaseUrl = null;
while (!exit) {
try {
// If no instance is selected, prompt for one
if (!currentInstance) {
currentInstance = await selectLagoonInstance();
logAction('Select Instance', 'N/A', `Selected instance: ${currentInstance}`);
}
// If no project is selected, prompt for one
if (!currentProject) {
const result = await selectProjectWithDetails(currentInstance);
currentProject = result.projectName;
currentProjectDetails = result.projectDetails;
logAction('Select Project', 'N/A', `Selected project: ${currentProject}`);
// Convert git URL to GitHub URL if possible
if (currentProjectDetails.giturl) {
githubBaseUrl = gitUrlToGithubUrl(currentProjectDetails.giturl);
}
}
// Show main menu
const action = await showMainMenu(currentInstance, currentProject);
logAction('Menu Selection', 'N/A', `Selected action: ${action}`);
switch (action) {
case 'listEnvironments':
await listEnvironments(currentInstance, currentProject, githubBaseUrl);
break;
case 'listUsers':
await listUsers(currentInstance, currentProject);
break;
case 'deleteEnvironment':
await deleteEnvironmentFlow(currentInstance, currentProject, githubBaseUrl);
break;
case 'generateLoginLink':
await generateLoginLinkFlow(currentInstance, currentProject, githubBaseUrl);
break;
case 'clearCache':
await clearCacheFlow(currentInstance, currentProject, githubBaseUrl);
break;
case 'deployBranch':
await deployBranchFlow(currentInstance, currentProject, currentProjectDetails);
break;
case 'configureUserSshKey':
await configureSshKey(currentInstance, currentProject);
break;
case 'changeProject':
currentProject = null;
currentProjectDetails = null;
githubBaseUrl = null;
logAction('Change Project', 'N/A', 'Project selection reset');
break;
case 'changeInstance':
currentInstance = null;
currentProject = null;
currentProjectDetails = null;
githubBaseUrl = null;
logAction('Change Instance', 'N/A', 'Instance selection reset');
break;
case 'exit':
exit = true;
logAction('Exit Application', 'N/A', 'User exited the application');
break;
}
} catch (error) {
console.error(chalk.red(`Error: ${error.message}`));
await inquirer.prompt([
{
type: 'confirm',
name: 'continue',
message: 'Do you want to continue?',
default: true
}
]).then(answers => {
if (!answers.continue) {
exit = true;
logAction('Exit Application', 'N/A', 'User exited after error');
}
});
}
}
console.log(chalk.green('Thank you for using Lagoon CLI Wrapper!'));
}
async function selectLagoonInstance() {
const spinner = ora('Loading Lagoon instances...').start();
const instances = await getLagoonInstances();
spinner.stop();
const { instance } = await inquirer.prompt([
{
type: 'list',
name: 'instance',
message: 'Select a Lagoon instance:',
choices: instances
}
]);
return instance;
}
async function selectProjectWithDetails(instance) {
const spinner = ora(`Loading projects for ${instance}...`).start();
const projectsWithDetails = await getProjectsWithDetails(instance);
spinner.stop();
const projectChoices = projectsWithDetails.map(project => ({
name: project.projectname,
value: project.projectname
}));
const { project } = await inquirer.prompt([
{
type: 'list',
name: 'project',
message: 'Select a project:',
choices: projectChoices
}
]);
const projectDetails = projectsWithDetails.find(p => p.projectname === project);
return {
projectName: project,
projectDetails: projectDetails
};
}
/**
* Displays the main menu for the interactive CLI and prompts the user to select an action.
*
* @param {string} instance - The name of the currently selected Lagoon instance.
* @param {string} project - The name of the currently selected project.
* @returns {Promise<string>} The action selected by the user.
*/
async function showMainMenu(instance, project) {
console.log(chalk.blue(`\nCurrent Instance: ${chalk.bold(instance)}`));
console.log(chalk.blue(`Current Project: ${chalk.bold(project)}\n`));
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'What would you like to do?',
choices: [
{ name: 'List Environments', value: 'listEnvironments' },
{ name: 'List Users', value: 'listUsers' },
{ name: 'Delete Environment', value: 'deleteEnvironment' },
{ name: 'Generate Login Link', value: 'generateLoginLink' },
{ name: 'Clear Drupal Cache', value: 'clearCache' },
{ name: 'Deploy Branch', value: 'deployBranch' },
{ name: 'Change Project', value: 'changeProject' },
{ name: 'Change Instance', value: 'changeInstance' },
{ name: 'Configure User SSH Key', value: 'configureUserSshKey' },
{ name: 'Exit', value: 'exit' }
]
}
]);
return action;
}
async function listEnvironments(instance, project, githubBaseUrl) {
const spinner = ora(`Loading environments for ${project}...`).start();
const environments = await getEnvironments(instance, project);
spinner.stop();
console.log(chalk.green('\nEnvironments:'));
environments.forEach(env => {
const prNumber = extractPrNumber(env);
if (prNumber && githubBaseUrl) {
const prUrl = `${githubBaseUrl}/pull/${prNumber}`;
console.log(`- ${env} ${chalk.blue(`(PR #${prNumber}: ${prUrl})`)}`);
} else {
console.log(`- ${env}`);
}
});
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}
async function listUsers(instance, project) {
const spinner = ora(`Loading users for ${project}...`).start();
const users = await getUsers(instance, project);
spinner.stop();
console.log(chalk.green('\nUsers:'));
users.forEach(user => {
console.log(`- ${user}`);
});
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}
async function deleteEnvironmentFlow(instance, project, githubBaseUrl) {
const spinner = ora(`Loading environments for ${project}...`).start();
const allEnvironments = await getEnvironments(instance, project);
spinner.stop();
// Filter out protected environments
const eligibleEnvironments = allEnvironments.filter(env =>
env !== 'production' &&
env !== 'master' &&
env !== 'develop' &&
!env.startsWith('project/')
);
if (eligibleEnvironments.length === 0) {
console.log(chalk.yellow('\nNo eligible environments to delete.'));
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
return;
}
// Display environments with PR links before selection
console.log(chalk.green('\nEligible environments for deletion:'));
eligibleEnvironments.forEach(env => {
const prNumber = extractPrNumber(env);
if (prNumber && githubBaseUrl) {
const prUrl = `${githubBaseUrl}/pull/${prNumber}`;
console.log(`- ${env} ${chalk.blue(`(PR #${prNumber}: ${prUrl})`)}`);
} else {
console.log(`- ${env}`);
}
});
console.log(''); // Add a blank line for better readability
// Create choices with PR information for selection
const choices = eligibleEnvironments.map(env => {
const prNumber = extractPrNumber(env);
const prUrl = `${githubBaseUrl}/pull/${prNumber}`;
if (prNumber && githubBaseUrl) {
return {
name: `${env} (PR #${prUrl})`,
value: env
};
}
return env;
});
const { selectedEnvironments } = await inquirer.prompt([
{
type: 'checkbox',
name: 'selectedEnvironments',
message: 'Select environments to delete:',
choices: choices
}
]);
if (selectedEnvironments.length === 0) {
console.log(chalk.yellow('\nNo environments selected.'));
return;
}
const { confirm } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: `Are you sure you want to delete the following environment(s)?:\n${selectedEnvironments.map(env => ` - ${env}`).join('\n')}\n\nTotal: ${selectedEnvironments.length} environment(s)`,
default: false
}
]);
if (confirm) {
for (const env of selectedEnvironments) {
const spinner = ora(`Deleting environment ${env}...`).start();
try {
await deleteEnvironment(instance, project, env);
spinner.succeed(`Environment ${env} deleted successfully.`);
} catch (error) {
spinner.fail(`Failed to delete environment ${env}: ${error.message}`);
}
}
} else {
console.log(chalk.yellow('\nDeletion cancelled.'));
}
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}
async function generateLoginLinkFlow(instance, project, githubBaseUrl) {
const spinner = ora(`Loading environments for ${project}...`).start();
const allEnvironments = await getEnvironments(instance, project);
spinner.stop();
// Filter out protected environments
const eligibleEnvironments = allEnvironments.filter(env =>
env !== 'production' &&
env !== 'master'
);
if (eligibleEnvironments.length === 0) {
console.log(chalk.yellow('\nNo eligible environments for login link generation.'));
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
return;
}
// Create choices with PR information
const choices = eligibleEnvironments.map(env => {
const prNumber = extractPrNumber(env);
if (prNumber && githubBaseUrl) {
return {
name: `${env} (PR #${prNumber})`,
value: env
};
}
return env;
});
const { selectedEnvironment } = await inquirer.prompt([
{
type: 'list',
name: 'selectedEnvironment',
message: 'Select an environment to generate a login link:',
choices: choices
}
]);
const spinner2 = ora(`Generating login link for ${selectedEnvironment}...`).start();
try {
const loginLink = await generateLoginLink(instance, project, selectedEnvironment);
spinner2.succeed('Login link generated successfully.');
console.log(chalk.green('\nLogin Link:'));
console.log(chalk.cyan(loginLink));
} catch (error) {
spinner2.fail(`Failed to generate login link: ${error.message}`);
}
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}
async function clearCacheFlow(instance, project, githubBaseUrl) {
const spinner = ora(`Loading environments for ${project}...`).start();
const allEnvironments = await getEnvironments(instance, project);
spinner.stop();
if (allEnvironments.length === 0) {
console.log(chalk.yellow('\nNo environments found.'));
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
return;
}
// Create choices with PR information
const choices = allEnvironments.map(env => {
const prNumber = extractPrNumber(env);
if (prNumber && githubBaseUrl) {
return {
name: `${env} (PR #${prNumber})`,
value: env
};
}
return env;
});
const { selectedEnvironment } = await inquirer.prompt([
{
type: 'list',
name: 'selectedEnvironment',
message: 'Select an environment to clear cache:',
choices: choices
}
]);
const spinner2 = ora(`Clearing cache for ${selectedEnvironment}...`).start();
try {
const result = await clearDrupalCache(instance, project, selectedEnvironment);
spinner2.succeed('Cache cleared successfully.');
console.log(chalk.green('\nCache Clear Result:'));
console.log(chalk.cyan(result || 'Cache cleared successfully.'));
} catch (error) {
spinner2.fail(`Failed to clear cache: ${error.message}`);
}
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}
async function deployBranchFlow(instance, project, projectDetails) {
// Check if project has a git URL
if (!projectDetails || !projectDetails.giturl) {
console.log(chalk.yellow('\nThis project does not have a valid Git URL configured.'));
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
return;
}
console.log(chalk.blue(`\nFetching branches from ${chalk.bold(projectDetails.giturl)}...`));
const spinner = ora('Loading branches...').start();
try {
// Get branches from the git repository
const branches = await getGitBranches(projectDetails.giturl);
spinner.succeed(`Found ${branches.length} branches.`);
if (branches.length === 0) {
console.log(chalk.yellow('\nNo branches found in the git repository.'));
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
return;
}
// Sort the branches to put main/master/develop first, then the rest alphabetically
const sortedBranches = branches.sort((a, b) => {
const priority = ['main', 'master', 'develop'];
const aIndex = priority.indexOf(a);
const bIndex = priority.indexOf(b);
if (aIndex !== -1 && bIndex !== -1) {
return aIndex - bIndex;
} else if (aIndex !== -1) {
return -1;
} else if (bIndex !== -1) {
return 1;
} else {
return a.localeCompare(b);
}
});
// Allow user to select a branch using autocomplete
const { selectedBranch } = await inquirer.prompt([
{
type: 'autocomplete',
name: 'selectedBranch',
message: 'Select a branch to deploy:',
source: (answersSoFar, input = '') => {
return Promise.resolve(
sortedBranches.filter(branch =>
!input || branch.toLowerCase().includes(input.toLowerCase())
)
);
}
},
{
type: 'list',
name: 'selectedBranch',
message: 'Select a branch to deploy:',
choices: sortedBranches
}
]);
// Confirm deployment
const { confirm } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: `Are you sure you want to deploy branch ${chalk.bold(selectedBranch)} to project ${chalk.bold(project)}?`,
default: false
}
]);
if (!confirm) {
console.log(chalk.yellow('\nDeployment cancelled.'));
return;
}
// Deploy the branch
const spinner2 = ora(`Deploying branch ${selectedBranch}...`).start();
try {
const result = await deployBranch(instance, project, selectedBranch);
spinner2.succeed('Deployment initiated successfully.');
console.log(chalk.green('\nDeployment Status:'));
console.log(chalk.cyan(result.message || 'Branch deployment initiated.'));
console.log(chalk.blue('\nNote: The deployment process runs asynchronously and may take several minutes to complete.'));
console.log(chalk.blue('You can check the status of the deployment in the Lagoon UI.'));
} catch (error) {
spinner2.fail(`Failed to deploy branch: ${error.message}`);
}
} catch (error) {
spinner.fail(`Failed to fetch branches: ${error.message}`);
}
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}