Git Auto-Pull Broken, Fix Found

At my work, we have a Git auto-pull script set up for development branches, so that whenever a developer pushes a commit, the development server will automatically pull in those changes.  Here is a basic example of that sort of script:

error_reporting(E_ALL);
 ignore_user_abort(true);

 function syscall ($cmd, $cwd) {
    $descriptorspec = array(
            1 => array('pipe', 'w') // stdout is a pipe that the child will write to
    );
    $resource = proc_open($cmd, $descriptorspec, $pipes, $cwd);
    if (is_resource($resource)) {
            $output = stream_get_contents($pipes[1]);
            fclose($pipes[1]);
            proc_close($resource);
            return $output;
    }
 }

// GitHub will hit us with POST (http://help.github.com/post-receive-hooks/)
if (!empty($_POST['payload'])) {
	
	// pull from origin
	$result = syscall('git pull 2>&1', getcwd());
 
	// send us the output
	mail('me@gmail.com', 'Git auto-pull', $result);
 	
}

However, sometime earlier this week, that started failing.  I added some debugging code to have it email me the result of syscall, but that was empty.

The Fix

The fix was as simple as adding the following line of code near the top:


putenv("HOME=".getcwd());

It was also useful to change the Git command like so, to have errors go to stdout so that they would also be included in the $result output:


$result = syscall('git pull origin master 2>&1', '/var/www/website/directory');

How I Investigated

First, I went to the command line and executed “sudo -u apache _git_pull.php”.  That gave the error, “Result: fatal: unable to access ‘/root/.config/git/config’: Permission denied.”  Doing a bit of Google searching, I found out that is because the HOME environment variable wasn’t set correctly for the Apache user.  So to correct this, I just added putenv(“HOME=”.getcwd()); to the top of the script.


Category(s): Code Snippets, Tools, Web Design
Tags: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *