当同一分支上有新的提交时,自动将本地git仓库与远程仓库同步

3

我在Amazon EC2实例上克隆了一个Git存储库。我想让ec2实例上的本地存储库始终在远程存储库的同一分支有新提交时自动同步(可以使用git pull command)。我该如何实现这一点?


3
您是否正在使用像GitHub或BitBucket这样的热门服务?如果是,您可以使用它们的网络钩子功能... GitHub:https://help.github.com/articles/about-webhooks/ 和 BitBucket:https://confluence.atlassian.com/bitbucket/manage-webhooks-735643732.html - squaretastic
1个回答

2
如果您希望将服务器与所在分支的最新更改同步,可以按照以下步骤操作。当提交或合并请求关闭时,“Git pull”将会被执行。
请将以下代码添加到您的代码库中以触发操作:
// This function serves as the Payload URL for Github's webhook
// https://github.com/reponame/projectname/settings/hooks/
public function post_receive() 
{
    // copied from 'https://gist.github.com/1809044'
    $commands = array(
        'hostname',
        'echo $PWD',
        'whoami',
        'git fetch',
        'branch=$(git symbolic-ref -q --short HEAD)',
        'git reset --hard origin/$branch',
        'git pull',
        'git status'
    );

    // Run the commands for output
    $output = '';
    foreach($commands AS $command){
        // Run it
        $tmp = shell_exec($command);
        // Output
        $output .= "<span style=\"color: #6BE234;\">\$</span> <span style=\"color: #729FCF;\">{$command}\n</span>";
        $output .= htmlentities(trim($tmp)) . PHP_EOL.'<br/>';
    }

    print_r($output);

}

转到Github.com的Webhooks和服务,https://github.com/reponame/projectname/settings/hooks

点击“添加Webhook”

在“Payload URL”中,指定您想要启用自动 'git pull' 的服务器的URL,例如,

"https://yourserver.com/github/post_receive"。我们需要确保URL是https(安全的),否则我们将获得302

或者,点击“禁用SSL验证”

对于“您想触发此Webhook的哪些事件?”,选择“让我选择个别事件。”并选择“Pull Request”和“Push”

点击“添加Webhook”

在“最近的投递”中,验证您是否收到正确的响应并且它是绿色的。

Webhook Post请求会在您的服务器上触发以下命令,

在Apache服务器上设置www-data组权限

sudo apt-get install members

members www-data

adduser username www-data

chown www-data:www-data -R username

cp -R /home/username/.ssh /var/www/.ssh

chown www-data:www-data -R /var/www/.ssh

ls -la /var/www/.ssh

sudo chmod g+w .git -R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接