UNPKG

github-glitch-sync

Version:

Utility tool to reduce your glitch code boilerplate, and simplify GitHub <-> Glitch sync.

56 lines (41 loc) 1.86 kB
const {exec} = require("child_process"); const {promisify} = require("util"); const execPromise = promisify(exec); const express = require("express"); const {GITHUB_USER_EMAIL, GITHUB_USER_NAME, GITHUB_USER_TOKEN} = process.env; function initialize(expressApp, {hookUrl = "/github-sync-hook", branch = "master", user = {}} = {}) { expressApp.use(hookUrl, express.json()) expressApp.post(hookUrl, function (req, res) { if (isGithubPushEvt(req)) { const {repository: {clone_url: origin}, head_commit} = req.body; console.log(`github-glitch-sync: New Commit 🎉 ${head_commit.message} / (email: ${head_commit.author.email})`); setupGitHub(user, origin) .then(() => performGitHubFetch(branch)) .then(refreshGlitchProject) } return res.sendStatus(200); }); } function setupGitHub(user, origin) { const {email = GITHUB_USER_EMAIL, name: username = GITHUB_USER_NAME, token = GITHUB_USER_TOKEN} = user || {}; console.log(`user: `, user); console.log({email, username, token, origin}); const authOrigin = origin.replace("://", `://${username}:${token}@`); console.log(`authOrigin: `, authOrigin); return execPromise(`git config user.name "${username}"`) .then(() => execPromise(`git config user.email "${email}"`)) .then(() => execPromise(`git config remote.origin.url >&- || git remote add origin ${authOrigin}`)) } function performGitHubFetch(branch) { return execPromise(`git fetch origin ${branch}`) .then(() => execPromise(`git reset --hard origin/${branch}`)) .then(() => execPromise(`git pull origin ${branch}`)) } function refreshGlitchProject() { return execPromise("refresh"); } function isGithubPushEvt(req) { return (req.headers['x-github-event'] === "push") } module.exports = {initialize};