-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
executable file
·85 lines (69 loc) · 2.01 KB
/
index.js
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
#!/usr/bin/env node
const inquirer = require('inquirer');
const execa = require('execa');
const getStream = require('get-stream');
const _ = require('lodash');
const addDelimiter = '\u001b[32m \u001b[32m+\u001b[0m \u001b[32m';
const deleteDelimiter = '\u001b[31m \u001b[31m-\u001b[0m \u001b[31m';
const toTrim = '\u001b[0m';
(async function run() {
try {
const plan = await parsePlan();
await prompt(plan);
} catch (err) {
console.error(err);
}
})();
async function parsePlan() {
const stdout = await shell('terraform plan');
const toAdd = parseResource(stdout, addDelimiter);
const toDelete = parseResource(stdout, deleteDelimiter);
return { toAdd, toDelete };
}
function parseResource(stdout, delimiter) {
return stdout
.split('\n')
.filter(s => s.includes(delimiter))
.map(s => s.replace(delimiter, '').replace(toTrim, ''));
}
async function prompt(plan) {
if (isEmpty(plan, 'toDelete')) return;
const planAfterMove = await pickMove(plan);
await prompt(planAfterMove);
}
async function isProceed() {
const { isProceed } = await inquirer.prompt([{
type: 'confirm',
name: 'isProceed',
message: 'Move another resource?',
default: true
}]);
return isProceed;
}
async function pickMove({ toDelete, toAdd }) {
const { from, to } = await inquirer.prompt([{
type: 'list',
name: 'from',
message: 'What move?',
choices: toDelete
}, {
type: 'list',
name: 'to',
message: 'Move to:',
choices: toAdd
}]);
const toDeleteAfterMove = _.remove(toDelete, item => item !== from);
const toAddAfterMove = _.remove(toAdd, item => item !== to);
await shell(`terraform state mv ${from} ${to}`);
return { toDelete: toDeleteAfterMove, toAdd: toAddAfterMove };
}
function shell(command) {
const [first, ...other] = command.split(' ');
const { stdout, stderr } = execa(first, other);
stdout.pipe(process.stdout);
stderr.pipe(process.stderr);
return getStream(stdout);
}
function isEmpty(object, key) {
return _.isEmpty(_.get(object, key));
}