-
Notifications
You must be signed in to change notification settings - Fork 155
/
index.js
516 lines (461 loc) · 17.8 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
const path = require('path')
const yaml = require('js-yaml')
const fs = require('fs')
const cron = require('node-cron');
const Glob = require('./lib/glob')
const ConfigManager = require('./lib/configManager')
const NopCommand = require('./lib/nopcommand')
let deploymentConfig
module.exports = (robot, _, Settings = require('./lib/settings')) => {
async function syncAllSettings (nop, context, repo = context.repo(), ref) {
try {
deploymentConfig = await loadYamlFileSystem()
robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`)
const configManager = new ConfigManager(context,ref)
const runtimeConfig = await configManager.loadGlobalSettingsYaml();
const config = Object.assign({}, deploymentConfig, runtimeConfig)
robot.log.debug(`config for ref ${ref} is ${JSON.stringify(config)}`)
if (ref) {
return Settings.syncAll(nop, context, repo, config, ref)
} else {
return Settings.syncAll(nop, context, repo, config)
}
} catch(e) {
if (nop) {
let filename="settings.yml"
if (!deploymentConfig) {
filename="deployment-settings.yml"
deploymentConfig={}
}
const nopcommand = new NopCommand(filename, repo, null,e, "ERROR")
console.error(`NOPCOMMAND ${JSON.stringify(nopcommand)}`)
Settings.handleError(nop, context, repo, deploymentConfig, ref, nopcommand)
} else {
throw e
}
}
}
async function syncSubOrgSettings (nop, context, suborg, repo = context.repo(), ref) {
try {
deploymentConfig = await loadYamlFileSystem()
robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`)
const configManager = new ConfigManager(context, ref)
const runtimeConfig = await configManager.loadGlobalSettingsYaml();
const config = Object.assign({}, deploymentConfig, runtimeConfig)
robot.log.debug(`config for ref ${ref} is ${JSON.stringify(config)}`)
return Settings.syncAll(nop, context, repo, config, ref)
} catch(e) {
if (nop) {
let filename="settings.yml"
if (!deploymentConfig) {
filename="deployment-settings.yml"
deploymentConfig={}
}
const nopcommand = new NopCommand(filename, repo, null,e, "ERROR")
console.error(`NOPCOMMAND ${JSON.stringify(nopcommand)}`)
Settings.handleError(nop, context, repo, deploymentConfig, ref, nopcommand)
} else {
throw e
}
}
}
async function syncSettings (nop, context, repo = context.repo(), ref) {
try {
deploymentConfig = await loadYamlFileSystem()
robot.log.debug(`deploymentConfig is ${JSON.stringify(deploymentConfig)}`)
//const runtimeConfig = await loadYaml(context)
const configManager = new ConfigManager(context,ref)
const runtimeConfig = await configManager.loadGlobalSettingsYaml();
const config = Object.assign({}, deploymentConfig, runtimeConfig)
robot.log.debug(`config for ref ${ref} is ${JSON.stringify(config)}`)
return Settings.sync(nop, context, repo, config, ref)
} catch(e) {
if (nop) {
let filename="settings.yml"
if (!deploymentConfig) {
filename="deployment-settings.yml"
deploymentConfig={}
}
const nopcommand = new NopCommand(filename, repo, null,e, "ERROR")
console.error(`NOPCOMMAND ${JSON.stringify(nopcommand)}`)
Settings.handleError(nop, context, repo, deploymentConfig, ref, nopcommand)
} else {
throw e
}
}
}
/**
* Loads the deployment config file from file system
* Do this once when the app starts and then return the cached value
*
* @return The parsed YAML file
*/
async function loadYamlFileSystem () {
if (deploymentConfig === undefined) {
const deploymentConfigPath = process.env.DEPLOYMENT_CONFIG_FILE ? process.env.DEPLOYMENT_CONFIG_FILE : 'deployment-settings.yml'
if (fs.existsSync(deploymentConfigPath)) {
deploymentConfig = yaml.load(fs.readFileSync(deploymentConfigPath))
} else {
//console.error(`Safe-settings load deployment config failed: file ${deploymentConfigPath} not found`)
//process.exit(1)
deploymentConfig = { restrictedRepos: [ 'admin', '.github', 'safe-settings' ] }
}
}
return deploymentConfig
}
/**
* Loads a file from GitHub
*
* @param params Params to fetch the file with
* @return The parsed YAML file
*/
async function loadYaml (context) {
try {
const repo = { owner: context.repo().owner, repo: 'admin' }
const CONFIG_PATH = '.github'
const params = Object.assign(repo, { path: path.posix.join(CONFIG_PATH, 'settings.yml') })
const response = await context.octokit.repos.getContent(params).catch(e => {
console.log.error(e)
console.error(`Error getting settings ${e}`)
})
// Ignore in case path is a folder
// - https://developer.github.com/v3/repos/contents/#response-if-content-is-a-directory
if (Array.isArray(response.data)) {
return null
}
// we don't handle symlinks or submodule
// - https://developer.github.com/v3/repos/contents/#response-if-content-is-a-symlink
// - https://developer.github.com/v3/repos/contents/#response-if-content-is-a-submodule
if (typeof response.data.content !== 'string') {
return
}
return yaml.load(Buffer.from(response.data.content, 'base64').toString()) || {}
} catch (e) {
if (e.status === 404) {
return null
}
throw e
}
}
function getModifiedRepoConfigName(payload) {
const repoSettingPattern = new Glob(".github/repos/*.yml")
let commit = payload.commits.find(c => {
return ( c.modified.find(s => {
robot.log.debug(JSON.stringify(s))
return ( s.search(repoSettingPattern)>=0 )
}) !== undefined )
})
if (commit) {
robot.log.debug(`${JSON.stringify(commit)}`)
return repo = {repo: commit.modified[0].match(repoSettingPattern)[1], owner: payload.repository.owner.name}
} else {
robot.log.debug(`No modifications to repo configs`)
}
return undefined
}
function getAddedRepoConfigName(payload) {
const repoSettingPattern = new Glob(".github/repos/*.yml")
let commit = payload.commits.find(c => {
return ( c.added.find(s => {
robot.log.debug(JSON.stringify(s))
return ( s.search(repoSettingPattern)>=0 )
}) !== undefined )
})
if (commit) {
robot.log.debug(`${JSON.stringify(commit)}`)
return repo = {repo: commit.added[0].match(repoSettingPattern)[1], owner: payload.repository.owner.name}
} else {
robot.log.debug(`No additions to repo configs`)
}
return undefined
}
function getAddedSubOrgConfigName(payload) {
const repoSettingPattern = new Glob(".github/suborgs/*.yml")
let commit = payload.commits.find(c => {
return ( c.added.find(s => {
robot.log.debug(JSON.stringify(s))
return ( s.search(repoSettingPattern)>=0 )
}) !== undefined )
})
if (commit) {
robot.log.debug(`${JSON.stringify(commit)}`)
return {suborg: commit.added[0].match(repoSettingPattern)[1], org: payload.repository.owner.name}
} else {
robot.log.debug(`No additions to suborgs configs`)
}
return undefined
}
function getModifiedSubOrgConfigName(payload) {
const repoSettingPattern = new Glob(".github/suborgs/*.yml")
let commit = payload.commits.find(c => {
return ( c.modified.find(s => {
robot.log.debug(JSON.stringify(s))
return ( s.search(repoSettingPattern)>=0 )
}) !== undefined )
})
if (commit) {
robot.log.debug(`${JSON.stringify(commit)} \n ${commit.modified[0].match(repoSettingPattern)[1]}`)
return repo = {suborg: commit.modified[0].match(repoSettingPattern)[1], org: payload.repository.owner.name}
} else {
robot.log.debug(`No modifications to suborgs configs`)
}
return undefined
}
function getChangedConfigName(glob, files, owner) {
let modifiedFile = files.find(s => {
return ( s.search(glob)>=0 )
})
if (modifiedFile) {
robot.log.debug(`${JSON.stringify(modifiedFile)}`)
return repo = {repo: modifiedFile.match(glob)[1], owner: owner}
} else {
robot.log.debug(`No changes to repo configs`)
}
return undefined
}
async function createCheckRun(context, pull_request, head_sha, head_branch) {
const { payload } = context
robot.log.debug(`Check suite was requested! for ${context.repo()} ${pull_request.number} ${head_sha} ${head_branch}`)
const res = await context.octokit.checks.create({
owner: payload.repository.owner.login,
repo: payload.repository.name,
name: 'Safe-setting validator',
head_sha: head_sha
})
robot.log.debug(JSON.stringify(res,null))
}
async function syncInstallation () {
robot.log.trace('Fetching installations')
const github = await robot.auth()
const installations = await github.paginate(
github.apps.listInstallations.endpoint.merge({ per_page: 100 })
)
for (installation of installations) {
robot.log.trace(`${JSON.stringify(installation)}`)
const github = await robot.auth(installation.id)
const context = {
payload: {
installation: installation
},
octokit: github,
log: robot.log,
repo: () => { return {repo: "admin", owner: installation.account.login}}
}
return syncAllSettings(false, context)
}
retrun
}
robot.on('push', async context => {
const { payload } = context
const { repository } = payload
const adminRepo = repository.name === 'admin'
if (!adminRepo) {
return
}
const defaultBranch = payload.ref === 'refs/heads/' + repository.default_branch
if (!defaultBranch) {
robot.log.debug('Not working on the default branch, returning...')
return
}
const settingsModified = payload.commits.find(commit => {
return commit.added.includes(Settings.FILE_NAME) ||
commit.modified.includes(Settings.FILE_NAME)
})
let repo = getModifiedRepoConfigName(payload)
if (repo) {
return syncSettings(false, context, repo)
}
repo = getAddedRepoConfigName(payload)
if (repo) {
return syncSettings(false, context, repo)
}
let suborg = getModifiedSubOrgConfigName(payload)
if (suborg) {
return syncSubOrgSettings(false, context, suborg)
}
suborg = getAddedSubOrgConfigName(payload)
if (suborg) {
return syncSubOrgSettings(false, context, suborg)
}
if (!settingsModified) {
robot.log.debug(`No changes in '${Settings.FILE_NAME}' detected, returning...`)
return
}
return syncAllSettings(false, context)
})
robot.on('branch_protection_rule', async context => {
const { payload } = context
const { changes, repository, sender } = payload
robot.log.debug('Branch Protection edited by ', JSON.stringify(sender))
if (sender.type === 'Bot') {
robot.log.debug('Branch Protection edited by Bot')
return
}
console.log('Branch Protection edited by a Human')
return syncSettings(false, context)
})
robot.on('repository.edited', async context => {
const { payload } = context
const { changes, repository, sender } = payload
robot.log.debug('repository.edited payload from ', JSON.stringify(sender))
if (sender.type === 'Bot') {
robot.log.debug('Repository Edited by a Bot')
return
}
console.log('Repository Edited by a Human')
if (!Object.prototype.hasOwnProperty.call(changes, 'default_branch')) {
robot.log.debug('Repository configuration was edited but the default branch was not affected, returning...')
return
}
robot.log.debug(`Default branch changed from '${changes.default_branch.from}' to '${repository.default_branch}'`)
return syncSettings(false, context)
})
robot.on('check_suite.requested', async context => {
const { payload } = context
const { repository } = payload
const adminRepo = repository.name === 'admin'
robot.log.debug(`Is Admin repo event ${adminRepo}`)
if (!adminRepo) {
robot.log.debug('Not working on the Admin repo, returning...')
return
}
const defaultBranch = payload.check_suite.head_branch === repository.default_branch
if (defaultBranch) {
robot.log.debug(' Working on the default branch, returning...')
return
}
if (!payload.check_suite.pull_requests[0]) {
robot.log.debug('Not working on a PR, returning...')
return
}
const pull_request = payload.check_suite.pull_requests[0]
createCheckRun(context, pull_request, payload.check_suite.head_sha, payload.check_suite.head_branch)
})
robot.on('pull_request.opened', async context => {
robot.log.debug('Pull_request opened !')
const { payload } = context
const { repository } = payload
const adminRepo = repository.name === 'admin'
robot.log.debug(`Is Admin repo event ${adminRepo}`)
if (!adminRepo) {
robot.log.debug('Not working on the Admin repo, returning...')
return
}
const defaultBranch = payload.pull_request.head_branch === repository.default_branch
if (defaultBranch) {
robot.log.debug(' Working on the default branch, returning...')
return
}
const pull_request = payload.pull_request
console.log(JSON.stringify(pull_request,null,2))
createCheckRun(context,pull_request, payload.pull_request.head.sha, payload.pull_request.head.ref)
})
robot.on('pull_request.reopened', async context => {
robot.log.debug('Pull_request REopened !')
const { payload } = context
const { repository } = payload
const pull_request = payload.pull_request
const adminRepo = repository.name === 'admin'
robot.log.debug(`Is Admin repo event ${adminRepo}`)
if (!adminRepo) {
robot.log.debug('Not working on the Admin repo, returning...')
return
}
const defaultBranch = payload.pull_request.head_branch === repository.default_branch
if (defaultBranch) {
robot.log.debug(' Working on the default branch, returning...')
return
}
console.log(JSON.stringify(pull_request,null,2))
createCheckRun(context,pull_request, payload.pull_request.head.sha, payload.pull_request.head.ref)
})
robot.on([ 'check_suite.rerequested'], async context => {
robot.log.debug('Check suite was rerequested!')
createCheckRun(context)
})
robot.on([ 'check_suite.rerequested'], async context => {
robot.log.debug('Check suite was rerequested!')
createCheckRun(context)
})
robot.on([ 'check_run.created'], async context => {
robot.log.debug(`Check run was created!`)
const { payload } = context
const { repository } = payload
const { check_run } = payload
const { check_suite } = check_run
const pull_request = check_suite.pull_requests[0]
const source = payload.check_run.name === "Safe-setting validator"
if (!source) {
robot.log.debug(' Not triggered by Safe-settings...')
return
}
const adminRepo = repository.name === 'admin'
robot.log.debug(`Is Admin repo event ${adminRepo}`)
if (!adminRepo) {
robot.log.debug('Not working on the Admin repo, returning...')
return
}
if (!pull_request) {
robot.log.debug('Not working on a PR, returning...')
return
}
let params = {
owner: payload.repository.owner.login,
repo: payload.repository.name,
check_run_id: payload.check_run.id,
status: 'in_progress',
started_at: new Date().toISOString(),
output: { title: "Starting NOP", summary: "initiating..."}
}
robot.log.debug(`Updating check run ${JSON.stringify(params)}`)
let res = await context.octokit.checks.update(params)
// guarding against null value from upstream libary that is
// causing a 404 and the check to stall
// from issue: https://github.com/github/safe-settings/issues/185#issuecomment-1075240374
if (check_suite.before === "0000000000000000000000000000000000000000")
{
check_suite.before = check_suite.pull_requests[0].base.sha;
}
params = Object.assign(context.repo(), { basehead: `${check_suite.before}...${check_suite.after}` })
const changes = await context.octokit.repos.compareCommitsWithBasehead(params)
const files = changes.data.files.map(f => { return f.filename })
const repo = getChangedConfigName(new Glob(".github/repos/*.yml"), files, context.repo().owner)
robot.log.debug(`${JSON.stringify(repo, null, 4)}`)
if (repo) {
return syncSettings(true, context, repo, pull_request.head.ref)
}
const suborg = getChangedConfigName(new Glob(".github/suborgs/*.yml"), files, context.repo().owner)
if (suborg) {
return syncAllSettings(true, context, suborg, pull_request.head.ref )
}
return syncAllSettings(true, context, context.repo(), pull_request.head.ref )
})
robot.on('repository.created', async context => {
const { payload } = context
const { sender } = payload
robot.log.debug('repository.created payload from ', JSON.stringify(sender))
if (sender.type === 'Bot') {
robot.log.debug('Repository created by a Bot')
return
}
robot.log.debug('Repository created by a Human')
return syncSettings(false, context)
})
if (process.env.CRON) {
/*
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
*/
cron.schedule(process.env.CRON, () => {
console.log('running a task every minute');
syncInstallation()
});
}
}