|
| 1 | +const SYNCUP_CONFIG = process.env.SYNCUP_CONFIG || 'sync-up.yml' |
| 2 | + |
| 3 | +const getConfig = require('probot-config') |
| 4 | +const createScheduler = require('probot-scheduler') |
| 5 | +const fetch = require('node-fetch') |
| 6 | +const yaml = require('js-yaml') |
| 7 | + |
| 8 | +const SyncUp = require('./lib/sync-up') |
| 9 | +const schema = require('./lib/schema') |
| 10 | + |
| 11 | +module.exports = async (robot) => { |
| 12 | + const scheduler = createScheduler(robot) |
| 13 | + |
| 14 | + robot.on('schedule.repository', routineCheck) |
| 15 | + robot.on('push', handlePush) |
| 16 | + robot.on(['pull_request', 'pull_request_review'], checkPRStatus) |
| 17 | + |
| 18 | + async function handlePush (context) { |
| 19 | + if (context.payload.commits.filter(c => c.message.indexOf(SYNCUP_CONFIG) > -1).length > 0) { |
| 20 | + await routineCheck(context) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + async function routineCheck (context) { |
| 25 | + const syncUp = await forRepository(context) |
| 26 | + if (syncUp) await syncUp.routineCheck() |
| 27 | + } |
| 28 | + |
| 29 | + async function checkPRStatus (context) { |
| 30 | + switch (context.event) { |
| 31 | + case 'pull_request': |
| 32 | + if (context.payload.action !== 'opened') { |
| 33 | + return |
| 34 | + } |
| 35 | + break |
| 36 | + case 'pull_request_review': |
| 37 | + if (context.payload.action !== 'submitted' || context.payload.review.state !== 'approved') { |
| 38 | + return |
| 39 | + } |
| 40 | + break |
| 41 | + default: |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + const syncUp = await forRepository(context) |
| 46 | + if (syncUp) await syncUp.checkAutoMerge(context.payload.pull_request) |
| 47 | + } |
| 48 | + |
| 49 | + async function forRepository (context) { |
| 50 | + if (!context.payload.repository.fork) { |
| 51 | + scheduler.stop(context.payload.repository) |
| 52 | + return null |
| 53 | + } |
| 54 | + |
| 55 | + const config = await getConfig(context, SYNCUP_CONFIG) |
| 56 | + if (!config) { |
| 57 | + scheduler.stop(context.payload.repository) |
| 58 | + return null |
| 59 | + } |
| 60 | + |
| 61 | + return new SyncUp(context.github, context.repo({ logger: robot.log }), config) |
| 62 | + } |
| 63 | + |
| 64 | + const app = robot.route('/_') |
| 65 | + |
| 66 | + app.get('/check/:owner/:repo', (req, res) => { |
| 67 | + fetch(`https://api.github.com/repos/${req.params.owner}/${req.params.repo}/contents/.github/${SYNCUP_CONFIG}`) |
| 68 | + .then(githubRes => githubRes.json()) |
| 69 | + .then(json => Buffer.from(json.content, 'base64').toString()) |
| 70 | + .then(yml => yaml.safeLoad(yml)) |
| 71 | + .then((config) => { |
| 72 | + const { error, value } = schema.validate(config) |
| 73 | + if (error) throw error |
| 74 | + res.end(JSON.stringify(value, null, 2)) |
| 75 | + }) |
| 76 | + .catch((e) => { |
| 77 | + res.status(400).end(`File not found or invalid`) |
| 78 | + }) |
| 79 | + }) |
| 80 | +} |
0 commit comments