Last active
April 9, 2020 19:51
-
-
Save foxxyz/9410e8381b1f8f4f3e256ec0114da731 to your computer and use it in GitHub Desktop.
Node.js post-receive hook example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// post-receive hook for git-push deployments | |
const fs = require('fs') | |
const path = require('path') | |
const readline = require('readline') | |
const { spawn } = require('child_process') | |
const rl = readline.createInterface({ input: process.stdin, terminal: false }) | |
deployPath = 'C:/some/deploy/path' | |
deployBranch = 'master' | |
// Return logger with a color code | |
function logger(code) { | |
return (msg) => console.log(`\x1b[${code}m%s\x1b[0m`, msg) | |
} | |
const error = logger('91') | |
const info = logger('94') | |
function run(cmd, options) { | |
return new Promise((res, rej) => { | |
let defaultOptions = { shell: true } | |
let p = spawn(cmd, Object.assign(defaultOptions, options)) | |
let stderr = '' | |
p.stdout.pipe(process.stdout) | |
p.stderr.on('data', (chunk) => stderr += chunk) | |
p.on('error', rej) | |
p.on('close', (code) => { | |
if (code) return rej(stderr) | |
res() | |
}) | |
}) | |
} | |
async function postReceive(fromCommit, toCommit, branch) { | |
// Only deploy if branch matches | |
if (!branch.endsWith(`/${deployBranch}`)) { | |
throw `Received branch ${branch}, not deploying` | |
} | |
// Copy files | |
info(`Deploying ${branch} (${toCommit}) to ${deployPath}...`) | |
await run(`git --work-tree "${deployPath}" checkout -f ${branch}`) | |
// Do some other operation | |
info('Installing dependencies...') | |
await run('npm ci', { cwd: deployPath }) | |
} | |
rl.on('line', line => { | |
postReceive(...line.split(' ')).catch(error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment