|
| 1 | +import { Handler } from './Handler' |
| 2 | + |
| 3 | +export class ArtifactsHandler extends Handler { |
| 4 | + constructor(githubToken, namespace = '', artifactsRegex = '') { |
| 5 | + super(githubToken) |
| 6 | + |
| 7 | + this.namespace = namespace |
| 8 | + this.artifactsRegex = artifactsRegex |
| 9 | + } |
| 10 | + |
| 11 | + async handle(body, callback) { |
| 12 | + let response = this.validateEvent(body) |
| 13 | + |
| 14 | + if (response !== true) { |
| 15 | + return callback(null, response) |
| 16 | + } |
| 17 | + |
| 18 | + console.log(`Working on repo ${body.repository.full_name} for PR #${body.pull_request.number}`) |
| 19 | + |
| 20 | + const payload = { |
| 21 | + success: { |
| 22 | + state: 'success', |
| 23 | + description: 'No artifacts found in deps', |
| 24 | + context: `${this.namespace} - Artifacts check`, |
| 25 | + }, |
| 26 | + failure: { |
| 27 | + state: 'failure', |
| 28 | + description: 'Artifacts found in deps, remove them to merge', |
| 29 | + context: `${this.namespace} - Artifacts check`, |
| 30 | + }, |
| 31 | + } |
| 32 | + |
| 33 | + const files = await this.githubClient.rest.pulls.listFiles({ |
| 34 | + owner: body.repository.owner.login, |
| 35 | + repo: body.repository.name, |
| 36 | + pull_number: body.pull_request.number, |
| 37 | + }) |
| 38 | + |
| 39 | + // loop through all files to see if package.json has been updated |
| 40 | + const file = files.data.find(({ filename }) => filename.includes('package.json')) |
| 41 | + |
| 42 | + if (!file) { |
| 43 | + response = await this.updateStatus(body, payload.success) |
| 44 | + |
| 45 | + return callback(null, response) |
| 46 | + } |
| 47 | + |
| 48 | + const refMatch = file.contents_url.match(/ref=([a-z0-9]+)/) |
| 49 | + if (!refMatch?.[1]) { |
| 50 | + response = await this.updateStatus(body, payload.success) |
| 51 | + |
| 52 | + return callback(null, response) |
| 53 | + } |
| 54 | + |
| 55 | + const content = await this.githubClient.rest.repos.getContent({ |
| 56 | + owner: body.repository.owner.login, |
| 57 | + repo: body.repository.name, |
| 58 | + path: file.filename, |
| 59 | + ref: refMatch[1], |
| 60 | + }) |
| 61 | + |
| 62 | + const match = Buffer.from(content.data.content.toString('utf8'), 'base64') |
| 63 | + .toString('ascii') |
| 64 | + .match(this.artifactsRegex) |
| 65 | + |
| 66 | + if (match === null) { |
| 67 | + response = await this.updateStatus(body, payload.success) |
| 68 | + } else { |
| 69 | + response = await this.updateStatus(body, payload.failure) |
| 70 | + } |
| 71 | + |
| 72 | + return callback(null, response) |
| 73 | + } |
| 74 | +} |
0 commit comments