forked from CircleCI-Public/CircleCI-Env-Inspector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
225 lines (207 loc) · 5.84 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
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
import inquirer from "inquirer";
import {
exitWithError,
getCollaborations,
getContexts,
getContextVariables,
getRepos,
getProjectVariables,
resolveVcsSlug,
} from "./utils.js";
import * as fs from "fs";
const CIRCLE_V1_API =
process.env.CIRCLE_V1_API ?? "https://circleci.com/api/v1.1";
const CIRCLE_V2_API =
process.env.CIRCLE_v2_API ?? "https://circleci.com/api/v2";
const GITHUB_API = process.env.GITHUB_API ?? "https://api.github.com";
const USER_DATA = {
contexts: [],
projects: [],
unavailable: [],
};
// Enter CircleCI Token if none is set
const CIRCLE_TOKEN =
process.env.CIRCLE_TOKEN ||
(
await inquirer.prompt([
{
message: "Enter your CircleCI API token",
type: "password",
name: "cciToken",
},
])
).cciToken;
// Select VCS
const VCS = (
await inquirer.prompt([
{
message: "Select a VCS",
type: "list",
name: "vcs",
choices: ["GitHub", "Bitbucket"],
},
])
).vcs;
// Enter GitHub Token if none is set
const GITHUB_TOKEN =
process.env.GITHUB_TOKEN ||
(
await inquirer.prompt([
{
message: "Enter your GitHub API token",
type: "password",
name: "ghToken",
when: VCS === "GitHub",
},
])
).ghToken;
const { response: resCollaborations, responseBody: collaboratorList } =
await getCollaborations(CIRCLE_V2_API, CIRCLE_TOKEN);
if (resCollaborations.status !== 200)
exitWithError(
"Failed to get collaborations with the following error:\n",
collaboratorList
);
else if (collaboratorList.length === 0)
exitWithError(
"There are no organizations of which you are a member or a collaborator",
collaboratorList
);
const filteredAccounts = collaboratorList.filter(account => VCS.toLowerCase() === account['vcs_type'].toLowerCase());
const accountNames = filteredAccounts.reduce((acc, curr) => [curr.name, ...acc], [])
const answers = await inquirer.prompt([
{
message: "Select an account",
type: "list",
name: "account",
choices: accountNames,
},
{
message: "Is this an Organization (Not a User)?",
type: "confirm",
name: "isOrg",
when: VCS === "GitHub",
},
]);
const accountID = collaboratorList.find(
(collaboration) => collaboration.name === answers.account
).id;
const getPaginatedData = async (api, token, identifier, caller) => {
const items = [];
let pageToken = "";
do {
const { response, responseBody } = await caller(
api,
token,
identifier,
pageToken
);
if (response.status !== 200)
exitWithError(
"Failed to get data with the following error:\n",
responseBody
);
if (responseBody.items.length > 0) items.push(...responseBody.items);
pageToken = responseBody.next_page_token;
} while (pageToken);
return items;
};
console.log("Getting Contexts Data...");
const contextList = await getPaginatedData(
CIRCLE_V2_API,
CIRCLE_TOKEN,
accountID,
getContexts
);
const contextData = await Promise.all(
contextList.map(async (context) => {
const variables = await getPaginatedData(
CIRCLE_V2_API,
CIRCLE_TOKEN,
context.id,
getContextVariables
);
return {
name: context.name,
id: context.id,
variables,
};
})
);
USER_DATA.contexts = contextData;
console.log("Getting Projects Data...");
const getRepoList = async (api, token, accountName) => {
const items = [];
const slug = answers.isOrg ? `orgs/${accountName}` : "user";
const source = VCS === "GitHub" ? "github" : "circleci";
let pageToken = 1;
let keepGoing = true;
do {
const { response, responseBody } = await getRepos(
api,
token,
slug,
pageToken
);
if (response.status !== 200)
exitWithError(
"Failed to get repositories with the following error:\n",
responseBody
);
const reducer =
VCS === "GitHub"
? (acc, curr) => [...acc, curr.full_name]
: (acc, curr) => [...acc, `${curr.username}/${curr.reponame}`];
if (responseBody.length > 0)
items.push(...responseBody.reduce(reducer, []));
// CircleCI only requires one request to get all repos.
if (responseBody.length === 0 || source === "circleci") keepGoing = false;
pageToken++;
} while (keepGoing);
return items;
};
const repoList =
VCS === "GitHub"
? await getRepoList(GITHUB_API, GITHUB_TOKEN, answers.account)
: await getRepoList(CIRCLE_V1_API, CIRCLE_TOKEN, answers.account);
console.log("Getting Projects Variables...");
const repoData = await Promise.all(
repoList.map(async (repo) => {
const vcsSlug = resolveVcsSlug(VCS);
let resProjectVars = await getProjectVariables(
CIRCLE_V2_API,
CIRCLE_TOKEN,
repo,
vcsSlug
);
if (resProjectVars.response.status === 429) {
let waitTime = 1;
let multiplier = 2;
let count = 0;
let maxWait = 300;
let maxRetries = 30;
do {
const retryAfterHeader =
resProjectVars.response.headers.get("retry-after");
const retryAfter =
!retryAfterHeader && retryAfterHeader > 0
? retryAfterHeader
: waitTime;
console.dir(`Waiting ${retryAfter} seconds. Retry #${count}`);
resProjectVars = await getProjectVariables(
CIRCLE_V2_API,
CIRCLE_TOKEN,
repo,
vcsSlug,
retryAfter
);
if (waitTime < maxWait) waitTime *= multiplier;
} while (resProjectVars.response.status === 429 && count++ < maxRetries);
} else if (resProjectVars.response.status != 200)
USER_DATA.unavailable.push(repo);
return { name: repo, variables: resProjectVars?.responseBody?.items };
})
);
USER_DATA.projects = repoData.filter((repo) => repo?.variables?.length > 0);
fs.writeFileSync("circleci-data.json", JSON.stringify(USER_DATA, null, 2));
console.log("Log created at circleci-data.json");