Github后接收挂钩Nodejs
我正在尝试在Nodejs中创build一个post-receive hook来更新我的服务器,当我的Github repo被更新时。
我之前在php中做过这个。 我现在正在使用Nodejs,我不确定应该如何实现。
我已经看过这篇关于在ec2实例上设置nodejs的博文。 它说:
Create a post-recieve hook that will copy over new code after it's been pushed to the repository $ cat > hooks/post-receive #!/bin/sh GIT_WORK_TREE=/home/ubuntu/www export GIT_WORK_TREE git checkout -f $ chmod +x hooks/post-receive
我不确定上面的代码在做什么以及如何实现。
任何想法的最佳方式呢?
我正在运行基本的32位Amazon Linux EC2实例。
一个git裸仓库不包括工作树。 所以要使用这些文件,你必须检查它们。
把上面的脚本放在(伪path)ec2中:mybaregitrepo / hooks / post-recieve会使它每次运行到ec2都会运行。
意思是:
#!/bin/sh //set git working tree (the files you can use) to the path /home/ubuntu/www GIT_WORK_TREE=/home/ubuntu/www export GIT_WORK_TREE //force git checkout so that your files will be put into the working tree. git checkout -f
比:
//make the post-recieve hook executable so that it can run when you push commits to ec2 chmod +x hooks/post-receive
这里是一个体面的runthroughbuild立远程裸git回购http://toroid.org/ams/git-website-howto
我的node
( Express
)应用程序forever
运行,所以我使用下面的处理程序,基本上做一个git pull
和杀死自己(因此respawning)。
function handleGitHub(req, res, next) { setTimeout(function() { var shouldRestart = !app.config.webhook || req.body.head_commit.message.indexOf(app.config.webhook) > -1; console.log('[GITHUB] WebHook Received for "%s" (WebHook: %s, Restart? %s)', req.body && req.body.head_commit.message, app.config.webhook && app.config.webhook, shouldRestart); if (!shouldRestart) { console.log('[GITHUB] Not restarting'); return; } if (app.server_https && app.server_https.close) { console.log('[GITHUB] Closing HTTPS'); app.server_https.close(); } if (app.server && app.server.close) { console.log('[GITHUB] Closing HTTP'); app.server.close(); } setTimeout(function() { var spawn = require('child_process').spawn; var shell = process.env.SHELL; var args = ['-c', 'git pull']; var path = require('path'); var projectPath = '/path/to/your/project/folder'; //or path.join(__dirname, '.... var opts = { cwd: projectPath }; console.log('[GITHUB] Spawning...', opts); var spawnProcess = spawn(shell, args, opts); spawnProcess.stdout.on('data', function(data) { // could log these }); spawnProcess.stderr.on('data', function(data) { // could log these }); spawnProcess.on('close', function(exitCode) { console.log('[GITHUB] Spawn finished', exitCode); console.log('[GITHUB] Exiting...'); console.log('-------------------------------------------------------'); process.exit(0); }); }, 1000); }, 500); res.send(200, 'OK'); }
现在,只需使用一个指向这个函数的路由:
app.post('/some_path_you_setup_in_github_web_hooks', handleGitHub);
你可以在https://github.com/your_username/your_project/settings/hooks中设置你的push hook