<commit_before># PHP Wrapper around the Git CLI

[![Build Status](https://img.shields.io/travis/Symplify/GitWrapper/master.svg?style=flat-square)](https://travis-ci.org/Symplify/GitWrapper)
[![Downloads](https://img.shields.io/packagist/dt/symplify/git-wrapper.svg?style=flat-square)](https://packagist.org/packages/symplify/git-wrapper)
[![Subscribe](https://img.shields.io/badge/subscribe-to--releases-green.svg?style=flat-square)](https://libraries.io/packagist/symplify%2Fgit-wrapper)

## Install

```json
composer require symplify/git-wrapper
```

## Usage

```php
use Symplify\GitWrapper\GitWrapper;

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.
$gitWorkingCopy = $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.
$gitWorkingCopy->add('test.txt');
$gitWorkingCopy->commit('Added the test.txt file as per the examples.');
$gitWorkingCopy->push();

// Render the output
echo $gitWorkingCopy->getOutput();

// 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:

```php
$gitWrapper->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: 

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

#### Logging

Use the logger listener with [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
compatible loggers such as [Monolog](https://github.com/Seldaek/monolog) to log commands that are executed.

```php
use Symplify\GitWrapper\Event\GitLoggerListener;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

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

$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.
```

## Event System

GitWrapper uses event system based on [Symfony\EventDispatcher](https://symfony.com/doc/current/components/event_dispatcher.html).

There are 4 events to hook on:

- `GitPrepareEvent` 
- `GitSuccessEvent`
- `GitErrorEvent`
- `GitOutputEvent`

To hook one on use their `::class` name, e.g. to get every success event create and register this subscriber:

```php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symplify\GitWrapper\Event\GitSuccessEvent;

final class MyEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            GitSuccessEvent::class => 'onSuccess',
        ];
    }
    
    public function onSuccess(GitSuccessEvent $gitSuccessEvent)
    {
        // do what you like to do
    }
}
```



### Prepared Subscribers

We have also few prepared special EventSubscibers for you:


**1. To stream output right away**, add `GitOutputStreamEventSubscriber` to your dispatcher:
 
```php
$this->eventDispatcher->addSubscriber(new GitOutputStreamEventSubscriber);
```

**2. To enabled logging** do the same with `GitLoggerEventSubscriber`:

```php
$this->eventDispatcher->addSubscriber(new GitLoggerEventSubscriber);
```


## 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. The following is an incomplete list of challenges that are often encountered when executing Git from 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.<commit_msg>[GitWrapper] Improve README.md<commit_after># PHP Wrapper around the Git CLI

[![Build Status](https://img.shields.io/travis/Symplify/GitWrapper/master.svg?style=flat-square)](https://travis-ci.org/Symplify/GitWrapper)
[![Downloads](https://img.shields.io/packagist/dt/symplify/git-wrapper.svg?style=flat-square)](https://packagist.org/packages/symplify/git-wrapper)
[![Subscribe](https://img.shields.io/badge/subscribe-to--releases-green.svg?style=flat-square)](https://libraries.io/packagist/symplify%2Fgit-wrapper)

## Install

```bash
composer require symplify/git-wrapper
```

## Usage

```php
use Symplify\GitWrapper\GitWrapper;

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.
$gitWorkingCopy = $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.
$gitWorkingCopy->add('test.txt');
$gitWorkingCopy->commit('Added the test.txt file as per the examples.');
$gitWorkingCopy->push();

// Render the output
echo $gitWorkingCopy->getOutput();

// 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:

```php
$gitWrapper->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:

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

### Logging

Use the logger listener with [PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
compatible loggers such as [Monolog](https://github.com/Seldaek/monolog) to log commands that are executed.

```php
use Symplify\GitWrapper\Event\GitLoggerListener;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

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

$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.
```

## Event System

GitWrapper uses event system based on [Symfony\EventDispatcher](https://symfony.com/doc/current/components/event_dispatcher.html).

There are 4 events to hook on:

- `GitPrepareEvent`
- `GitSuccessEvent`
- `GitErrorEvent`
- `GitOutputEvent`

To hook one on use their `::class` name, e.g. to get every success event create and register this subscriber:

```php
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symplify\GitWrapper\Event\GitSuccessEvent;

final class MyEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            GitSuccessEvent::class => 'onSuccess',
        ];
    }

    public function onSuccess(GitSuccessEvent $gitSuccessEvent)
    {
        // do what you like to do
    }
}
```

### Prepared Subscribers

We have also few prepared special EventSubscibers for you:

**1. To stream output right away**, add `GitOutputStreamEventSubscriber` to your dispatcher:

```php
$this->eventDispatcher->addSubscriber(new GitOutputStreamEventSubscriber);
```

**2. To enabled logging** do the same with `GitLoggerEventSubscriber`:

```php
$this->eventDispatcher->addSubscriber(new GitLoggerEventSubscriber);
```

## 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. The following is an incomplete list of challenges that are often encountered when executing Git from 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.
{'fraction_non_alphanumeric': 0.1250402835965195, 'fraction_numerical': 0.0017187667848318831, 'mean_word_length': 4.544967242406194, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 37, 'https://': 18, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3076685', 'n_tokens_mistral': 2865, 'n_tokens_neox': 2709, 'n_words': 897}