A PHP wrapper around the Git command line utility.

Overview

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:

'my-branch', // Passes the "-t my-branch" option. ]; ">
$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.

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. ">


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.

git('config --global user.email [email protected]'); // Set configuration options per repository. $git->config('user.name', 'User name'); $git->config('user.email', '[email protected]'); ">
// 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);
Comments
  • Add a branch alias

    Add a branch alias

    You should add a 2.x branch alias.

    Currently, if I do this: "cpliakas/git-wrapper": "^2.0,>2.0.0"

    I get:

      Problem 1
        - The requested package cpliakas/git-wrapper ^2.0,>2.0.0 exists as cpliakas/git-wrapper[1.0.0, 1.0.0-RC1, 1.0.0beta1, 1.0.0beta2, 1.0.0beta3, 1.0.0beta4, 1.0.0beta5, 1.0.0beta6, 1.0.0beta7, 1.0.1, 1.0.2, 1.0.3, 1.1.0, 1.1.1, 1.1.2, 1.2.0, 1.3.0, 1.4.0, 1.4.1, 1.5.0, 1.6.0, 1.6.1, 1.7.0, dev-master, v2.0.0] but these are rejected by your constraint.
    
    opened by soullivaneuh 21
  • Allow the Symfony 3.4 event dispatcher

    Allow the Symfony 3.4 event dispatcher

    I would like to use this with Drupal 8 which still requires the Symfony 3.4 event dispatcher. There is hardly any difference between the 3.4 and 4.x versions of the event dispatcher, so there should be little harm in allowing this version.

    opened by pfrenssen 13
  • Looking for maintainer

    Looking for maintainer

    @cpliakas Hey, are you still in PHP? There is no activity for over 1,5 years. This package is still used though with some critical issues like disability for Symfony 4.

    I'm thinking of forking it under @Symplify to prevent its pass out.

    opened by TomasVotruba 13
  • Update argument order for dispatch method for symfony compatibility

    Update argument order for dispatch method for symfony compatibility

    Symfony 4.3 compatibility patch.

    This will address #175 compatibility but does not provide a fix for the static analysis argument count problem. I am not totally sure how to fix that.

    opened by valeryan 12
  • Host authenticity interaction on SSH clone

    Host authenticity interaction on SSH clone

    On a fresh new container, with the following piece of code to do a SSH clone:

    use GitWrapper\GitWrapper;
    
    require_once 'vendor/autoload.php';
    
    $wrapper = new GitWrapper();
    
    $git = $wrapper->cloneRepository('[email protected]:cpliakas/git-wrapper.git', 'git-test');
    
    sullivan@7e1b7c24a5d3:/code$ php test.php 
    The authenticity of host 'github.com (192.30.253.113)' can't be established.
    RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
    Are you sure you want to continue connecting (yes/no)? 
    

    IMHO, it should be non-interactive by default.

    opened by soullivaneuh 12
  • GitProcess Throws Invalid Exception / Exit Code 1

    GitProcess Throws Invalid Exception / Exit Code 1

    I updated via composer to 1.2.0 today, and started having a GitException thrown:

    GitWrapper\GitException - - Line[87] in file C:\inetpub\Intranet_Local\vendor\cpliakas\git-wrapper\src\GitWrapper\GitProcess.php

    The reason for this is that this Git command is returning an exit code of 1 (or that is what GitWrapper is capturing.)

    cmd /V:ON /E:ON /C "(c:^\Git^\cmd^\git.EXE rev-parse --abbrev-ref HEAD)" 1>C:\Windows\Temp\sf_5EA1.tmp 2>C:\Windows\Temp\sf_5EA2.tmp

    However, I've verified that the command is working (the correct branch is being determined), however, the exception is being thrown due to the exit code anyway.

    I reverted to 1.1.2 and the problem still exists. I've tested this on 2 different machines.

    bug 
    opened by laurinkeithdavis 12
  • raw git commands are failing with git exception

    raw git commands are failing with git exception

    After updating to the latest version of git wrapper any raw git commands I attempt are failing.

    For example:

    $git = $this->gitWrapper->workingCopy($release);
    $branch = $git->getBranches()->head();
    $this->gitWrapper->git('push --set-upstream origin ' . $branch, $release);
    

    I am sure there is a command to set the upstream but I had implemented this manually and after updating it now fails.

    opened by valeryan 11
  • Fix a bug on windows

    Fix a bug on windows

    On windows, git binary paths are usually at: "C:\Program Files...".

    When I use:

    GitWorkingCopy::getStatus();
    

    It cause an error: image

    I found getStatus() use GitWrapper::git to run a raw command, so I changed it to use GitWorkingCopy::run firstly, but GitWrapper::git is still not working if git binary path including spaces.

    I reviewed the code of command line formating, found a bug of concat gitBinary and gitCommandLine, and it's now fixed.

    My English is not professional, but I'm trying my best. Thanks.

    opened by wi1dcard 11
  • Add some CS linters and fixers

    Add some CS linters and fixers

    We should setup some tools to maintain a certain coding style quality.

    PHP-CS-Fixer and maybe Yamllint would be a good start.

    We may a both CLI and SAAS service support with the tool I made: https://flintci.io

    Would you like me to setup it on a PR and make a try?

    Regards.

    EDIT: I didn't see you have this: https://github.com/cpliakas/git-wrapper/blob/master/easy-coding-standard.neon

    I don't know if this can be complementary.

    opened by soullivaneuh 11
  • GitWrapper\GitException - fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.

    GitWrapper\GitException - fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.

    From time to time, I get this:

    GitWrapper\GitException - fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git [...] -- [...]' - Line[511] in file C:\inetpub\Intranet_Local\vendor\cpliakas\git-wrapper\src\GitWrapper\GitWrapper.php

    0 C:\inetpub\Intranet_Local\vendor\cpliakas\git-wrapper\src\GitWrapper\GitWrapper.php 443 run [object] GitWrapper\GitCommand 1 C:\inetpub\Intranet_Local\library\classes\Config.php 38 git rev-parse --abbrev-ref HEAD 2 C:\inetpub\Intranet_Local\library\classes\Menu.php 24 Config::defineBRANCH 3 C:\inetpub\Intranet_Local\library\classes\FrameworkLink.php 28 Menu::getJS 4 C:\inetpub\Intranet_Local\library\classes\Common.php 1602 FrameworkLink::loadMenu 5 C:\inetpub\Intranet_Local\library\classes\apps\AuthGrid.php 51 Common::Head form calendar,scriptaculous,tiagra_menu,window,auth_grid 6 C:\inetpub\Intranet_Local\auth_grid.php 5 Apps_AuthGrid::Init

    bug 
    opened by laurinkeithdavis 11
  • nette/utils should be required

    nette/utils should be required

    Currently the package is in require-dev but is used in primary source code: https://github.com/cpliakas/git-wrapper/blob/master/src/GitBranches.php#L9

    opened by samdark 9
  • Transfer repository?

    Transfer repository?

    Hi @TomasVotruba!

    I hope all is well with you, and it has been great to watch the progress of this tool from the sidelines. Nothing burning on my side, and happy to keep the repo as-is. I was wondering it it would make sense to either transfer this repository to your account (or some other approach) that would give you more control over the repo and supporting toolchain. I just wanted to raise the question.

    question 
    opened by cpliakas 16
Releases(v2.0.0)
  • v2.0.0(Dec 31, 2017)

    Package is now alive and kicking thanks to @cpliakas and @TomasVotruba, who agreed maintain this repository.

    This release now requires as minimum:

    • PHP 7.1
    • Symfony 4

    See CHANGELOG.md for more information.

    Source code(tar.gz)
    Source code(zip)
Owner
Chris Pliakas
Chris Pliakas
m4b-tool is a command line utility to merge, split and chapterize audiobook files such as mp3, ogg, flac, m4a or m4b

m4b-tool m4b-tool is a is a wrapper for ffmpeg and mp4v2 to merge, split or and manipulate audiobook files with chapters. Although m4b-tool is designe

Andreas 798 Jan 8, 2023
A compact command line utility for checking YAML file syntax

A compact command line utility for checking YAML file syntax. Uses the parsing facility of the Symfony Yaml Component.

John Fitzpatrick 12 Oct 25, 2022
Utility that helps you switch git configurations with ease.

git-profile Utility that helps you switch git configurations with ease Preface It is possible that you have multiple git configurations. For example:

Zeeshan Ahmad 240 Jul 18, 2022
A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!

CLIFramework CLIFramework is a command-line application framework, for building flexiable, simple command-line applications. Commands and Subcommands

Yo-An Lin 428 Dec 13, 2022
Lovely PHP wrapper for using the command-line

ShellWrap What is it? It's a beautiful way to use powerful Linux/Unix tools in PHP. Easily and logically pipe commands together, capture errors as PHP

James Hall 745 Dec 30, 2022
PhpGit - A Git wrapper for PHP 7.1+

PhpGit PhpGit - A Git wrapper for PHP 7.1+ The project is forked from https://github.com/kzykhys/PHPGit Requirements PHP 7.1+ Git Installation Update

PHPPkg 9 Nov 1, 2022
Thin Wrapper around rbenv for PHP version managment

phpenv ![Gitter](https://badges.gitter.im/Join Chat.svg) Sets up a separate rbenv environment for PHP man page SYNOPSIS phpenv-install.sh UPDATE=yes p

Christoph Hochstrasser 571 Dec 29, 2022
A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface

PHP WkHtmlToPdf PHP WkHtmlToPdf provides a simple and clean interface to ease PDF and image creation with wkhtmltopdf. The wkhtmltopdf and - optionall

Michael Härtl 1.5k Dec 25, 2022
A PHP wrapper around the OpenSSL extension that provides a user-friendly interface for dealing with OpenSSL.

php-openssl-proxy About A PHP wrapper around the OpenSSL extension that provides a user-friendly interface for dealing with OpenSSL. What's up with th

Adão Pedro 4 Mar 5, 2022
An object oriented wrapper around PHP's built-in server.

Statix Server Requirements PHP 8 minumum Installation composer require statix/server Basic Usage To get started, ensure the vendor autoload script is

Statix PHP 113 Dec 27, 2022
A PHP wrapper around Libreoffice for converting documents from one format to another.

Document Converter A PHP wrapper around Libreoffice for converting documents from one format to another. For example: Microsoft Word to PDF OpenOffice

Lukas White 0 Jul 28, 2022
A simple wrapper around vlucas' PHP dotenv library for Kirby CMS.

kirby-phpdotenv A simple wrapper around vlucas' PHP dotenv library for Kirby CMS. Why? I've been using .env in my Kirby projects for a while, but I go

Steve Jamesson 5 Feb 6, 2020
Laravel wrapper around OAuth 1 & OAuth 2 libraries.

Introduction Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub, GitL

The Laravel Framework 5.2k Dec 27, 2022
A developer-friendly wrapper around execution of shell commands.

ptlis/shell-command A developer-friendly wrapper around execution of shell commands. There were several goals that inspired the creation of this packa

brian ridley 18 Dec 31, 2022
WordPlate is a wrapper around WordPress. It makes developers life easier. It is just like building any other WordPress website with themes and plugins. Just with sprinkles on top.

WordPlate is simply a wrapper around WordPress. It makes developers life easier. It is just like building any other WordPress website with themes and plugins. Just with sprinkles on top.

WordPlate 1.7k Dec 24, 2022
An elegant wrapper around Google Vision API

STILL UNDER DEVELOPMENT - DO NOT USE IN PRODUCTION Requires PHP 8.0+ For feedback, please contact me. This package provides an elegant wrapper around

Ahmad Mayahi 24 Nov 20, 2022
A wrapper around Spatie’s Browsershot for managing social share images (OGP, Twitter etc.)

Very short description of the package This package allows you to create dynamic social sharing images in your Laravel apps. It uses Spatie’s Browsersh

Richard Le Poidevin 4 Dec 25, 2021
This is a simple Wrapper around the ZipArchive methods with some handy functions

Note I haven't updated this package in a long time except merging PRs. The last time I was using this package was with PHP5. I archived the repository

Nils Plaschke 845 Dec 13, 2022
Simple wrapper package around MPDF's setProtection method that allows you to set password on PDF files

Laravel PDF Protect (fork) Simple wrapper package around MPDF's setProtection method that allows you to set password on PDF files. Installation You ca

Raphael Planer 2 Jan 23, 2022
This is a simple Wrapper around the ZipArchive methods with some handy functions

Note I haven't updated this package in a long time except merging PRs. The last time I was using this package was with PHP5. I archived the repository

Nils Plaschke 836 Jan 26, 2022