Skip navigation

UPDATE: There is a new version of this effort.

I needed to modify a local git servers web interface to indicate which revision a remote repo was currently on. This is what happened:

The PHP:

// make sure we have what we need
if( $_SERVER['REQUEST_METHOD'] == 'GET' && !empty($_GET['path'])){

    // our return array
    $return = array();

    // build the git command with the supplied path
    $gitCmd = 'git --git-dir='. $_GET['path'] . '.git --work-tree=' . $_GET['path'] . ' rev-parse HEAD';

    // configure the connection using the local keys
    $connection = ssh2_connect('host.domain.tld', 22, array('hostkey' => 'ssh-rsa'));

    // attempt to authenticate
    if( ssh2_auth_pubkey_file($connection, 'ssh_user', '/path/to/id_rsa.pub', '/path/to/id_rsa') ){

	// capture the return stream, blocking is set to ensure that we have data before we try to read from the stream
	$stream = ssh2_exec($connection, $gitCmd);
	stream_set_blocking($stream, true);

	// $result is the current head revision
	$result = stream_get_contents($stream);

	// make sure we have something and it's not FALSE
	if(!empty($result)){
	    $return['head'] = $result;
	}else{
	    $return['error'] = 'Error retrieving HEAD of remote repository.';
	}
    }else{
	// fail
	$return['error'] = 'SSH Authentication Failed.';
    }

    // send the data back as a json obj
    echo json_encode($return);
}

// done
die();

And the JS:

// update this object with the repos and their paths
var repoObject = {
    'repoName.git' : {
        'path' : '/path/to/local/repo/'
    }
};
// this is our success function
function querySuccess(data){
    // if we have errors, display them
    if( 'error' in data ){
	$('#query_error').text(data.error);
    }else{
        $('.' + data.head).addClass('currentHead');
    }
}
// we run this on document ready for great justice
$(function(){
    var repoTitle = $('#project_name').val();
    // only check rev if we are within a recognized repo
    if (  repoTitle in repoObject) {
        var rData = {
            'path' : repoObject[repoTitle].path
	    };
        $.ajax({
            dataType: 'json',
            url: '/get_head.php',
            data: rData,
            success: function(data){
	        querySuccess(data);
            },
            beforeSend: function(){
                $('#busy_anim').css('display','inline-block');
            },
            complete: function(){
                $('#busy_anim').css('display','none');
            }
        });
    }
});

You are going to want to ensure that you protect the keys you generate to do this, in this example they are in the web directory only protected by Apache.

Leave a Reply