2011-10-27 66 views
1

我想在Nodejs中創建一個post-receive掛鉤來更新我的服務器時,我的Github repo已更新。Github後接收掛鉤在Nodejs

我已經在php中完成了這項工作。我現在使用Nodejs,並且不確定應該如何實現。

我查看了this博客文章,關於在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實例。

回答

2

git裸存儲庫不包含工作樹。所以要使用這些文件,你必須檢查它們。

把上面的腳本放在(僞路徑)中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 

這裏是設置遠程裸git倉庫的體面runthrough http://toroid.org/ams/git-website-howto

0

nodeExpress)的應用程序下運行forever,所以我使用下面的處理程序,它基本上做了一個git pull並殺死自己(因此重生)。

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

你推鉤