Weave Code
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 State Laravel Package

sebastian/git-state

PHP library to describe the state of a Git checkout. Retrieve origin URL, current branch and commit hash, and determine whether the working directory is clean or get a git-style status output. Useful for build/test tooling and CI metadata.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require sebastian/git-state
    

    For development-only usage (e.g., testing):

    composer require --dev sebastian/git-state
    
  2. First Use Case: Check Git State in a Laravel Artisan Command Create a new Artisan command to inspect Git state:

    php artisan make:command GitStatus
    

    Edit the generated file (app/Console/Commands/GitStatus.php):

    use SebastianBergmann\GitState\Builder;
    use Illuminate\Console\Command;
    
    class GitStatus extends Command
    {
        protected $signature = 'git:status';
        protected $description = 'Display the current Git repository state';
    
        public function handle()
        {
            $builder = new Builder();
            $state = $builder->build();
    
            if ($state === false) {
                $this->error('Not a Git repository or missing origin.');
                return 1;
            }
    
            $this->info("Branch: {$state->branch()}");
            $this->info("Commit: {$state->commit()}");
            $this->info("Origin: {$state->originUrl()}");
            $this->info($state->isClean() ? 'Working directory is clean' : 'Working directory has changes');
            if (!$state->isClean()) {
                $this->line('Status:');
                $this->line($state->status());
            }
        }
    }
    

    Run the command:

    php artisan git:status
    
  3. Where to Look First

    • Builder Class: The entry point for creating a GitState object.
      $builder = new Builder();
      $state = $builder->build();
      
    • GitState Methods: Key methods to inspect:
      • $state->branch(): Current branch name.
      • $state->commit(): Current commit hash.
      • $state->originUrl(): Remote origin URL.
      • $state->isClean(): Boolean indicating if the working directory is clean.
      • $state->status(): String with Git status output.
    • Error Handling: The build() method returns false if not in a Git repo or missing an origin.

Implementation Patterns

Usage Patterns in Laravel

  1. Service Layer Integration Encapsulate Git state logic in a service class for reusability:

    namespace App\Services;
    
    use SebastianBergmann\GitState\Builder;
    
    class GitStateService
    {
        public function getState()
        {
            $builder = new Builder();
            $state = $builder->build();
    
            if ($state === false) {
                return null;
            }
    
            return [
                'branch' => $state->branch(),
                'commit' => $state->commit(),
                'origin' => $state->originUrl(),
                'is_clean' => $state->isClean(),
                'status' => $state->status(),
            ];
        }
    }
    

    Use the service in controllers or other services:

    use App\Services\GitStateService;
    
    class DeploymentController extends Controller
    {
        public function check(GitStateService $gitState)
        {
            $state = $gitState->getState();
            if (!$state || !$state['is_clean']) {
                abort(500, 'Git repository is not in a valid state for deployment.');
            }
            // Proceed with deployment
        }
    }
    
  2. Middleware for Git State Validation Validate Git state before critical operations (e.g., deployments):

    namespace App\Http\Middleware;
    
    use Closure;
    use App\Services\GitStateService;
    
    class ValidateGitState
    {
        public function __construct(protected GitStateService $gitState)
        {
        }
    
        public function handle($request, Closure $next)
        {
            $state = $this->gitState->getState();
            if (!$state || !$state['is_clean']) {
                abort(403, 'Git repository must be clean for this operation.');
            }
            return $next($request);
        }
    }
    

    Register the middleware in app/Http/Kernel.php:

    protected $routeMiddleware = [
        // ...
        'validate.git' => \App\Http\Middleware\ValidateGitState::class,
    ];
    

    Use in routes:

    Route::middleware(['validate.git'])->group(function () {
        Route::post('/deploy', [DeploymentController::class, 'deploy']);
    });
    
  3. Artisan Commands for Git Operations Create custom commands for Git-related tasks:

    php artisan make:command GitInfo
    

    Example command to log Git state:

    use SebastianBergmann\GitState\Builder;
    use Illuminate\Console\Command;
    
    class GitInfo extends Command
    {
        protected $signature = 'git:info';
        protected $description = 'Log Git repository information';
    
        public function handle()
        {
            $builder = new Builder();
            $state = $builder->build();
    
            if ($state === false) {
                $this->error('Not a Git repository or missing origin.');
                return 1;
            }
    
            \Log::info('Git State', [
                'branch' => $state->branch(),
                'commit' => $state->commit(),
                'origin' => $state->originUrl(),
                'is_clean' => $state->isClean(),
            ]);
    
            $this->info('Git information logged successfully.');
        }
    }
    
  4. Event Listeners for Git State Changes Trigger actions based on Git state (e.g., notify team if working directory is dirty):

    namespace App\Listeners;
    
    use App\Services\GitStateService;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class GitStateListener
    {
        public function __construct(protected GitStateService $gitState)
        {
        }
    
        public function handle()
        {
            $state = $this->gitState->getState();
            if ($state && !$state['is_clean']) {
                // Notify team or log warning
                \Log::warning('Dirty working directory detected', [
                    'status' => $state['status'],
                ]);
            }
        }
    }
    

    Register the listener in EventServiceProvider:

    protected $listen = [
        'app.started' => [
            GitStateListener::class,
        ],
    ];
    
  5. Caching Git State for Performance Cache Git state to avoid repeated Git command executions:

    namespace App\Services;
    
    use SebastianBergmann\GitState\Builder;
    use Illuminate\Support\Facades\Cache;
    
    class GitStateService
    {
        public function getState()
        {
            return Cache::remember('git.state', now()->addMinutes(5), function () {
                $builder = new Builder();
                $state = $builder->build();
                return $state ? [
                    'branch' => $state->branch(),
                    'commit' => $state->commit(),
                    'origin' => $state->originUrl(),
                    'is_clean' => $state->isClean(),
                    'status' => $state->status(),
                ] : null;
            });
        }
    }
    

Gotchas and Tips

Pitfalls and Debugging

  1. Non-Git Repository Handling

    • The build() method returns false if not in a Git repository or if the origin is missing.
    • Tip: Always check for false and handle gracefully:
      $state = $builder->build();
      if ($state === false) {
          throw new \RuntimeException('Not a Git repository or missing origin.');
      }
      
    • Debugging: Verify Git is installed and the directory is a Git repo:
      git --version
      git rev-parse --is-inside-work-tree
      
  2. Git Command Failures

    • If Git commands fail (e.g., due to permissions or missing config), the package may throw exceptions or return unexpected results.
    • Tip: Wrap the builder in a try-catch block:
      try {
          $state = $builder->build();
      } catch (\Exception $e) {
          \Log::error('Git state error: ' . $e->getMessage());
          return null;
      }
      
  3. Working Directory Changes

    • The isClean() method checks for uncommitted changes. False positives can occur if Git ignores files or if the working directory is not as expected.
    • Tip: Use status() to inspect changes:
      if (!$state->isClean()) {
          $this->line('Uncommitted changes:');
          $this->line($state->status());
      }
      
  4. Remote URL Issues

    • The originUrl() method may return unexpected values if the remote is misconfigured or named differently (e.g., upstream instead of origin).
    • Tip: Validate the remote name:
      $originUrl = $state->originUrl();
      if (empty($originUrl)) {
          // Try fetching from other remotes or handle as
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope