-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
258 lines (232 loc) · 8.22 KB
/
main.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
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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const GITHUB_API = 'https://api.github.com'
const TRAVIS_API = 'https://api.travis-ci.com'
const DEV_USER = 'dev-launchers-sandbox'
const PROD_ORG = "dev-launchers"
const USER_AGENT = 'dev-launchers-internal-api'
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
const url = new URL(request.url)
const projectName = url.searchParams.get("project")
const templateRepo = url.searchParams.get("template")
if (projectName == null) {
console.log("project name is not specified in query parameter")
return new Response(null, {
"status": 400,
"statusText": "project name is not specified in query parameter",
})
}
const repoName = "project__" + projectName
const githubAuthToken = await ADMIN_PORTAL.get("githubAuthToken")
const githubAPIClient = new GithubAPIClient(GITHUB_API, githubAuthToken, USER_AGENT)
let resp = await githubAPIClient.createDevRepo(repoName, DEV_USER, templateRepo)
if (resp.status != 201) {
console.log(`Failed to create dev ${repoName}, status ${resp.status}`)
return resp;
}
console.log("Created dev repo")
resp = await githubAPIClient.createProdRepo(repoName, PROD_ORG)
if (resp.status != 201) {
console.log(`Failed to create prod repo ${repoName}, status ${resp.status}`)
return resp
}
console.log("Created prod repo")
resp = await githubAPIClient.createBranchFromHead(repoName, DEV_USER, 'gh-pages')
if (resp.status != 201) {
console.log(`Failed to create gh-pages branch for ${repoName}, status ${resp.status}`)
return resp
}
console.log(`Create gh-pages branch for ${repoName}`)
resp = await githubAPIClient.enableGithubPage(repoName, DEV_USER, 'gh-pages')
if (resp.status != 201) {
console.log(`Failed to enabled github page on dev repo ${repoName} owned by ${DEV_USER}, status ${resp.status}`)
return resp
}
console.log("Enabled github page on dev repo")
resp = await githubAPIClient.enableGithubPage(repoName, PROD_ORG, 'master')
if (resp.status != 201) {
console.log(`Failed to enabled github page on prod repo ${repoName} owned by ${PROD_ORG}, status ${resp.status}`)
return resp
}
console.log("Enabled github page on prod repo")
const travisAuthToken = await ADMIN_PORTAL.get("travisAuthToken")
const travisAPIClient = new TravisAPIClient(TRAVIS_API, travisAuthToken, USER_AGENT)
const travisID = await travisAPIClient.findTravisIDByRepoName(DEV_USER, repoName)
if (travisID == undefined) {
err = `ID for ${repoName} not found`
console.log(err)
resp = new Response(null, {
"status": 404,
"statusText": err,
})
return resp
}
console.log(`ID of ${repoName} is ${travisID}`)
// Upload github token
const githubPageDeployToken = await ADMIN_PORTAL.get("githubPageDeployToken")
resp = await travisAPIClient.uploadEnvVar(travisID, "GITHUB_TOKEN", githubPageDeployToken)
if (resp.status != 201) {
console.log(`Failed to upload github page deploy token for ${repoName}, status ${resp.status}`)
return resp
}
console.log("upload GITHUB_TOKEN")
// Upload repo name
resp = await travisAPIClient.uploadEnvVar(travisID, "REPO_NAME", repoName)
if (resp.status != 201) {
console.log(`Failed to upload repo name for ${repoName}, status ${resp.status}`)
return resp
}
console.log("upload REPO_NAME")
return resp
}
class GithubAPIClient {
constructor(githubAPI, authToken, userAgent) {
this.baseURL = githubAPI
this.authHeaders = {
'Authorization': `token ${authToken}`,
'User-Agent': userAgent,
'Content-Type': "application/json"
}
}
async createDevRepo(repoName, user, templateRepo) {
if (templateRepo == null) {
templateRepo = "template__project"
}
const req = new Request(
`${this.baseURL}/repos/${user}/${templateRepo}/generate`,
{
method: 'POST',
headers: addAcceptHeader(this.authHeaders, "application/vnd.github.baptiste-preview+json"),
body: JSON.stringify({
"owner": user,
"name": repoName,
"description": "Development repository for " + repoName,
"private": false,
}),
},
)
return asyncFetch(req)
}
async createProdRepo(repoName, org) {
const req = new Request(
`${this.baseURL}/orgs/${org}/repos`,
{
method: 'POST',
headers: this.authHeaders,
body: JSON.stringify({
"name": repoName,
"description": "Production repository for " + repoName,
"auto_init": true,
"private": false,
}),
},
)
return asyncFetch(req)
}
async enableGithubPage(repoName, owner, branch) {
const req = new Request(
`${this.baseURL}/repos/${owner}/${repoName}/pages`,
{
method: 'POST',
headers: addAcceptHeader(this.authHeaders, "application/vnd.github.switcheroo-preview+json"),
body: JSON.stringify({
"source": {
"branch": branch,
},
}),
},
)
return asyncFetch(req)
}
async createBranchFromHead(repoName, owner, newBranch) {
// Get sha of head
const headShaReq = new Request(
`${this.baseURL}/repos/${owner}/${repoName}/git/refs/heads`,
{
method: 'GET',
headers: this.authHeaders,
},
)
const resp = await asyncFetch(headShaReq)
if (resp.status != 200) {
return resp
}
const headSha = await resp.json().then(body => {
return body[0].object.sha
})
const createBranchReq = new Request(
`${this.baseURL}/repos/${owner}/${repoName}/git/refs`,
{
method: 'POST',
headers: this.authHeaders,
body: JSON.stringify({
"ref": `refs/heads/${newBranch}`,
"sha": headSha
}),
},
)
return asyncFetch(createBranchReq)
}
}
class TravisAPIClient {
constructor(travisAPI, authToken, userAgent) {
this.baseURL = travisAPI
this.authHeaders = {
'Authorization': `token ${authToken}`,
'User-Agent': userAgent,
'Travis-API-Version': '3',
'Content-Type': 'application/json',
}
}
async findTravisIDByRepoName(owner, repoName) {
const req = new Request(
`${this.baseURL}/owner/${owner}/repos`,
{
method: 'GET',
headers: this.authHeaders,
}
)
const resp = await asyncFetch(req)
if (resp.status != 200) {
return undefined
}
return resp.json().then(body => {
const repoWithName = body.repositories.find(repo => {
return repo.name == repoName
})
return repoWithName.id
})
}
async uploadEnvVar(travisID, name, val) {
const req = new Request(
`${this.baseURL}/repo/${travisID}/env_vars`,
{
method: 'POST',
headers: this.authHeaders,
body: JSON.stringify({
"env_var.name": name,
"env_var.value": val,
"env_var.public": false,
}),
},
)
return asyncFetch(req)
}
}
async function asyncFetch(req) {
const resp = await fetch(req)
.then(function (response) {
return response
});
return resp
}
function addAcceptHeader(baseHeaders, acceptValue) {
let headers = baseHeaders
headers["Accept"] = acceptValue
return headers
}