Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Git Wrapper Laravel Package

symplify/git-wrapper

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require symplify/git-wrapper --dev
    

    (Note: Marked as --dev since the package is archived but may still be useful for legacy projects.)

  2. Basic Usage Initialize the wrapper in a service or helper class:

    use Symplify\GitWrapper\GitWrapper;
    
    $gitWrapper = new GitWrapper();
    
  3. First Use Case Check git status in a Laravel command:

    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    
    class GitStatusCommand extends Command
    {
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $gitWrapper = new GitWrapper();
            $status = $gitWrapper->execute('status', '--porcelain');
    
            $output->writeln('Git status:');
            $output->writeln($status);
    
            return Command::SUCCESS;
        }
    }
    

Implementation Patterns

Common Workflows

  1. Running Git Commands Use execute() for raw output or executeSilently() for suppressed output:

    $log = $gitWrapper->execute('log', '--oneline', '-n', 5);
    $gitWrapper->executeSilently('branch', '-D', 'old-branch');
    
  2. Integration with Laravel Artisan Wrap git operations in Artisan commands for CLI tooling:

    $gitWrapper->execute('pull', 'origin', 'main');
    $gitWrapper->execute('push', 'origin', 'feature-branch');
    
  3. Git Hooks & Automation Use in Laravel events (e.g., Illuminate\Foundation\Bootstrap\LoadConfiguration) to trigger git actions:

    $gitWrapper->execute('add', '.');
    $gitWrapper->execute('commit', '-m', 'Auto-commit via Laravel');
    
  4. Dependency Injection Bind the wrapper in Laravel’s service container for reusable access:

    $this->app->singleton(GitWrapper::class, function ($app) {
        return new GitWrapper();
    });
    
  5. Git Operations in Controllers (Caution: Avoid in production controllers; use services instead.)

    $gitWrapper->execute('fetch', '--all');
    

Integration Tips

  • Error Handling: Wrap calls in try-catch to handle git failures gracefully:
    try {
        $gitWrapper->execute('checkout', 'nonexistent-branch');
    } catch (\Symplify\GitWrapper\Exception\GitException $e) {
        Log::error('Git error: ' . $e->getMessage());
    }
    
  • Environment Awareness: Check for .git directory existence before operations:
    if (!file_exists('.git')) {
        throw new \RuntimeException('Not a git repository');
    }
    
  • Laravel Mix/Valet: Useful for local development workflows (e.g., auto-committing asset changes).

Gotchas and Tips

Pitfalls

  1. Archived Package

  2. Git Command Injection

    • Risk: Unsanitized input in execute() can lead to command injection.
    • Fix: Validate all arguments or use whitelisted commands:
      $allowedCommands = ['status', 'log', 'branch'];
      if (!in_array($command, $allowedCommands)) {
          throw new \InvalidArgumentException('Command not allowed');
      }
      
  3. Output Parsing

    • Raw output may require manual parsing (e.g., git log --pretty=format:"%h").
    • Use execute() + preg_match() for structured data:
      preg_match('/^([a-f0-9]{7}) .*/m', $logOutput, $matches);
      
  4. Performance

    • Avoid running git commands in loops or high-traffic routes.
    • Cache results where possible (e.g., git status in a middleware).
  5. Windows Line Endings

    • Git commands may fail on Windows due to path/line-ending issues.
    • Use str_replace("\r\n", "\n", $output) to normalize.

Debugging

  • Verbose Output: Enable debug mode for troubleshooting:
    $gitWrapper->setDebug(true);
    
  • Check Return Codes: Inspect $gitWrapper->getExitCode() after execution.
  • Log Commands: Log executed commands for auditing:
    Log::debug('Executing git command: ' . $gitWrapper->getLastCommand());
    

Extension Points

  1. Custom Git Commands Extend the wrapper for project-specific commands:

    class CustomGitWrapper extends GitWrapper
    {
        public function deploy()
        {
            $this->execute('add', '.');
            $this->execute('commit', '-m', 'Deploy');
            $this->execute('push', 'origin', 'main');
        }
    }
    
  2. GitHub/GitLab API Integration Combine with APIs for hybrid workflows (e.g., git-wrapper for local ops + API for remote).

  3. Laravel Events Trigger git actions on events (e.g., Illuminate\Queue\Events\JobProcessed):

    event(new GitCommitEvent('Auto-commit after job'));
    
  4. Testing Mock GitWrapper in PHPUnit:

    $mock = $this->createMock(GitWrapper::class);
    $mock->method('execute')->willReturn('mocked output');
    

Config Quirks

  • Git Path: Override the default git binary path:
    $gitWrapper = new GitWrapper('/custom/path/to/git');
    
  • Environment Variables: Use .env for sensitive git credentials (e.g., GIT_USER, GIT_TOKEN).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel