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

Robo Git Laravel Package

sweetchuck/robo-git

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation: Require the package via Composer:
    composer require --dev sweetchuck/robo-git
    
  2. Usage: Add the GitTaskLoader trait to your RoboFile.php:
    use Sweetchuck\Robo\Git\GitTaskLoader;
    
    class RoboFile extends \Robo\Tasks
    {
        use GitTaskLoader;
    }
    
  3. First Use Case: List branches in the current directory:
    public function gitBranches()
    {
        return $this->taskGitBranchList()->run();
    }
    
    Run with:
    vendor/bin/robo git:branches
    

Implementation Patterns

Common Workflows

  1. Data-Driven Pipelines: Use State\Data to chain tasks. Example: Fetch branch info, then filter branches:

    public function filterBranches()
    {
        return $this->collectionBuilder()
            ->addTask($this->taskGitBranchList())
            ->addCode(function (\Robo\State\Data $data) {
                $branches = array_filter($data['gitBranches'], function ($branch) {
                    return strpos($branch['refName.short'], 'feature/') === 0;
                });
                $this->output()->writeln('Filtered branches: ' . implode(', ', array_keys($branches)));
            });
    }
    
  2. Conditional Logic: Use parsed Git data to drive workflows. Example: Check if a branch exists:

    public function checkBranchExists(string $branchName)
    {
        return $this->collectionBuilder()
            ->addTask($this->taskGitBranchList())
            ->addCode(function (\Robo\State\Data $data) use ($branchName) {
                $exists = isset($data['gitBranches'][$branchName]);
                $this->output()->writeln($branchName . ' exists: ' . ($exists ? 'Yes' : 'No'));
                return $exists ? 0 : 1;
            });
    }
    
  3. Directory-Specific Operations: Set workingDirectory for repo-agnostic tasks:

    public function listFilesInRepo(string $repoPath)
    {
        return $this->taskGitListFiles()
            ->setPaths(['*.php'])
            ->setWorkingDirectory($repoPath);
    }
    
  4. Configuration Integration: Fetch Git config dynamically:

    public function getGitConfig(string $key)
    {
        return $this->taskGitConfigGet()->setName($key);
    }
    

Integration Tips

  • Laravel Artisan: Extend Laravel’s Artisan with custom Git tasks:
    // app/Console/Kernel.php
    protected $commands = [
        \App\Console\Commands\GitBranchCommand::class,
    ];
    
  • CI/CD Pipelines: Use parsed Git data (e.g., gitCurrentBranch) to trigger workflows:
    public function deployIfMainBranch()
    {
        return $this->collectionBuilder()
            ->addTask($this->taskGitCurrentBranch())
            ->addCode(function (\Robo\State\Data $data) {
                if ($data['gitCurrentBranch.short'] === 'main') {
                    $this->taskExec('php artisan deploy')->run();
                }
            });
    }
    

Gotchas and Tips

Pitfalls

  1. Data Key Confusion:

    • taskGitBranchList() stores results in $data['gitBranches'], not $data['branches'].
    • taskGitListFiles() uses $data['files'] with ListFilesItem objects (not plain arrays).
  2. Working Directory:

    • Forgetting setWorkingDirectory() defaults to the current directory, which may not be the repo root. Always specify explicitly for clarity:
      ->setWorkingDirectory(base_path('../'))
      
  3. Error Handling:

    • Git commands may fail silently. Validate $data keys before use:
      if (!isset($data['gitCurrentBranch'])) {
          $this->output()->writeln('Git operation failed!');
          return 1;
      }
      
  4. Undocumented Options:

    • Some tasks (e.g., taskGitListFiles) support Git’s full option set, but not all are documented in the README. Refer to git --help for advanced flags.

Debugging

  • Inspect Raw Output: Use taskExec() alongside robo-git tasks to debug raw Git output:
    $this->taskExec('git branch --all')->run();
    
  • State Data Dumping: Dump the entire $data object to inspect available keys:
    ->addCode(function (\Robo\State\Data $data) {
        $this->output()->writeln(print_r($data->getAll(), true));
    })
    

Tips

  1. Extend for Custom Logic: Override task methods to add custom parsing. Example: Extract commit hashes from git log:

    use Sweetchuck\Robo\Git\GitTaskLoader;
    
    class CustomRoboFile extends \Robo\Tasks
    {
        use GitTaskLoader;
    
        public function taskGitLog()
        {
            return $this->taskExec('git log --pretty=format:"%H"')
                ->setOutputBuffering(true);
        }
    }
    
  2. Performance: Cache frequent operations (e.g., branch lists) in State\Data:

    ->addCode(function (\Robo\State\Data $data) {
        if (!$data->has('cachedBranches')) {
            $data->set('cachedBranches', $this->taskGitBranchList()->run());
        }
    })
    
  3. Type Safety: Use PHP 8’s array_key_exists() or isset() with strict checks for ListFilesItem objects:

    foreach ($data['files'] as $file) {
        if ($file instanceof \Sweetchuck\Robo\Git\ListFilesItem) {
            $this->output()->writeln($file->fileName);
        }
    }
    
  4. Configuration: Store repetitive Git configs (e.g., user.email) in robo.yml:

    git:
      user:
        email: "dev@example.com"
    

    Then fetch dynamically:

    $this->taskGitConfigGet()->setName('user.email');
    
  5. Testing: Mock Git commands in tests using taskExec() with fixed outputs:

    $this->taskExec('git branch')->expects($this->once())->run();
    

```markdown
## Extension Points
1. **Custom Tasks**:
   Extend the package by creating wrapper tasks for unsupported Git commands. Example:
   ```php
   public function taskGitDiffStats()
   {
       return $this->taskExec('git diff --stat')
           ->setOutputBuffering(true);
   }
  1. Data Parsers: Override the default output parsers (e.g., for taskGitBranchList) to customize data structure:

    public function taskGitBranchList()
    {
        $task = parent::taskGitBranchList();
        $task->setParser(function ($output) {
            // Custom parsing logic
            return ['custom' => 'data'];
        });
        return $task;
    }
    
  2. Integration with Laravel: Bind Robo tasks to Laravel’s service container for dependency injection:

    $this->app->bind(\Sweetchuck\Robo\Git\GitTaskLoader::class, function () {
        return new class extends \Sweetchuck\Robo\Git\GitTaskLoader {
            // Custom logic
        };
    });
    
  3. Event Listeners: Attach listeners to task execution for logging/auditing:

    $this->taskGitBranchList()->addListener(function ($task) {
        $this->output()->writeln('Branch list task started');
    });
    
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