• Stars
    star
    507
  • Rank 86,761 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 12 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A PHP wrapper around the Git command line utility.

PHP Wrapper around GIT

Total Downloads Latest Stable Version

Git Wrapper provides a readable API that abstracts challenges of executing Git commands from within a PHP process for you.

  • It's built upon the Symfony\Process to execute the Git command with cross-platform support and uses the best-in-breed techniques available to PHP.
  • This library also provides an SSH wrapper script and API method for developers to easily specify a private key other than default by using the technique from StackOverflow.
  • Finally, various commands are expected to be executed in the directory containing the working copy. The library handles this transparently so the developer doesn't have to think about it.

Install

composer require cpliakas/git-wrapper

Usage

use GitWrapper\GitWrapper;

// Initialize the library. If the path to the Git binary is not passed as 
// the first argument when instantiating GitWrapper, it is auto-discovered.
require_once __DIR__ . '/vendor/autoload.php';

$gitWrapper = new GitWrapper();

// Optionally specify a private key other than one of the defaults
$gitWrapper->setPrivateKey('/path/to/private/key');

// Clone a repo into `/path/to/working/copy`, get a working copy object
$git = $gitWrapper->cloneRepository('git://github.com/cpliakas/git-wrapper.git', '/path/to/working/copy');

// Create a file in the working copy
touch('/path/to/working/copy/text.txt');

// Add it, commit it, and push the change
$git->add('test.txt');
$git->commit('Added the test.txt file as per the examples.');
$git->push();

// Render the output for operation
echo $git->push();

// Stream output of subsequent Git commands in real time to STDOUT and STDERR.
$gitWrapper->streamOutput();

// Execute an arbitrary git command.
// The following is synonymous with `git config -l`
$gitWrapper->git('config -l');

All command methods adhere to the following paradigm:

$git->command($arg1, $arg2, ..., $options);

Replace command with the Git command being executed, e.g. checkout, push, etc. The $arg* parameters are a variable number of arguments as they would be passed to the Git command line tool. $options is an optional array of command line options in the following format:

$options = [
    'verbose' => true,   // Passes the "--verbose" flag.
    't' => 'my-branch',  // Passes the "-t my-branch" option.
];

Logging

Use the logger listener with PSR-3 compatible loggers such as Monolog to log commands that are executed.

<?php

use GitWrapper\EventSubscriber\GitLoggerEventSubscriber;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Log to a file named "git.log"
$logger = new Logger('git');
$logger->pushHandler(new StreamHandler('git.log', Logger::DEBUG));

// Instantiate the subscriber, add the logger to it, and register it.
$gitWrapper->addLoggerEventSubscriber(new GitLoggerEventSubscriber($logger));

$git = $gitWrapper->cloneRepository('git://github.com/cpliakas/git-wrapper.git', '/path/to/working/copy');

// The "git.log" file now has info about the command that was executed above.

Gotchas

There are a few "gotchas" that are out of scope for this library to solve but might prevent a successful implementation of running Git via PHP.

Missing HOME Environment Variable

Sometimes the HOME environment variable is not set in the Git process that is spawned by PHP. This will cause many Git operations to fail. It is advisable to set the HOME environment variable to a path outside of the document root that the web server has write access to. Note that this environment variable is only set for the process running Git and NOT the PHP process that is spawns it.

$gitWrapper->setEnvVar('HOME', '/path/to/a/private/writable/dir');

It is important that the storage is persistent as the ~/.gitconfig file will be written to this location. See the following "gotcha" for why this is important.

Missing Identity And Configurations

Many repositories require that a name and email address are specified. This data is set by running git config [name] [value] on the command line, and the configurations are usually stored in the ~/.gitconfig file. When executing Git via PHP, however, the process might have a different home directory than the user who normally runs git via the command line. Therefore no identity is sent to the repository, and it will likely throw an error.

// Set configuration options globally.
$gitWrapper->git('config --global user.name "User name"');
$gitWrapper->git('config --global user.email [email protected]');

// Set configuration options per repository.
$git->config('user.name', 'User name');
$git->config('user.email', '[email protected]');

Commits To Repositories With No Changes

Running git commit on a repository with no changes fails with exception. To prevent that, check changes like:

if ($git->hasChanges()) {
    $git->commit('Committed the changes.');
}

Permissions Of The GIT_SSH Wrapper Script

On checkout, the bin/git-ssh-wrapper.sh script should be executable. If it is not, git commands will fail if a non-default private key is specified.

$ chmod +x ./bin/git-ssh-wrapper.sh

Timeout

There is a default timeout of 60 seconds. This might cause "issues" when you use the clone feature of bigger projects or with slow internet.

$this->gitWrapper = new GitWrapper();
$this->gitWrapper->setTimeout(120);

More Repositories

1

aws-sam-golang-example

An example API and Worker written in Golang using the Amazon Serverless Application Model (AWS SAM)
Go
110
star
2

php-project-starter

A command line tool that allows developers to quickly create PHP applications that use common conventions and best-in-breed development tools.
PHP
75
star
3

jira-client

A PHP client for integrating with the JIRA issue & bug tracker software.
PHP
71
star
4

magento-client-php

A PHP client library that consumes Magento's REST and XMLRPC APIs
PHP
55
star
5

psolr

A simple PHP client for Apache Solr that is built on top of Guzzle and inspired by RSolr.
PHP
16
star
6

manifest-publisher

A command line tool that builds and publishes a herrera-io/php-phar-update manifest.json file
PHP
15
star
7

search-framework

A search framework that facilitates reusable code and concepts across search backend libraries.
PHP
13
star
8

dynamo-db-odm

A lightweight ODM for DynamoDB
PHP
10
star
9

drupal-distro

A command line tool that creates and manages Drupal distributions.
PHP
9
star
10

quickbase-sentiment-analysis

A sentiment analysis service for Quickbase
JavaScript
6
star
11

elasticsearch-engine

Provides an Elasticsearch engine to the Search Framework library by leveraging the Elastica project.
PHP
5
star
12

composer-manager-docs

Documentation for Drupal's Composer Manager module https://drupal.org/project/composer_manager
5
star
13

cliutil

Helper functions that simplify writing CLI tools with Cobra and Viper.
Go
4
star
14

simplesamlphp-composer

A Composer-compatible packages.json file for SimpleSAMLphp along with a stupid simple PHP script that generates the file.
PHP
4
star
15

doctrine-password

Adds a password type to Doctrine that hashes and compares passwords using the phpass library.
PHP
4
star
16

git-sync

Synchronizes Git repositories.
PHP
3
star
17

cgo-example

A simple CGO application for example purposes.
Go
3
star
18

silex-drupal-integration

Adds a Drupal authentication provider for Silex and a client library that communicates with Drupal via the Services module.
PHP
3
star
19

fastwalk

A copy of the fastwalk code inside of Go Tools with exported functions for use as a standalone library.
Go
2
star
20

feed-collection

Provides an RSS / Atom feed collection to the search framework library.
PHP
2
star
21

bigoven-php

A PHP client library for the BigOven API
PHP
2
star
22

solr-search-engine

Provides a Solr search server to the Search Framework library by leveraging the Solarium project.
PHP
2
star
23

scanner

A Go package that provides a recursive file scanner that is useful for efficiently processing large and relatively static datasets.
Go
2
star
24

finance

A Golang library and command line tool that executes finance calculations and operations.
Go
2
star
25

fileinfo

A go package that extracts and stores basic metadata about a file.
Go
1
star
26

quickbase-pipelines-auth

1
star
27

solarium-statsjsp

A stats.jsp request handler for Solarium.
PHP
1
star
28

quickbase-action-test

1
star
29

wh-test

Github Webhooks testing.
Go
1
star
30

Acquia-Cloud-Utilities

Deprecated: See https://github.com/acquia/acquia-sdk-php
PHP
1
star
31

goreleaser-test

Test of goreleaser that serves as a working example.
Makefile
1
star
32

quickbase-deploy-action

Shell
1
star
33

nagiostatus

PHP parser library for the Nagios status.dat file.
PHP
1
star
34

solarium-system

An admin/system request handler for Solarium.
PHP
1
star
35

quickbase-test-action

Shell
1
star
36

quickbase-textmate

A command line tool that automates creation to TextMate grammar for use with VS Code
Go
1
star
37

git-collection

Provides collection of Git logs and diffs to the search framework library.
PHP
1
star
38

quickbase-do-query

A command line tool that gets records from a Quick Base table.
Go
1
star