This repository has been archived by the owner on Oct 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
executable file
·80 lines (67 loc) · 1.82 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
#!/usr/bin/env node
const fs = require("fs");
const inquirer = require("inquirer");
inquirer.registerPrompt("search-list", require("inquirer-search-list"));
console.log("AWS Profile Switcher Plus");
const homeDir = process.env["HOME"];
const configFilePath =
process.env["AWS_CONFIG_FILE"] || `${homeDir}/.aws/config`;
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-configure.html"
);
return;
}
const profiles = matches.map((match) => {
return match.replace(bracketsRemovalRegx, "");
});
profiles.push(defaultProfileChoice);
const profileChoice = [
{
type: "search-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(configFilePath, "utf8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
const writeToConfig = (answers) => {
return new Promise((resolve, reject) => {
fs.writeFile(`${homeDir}/.awsp`, answers.profile, { flag: "w" }, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
readAwsProfiles()
.then(promptProfileChoice)
.then(writeToConfig)
.catch((error) => {
console.log("Error:", error);
process.exit(1);
});