首頁  >  問答  >  主體

開源中國Git PUSH鉤子部署PHP程式

我的程式碼託管在開源中國得Git庫裡,想使用Git鉤子來實現程式的部署,寫了一個程式接受鉤子的post的數據,但是不能實現程式的部署。 。程式碼如下:

public function index(){
        $logger = new KLogger(LOG_PATH.'KLogger');

        $web_root_dir = APP_PATH;  // /var/www/site

        if(IS_POST){
            $payload = $_POST;
            $payload = json_decode($payload['hook']);
            $logger->info('data from git post...', $payload); 

            // if (!empty($payload['password'])){
                $command = "cd {$web_root_dir} && git pull";
                $logger->info('enter if .....');
                $result = exec($command);
                $logger->info('command execute result...'.$result); 

            // }
        }

    }

在程式裡記錄了日誌,能接收到post數據,但指令執行不成功,以下是log的內容:

[2015-05-05 2:07:34.114928] [INFO] data from git post...
    password: '123456'
    push_data: stdClass::__set_state(array(
         'before' => '7a563d4498371a8572a88ff22fb726ac7f8dd467',
         'after' => 'f24b208ddb520b1349fca6a5a0295db516b3982b',
         'ref' => 'refs/heads/master',
         'user_id' => 120469,
         'user_name' => '',
         'repository' => stdClass::__set_state(array(
             'name' => '',
             'url' => '',
             'description' => '',
             'homepage' => '',
        )),
         'commits' => array(
            0 => stdClass::__set_state(array(
                 'id' => 'f24b208ddb520b1349fca6a5a0295db516b3982b',
                 'message' => 'a',
                 'timestamp' => '2015-05-05T02:07:35+08:00',
                 'url' => 'http://git.oschina.net/commit/f24b208ddb520b1349fca6a5a0295db516b3982b',
                 'author' => stdClass::__set_state(array(
                     'name' => '',
                     'email' => '',
                )),
            )),
        ),
         'total_commits_count' => 1,
    ))
[2015-05-05 2:07:34.115142] [INFO] enter if .....
[2015-05-05 2:07:35.482580] [INFO] command execute result...
阿神阿神2697 天前746

全部回覆(3)我來回復

  • 漂亮男人

    漂亮男人2017-05-02 09:21:58

    http://blog.skyx.in/archives/158/

    可能是權限問題

    回覆
    0
  • 漂亮男人

    漂亮男人2017-05-02 09:21:58

    我一般不用鉤子,麻煩還維護,需要部署的地方執行這個腳本

    #! /bin/bash
    while true
    do
        git pull
        sleep 5
    done
    

    當然,如果你的程式還需要針對程式碼更新做一些其他操作,這個就不好用了.

    回覆
    0
  • ringa_lee

    ringa_lee2017-05-02 09:21:58

    貼自己寫的一個簡單的小腳本,配置一些資訊既可以實現題主功能,能夠簡單的記錄資訊到log。

    <?php
    /**
     * Class Main
     * @url https://git.oschina.net/edvard_hua2/PHP-WebHook-Script.git
     * @author Edward
     * @time 2015.08.23 08:13
     */
    
    /**
     * format var_dump
     * @param void $varVal 
     * @param str $varName 
     * @param bool $isExit 
     */
    function dump($varVal, $isExit = FALSE){
        ob_start();
        var_dump($varVal);
        $varVal = ob_get_clean();
        $varVal = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $varVal);
        echo '<pre>'.$varVal.'</pre>';
        $isExit && exit();
    }
    
    /**
     * @param str $msg
     */
    function writeLog($msg){
        date_default_timezone_set("Asia/Shanghai");
        file_put_contents('log.txt',"\r\n".date("h:i:sa").': '.$msg,FILE_APPEND|LOCK_EX);
    }
    
    /**
     * @see http://php.net/manual/en/function.proc-open.php
     */
    $descriptorspec = array(
       0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
       1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
       2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
    );
    
    $postData = json_decode($_POST['hook'],true);
    if($postData['password'] !== '##You Password##'){
        writeLog('un-authorization request:'.$_SERVER['HTTP_HOST']);
        die;
    }
    
    $username = '##You Username##';
    $password = '##You Password##';
    
    $cwd = '####';  //The initial working dir for the command. This must be an absolute directory path
    $projectSuffix = '##owner##/##project_name##.git';
    $branch = '##Branch Name##';
    
    $updateUrl = 'https://'.$username.':'.$password.'@git.oschina.net/'.$projectSuffix;
    $process = proc_open('git pull '.$updateUrl.' '.$branch,$descriptorspec,$pipes,$cwd,NULL);
    if(is_resource($process)){
        $output = stream_get_contents($pipes[1]);
        fclose($pipes[1]);
    }
    $return_value = proc_close($process);
    
    if($return_value == 0){
        writeLog('Command success: '.$postData['push_data']['after'].'\r\n'.$output);
    }else
        writeLog('Command faild.');
    
    ?>

    回覆
    0
  • 取消回覆