Skip to content

Instantly share code, notes, and snippets.

@permpkin
Created May 26, 2023 04:32
Show Gist options
  • Save permpkin/cec752a2db5dbdf6a819ecf58a922283 to your computer and use it in GitHub Desktop.
Save permpkin/cec752a2db5dbdf6a819ecf58a922283 to your computer and use it in GitHub Desktop.
const express = require('express');
const { exec } = require('child_process');
const app = express();
const PORT = process.env.PORT || 3000;
const GITHUB_SECRET = process.env.GITHUB_SECRET_TOKEN;
/**
* # Set github webhook to yourdomain.com(:3000 if no proxy)/api/hook ( or adjust route below )
* GITHUB_SECRET_TOKEN=your-github-secret-token
* PORT=3000
* RUN_CMD='cd /my-folder/ && git pull && npm install && pm2 restart'
**/
app.use(express.json());
app.post('/api/hook', (req, res) => {
const { body, headers } = req;
// Verify if the request is coming from GitHub
const isGithubRequest = headers['user-agent'].includes('GitHub-Hookshot');
if (!isGithubRequest) {
return res.status(403).send('Forbidden');
}
// Verify the event type is "pull_request" and action is "closed"
const eventType = headers['x-github-event'];
const action = body.action;
if (eventType !== 'pull_request' || action !== 'closed') {
return res.status(204).send('Event not relevant');
}
// Verify if the pull request was for the "development" branch
const branchName = body.pull_request.head.ref;
if (branchName !== 'development') {
return res.status(204).send('Branch not relevant');
}
// Perform the required actions
exec(
process.env.RUN_CMD,
(error, stdout, stderr) => {
if (error) {
console.error(`Error executing commands: ${error}`);
return res.status(500).send('Internal Server Error');
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
return res.status(200).send('OK');
}
);
});
app.listen(PORT, () => {
console.log(`Webhook endpoint listening on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment