-
Notifications
You must be signed in to change notification settings - Fork 49
/
index.js
executable file
·76 lines (62 loc) · 1.74 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
#!/usr/bin/env node
const fs = require('fs');
const inquirer = require('inquirer');
console.log('AWS Profile Switcher');
const homeDir = process.env['HOME']
const profileRegex = /\[profile .*]/g;
const bracketsRemovalRegx = /(\[profile )|(\])/g;
const defaultProfileChoice = 'default';
const promptProfileChoice = (data) => {
const matches = data.match(profileRegex);
if (!matches) {
console.log('No profiles found.');
console.log('Refer to this guide for help on setting up a new AWS profile:');
console.log('https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html');
return;
}
const profiles = matches.map((match) => {
return match.replace(bracketsRemovalRegx, '');
});
profiles.push(defaultProfileChoice);
const profileChoice = [
{
type: 'list',
name: 'profile',
message: 'Choose a profile',
choices: profiles,
default: process.env.AWS_PROFILE || defaultProfileChoice
}
];
return inquirer.prompt(profileChoice);
}
const readAwsProfiles = () => {
return new Promise((resolve, reject) => {
fs.readFile(`${homeDir}/.aws/config`, 'utf8', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
const writeToConfig = (answers) => {
const profileChoice =
answers.profile === defaultProfileChoice ? '' : answers.profile;
return new Promise((resolve, reject) => {
fs.writeFile(`${homeDir}/.awsp`, profileChoice, { flag: 'w' }, function (err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
readAwsProfiles()
.then(promptProfileChoice)
.then(writeToConfig)
.catch(error => {
console.log('Error:', error);
process.exit(1);
});