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

Cli Utils Laravel Package

toolkit/cli-utils

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require toolkit/cli-utils
    

    Requires PHP 8.0+.

  2. First Use Case:

    use Toolkit\Cli\Color;
    
    // Basic colored output
    Color::println('Hello, Laravel!', 'success');
    
  3. Where to Look First:

    • Color: For terminal styling (e.g., logs, prompts).
    • CliApp: For building CLI commands (e.g., Artisan-like tools).
    • Highlighter: For syntax-highlighted code output (e.g., debugging PHAR files).

Implementation Patterns

1. CLI Command Development

Workflow:

use Toolkit\Cli\CliApp;

// Define a command
$cmd = CliApp::new('deploy', 'Deploy Laravel assets');
$cmd->addOpt('dry-run', 'd', 'Simulate deployment');
$cmd->addOpt('force', 'f', 'Force overwrite');
$cmd->addArg('env', 'Target environment', true); // Required

$cmd->setHandler(function (CliApp $cmd) {
    $env = $cmd->getArg('env');
    $dryRun = $cmd->hasOpt('dry-run');

    // Logic here (e.g., Artisan::call('deploy', ['env' => $env, '--dry-run' => $dryRun]))
    Color::println("Deploying to $env", $dryRun ? 'warning' : 'success');
});

$cmd->run();

Integration Tips:

  • Use CliApp::help() to auto-generate --help output.
  • Combine with Laravel’s Artisan for hybrid CLI tools:
    $cmd->setHandler(fn($cmd) => Artisan::call('migrate', $cmd->getOpts()));
    

2. Terminal UI Enhancements

Patterns:

  • Progress Bars:
    use Toolkit\Cli\Download;
    $downloader = Download::file('https://example.com/large-file.zip', 'downloads/');
    $downloader->setShowType('bar')->start(); // Visual feedback
    
  • Cursor Control (e.g., for spinners or dynamic prompts):
    use Toolkit\Cli\Util\Terminal;
    Terminal::hideCursor();
    // Render spinner...
    Terminal::showCursor();
    

Laravel-Specific Use Cases:

  • Replace Symfony/Console helpers (e.g., OutputFormatter) with Color for consistent styling.
  • Use Highlighter in tinker or make:command scaffolding to display code snippets.

3. Logging and Debugging

Workflow:

use Toolkit\Cli\Util\Clog;

// Log levels: debug, info, warning, error, success
Clog::log('info', 'Database connection established');
Clog::log('error', 'Failed to migrate: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);

Integration:

  • Replace Log::channel('stack')->debug() with Clog for CLI-specific logs.
  • Pipe Clog output to Laravel’s Log for unified logging:
    Clog::setHandler(function ($level, $message, $context) {
        Log::channel('cli')->$level($message, $context);
    });
    

4. Code Highlighting

Use Case:

use Toolkit\Cli\Util\Highlighter;

// Highlight a Blade template or config file
$highlighted = Highlighter::create()->highlight(file_get_contents(resource_path('views/welcome.blade.php')));
echo $highlighted;

Laravel Integration:

  • Attach to Artisan::command() output for better debugging:
    Artisan::command('inspect:view {view}', function ($view) {
        echo Highlighter::create()->highlight(view()->file($view));
    });
    

Gotchas and Tips

Pitfalls

  1. Color Compatibility:

    • Color uses ANSI escape codes. Test in Windows Terminal (may require enableVirtualTerminalProcessing for CMD).
    • Fix: Use Color::isSupported() to check before rendering:
      if (!Color::isSupported()) {
          echo "Fallback: " . strip_tags($message);
      }
      
  2. CliApp Argument Parsing:

    • Gotcha: Short options (-f) override long options (--force) if values conflict.
    • Fix: Use addOpt() with required: true and validate early:
      $cmd->addOpt('port', 'p', 'Server port', 8000, true); // Default + required
      if (!$cmd->hasOpt('port') || !is_numeric($cmd->getOpt('port'))) {
          throw new \RuntimeException('Port must be numeric');
      }
      
  3. Terminal Control Quirks:

    • Terminal::clearScreen() may not work in SSH multiplexing (e.g., tmux).
    • Fix: Use Terminal::savePosition()/restorePosition() for localized clearing.

Debugging Tips

  1. CliApp:

    • Dump parsed args/opts for debugging:
      $cmd->setHandler(function (CliApp $cmd) {
          var_dump($cmd->getOpts(), $cmd->getArgs());
      });
      
    • Enable debug mode for Download:
      $downloader->setDebug(true); // Shows raw HTTP responses
      
  2. Highlighter:

    • Issue: Custom syntax highlighting fails.
    • Fix: Extend Highlighter:
      $highlighter = Highlighter::create()
          ->addRule('/\b(Artisan|Route)\b/', 'keyword');
      

Extension Points

  1. Custom Color Themes:

    Color::setTheme([
        'success' => ['fg' => 'green', 'bold' => true],
        'warning' => ['fg' => 'yellow', 'bg' => 'black'],
    ]);
    
  2. CliApp Middleware:

    • Add pre/post handlers:
      $cmd->addMiddleware(function (CliApp $cmd) {
          if ($cmd->hasOpt('verbose')) {
              Clog::log('debug', 'Verbose mode enabled');
          }
      });
      
  3. Download Hooks:

    • Extend Download for custom progress logic:
      $downloader->onProgress(function ($progress) {
          if ($progress > 0.9) {
              Color::println('Almost done!', 'warning');
          }
      });
      

Laravel-Specific Gotchas

  • Artisan Integration:

    • Avoid mixing CliApp and Artisan input parsing (use one or the other).
    • Workaround: Parse CliApp first, then pass to Artisan:
      $args = $cmd->getRemainArgs();
      Artisan::call('migrate', array_merge($cmd->getOpts(), ['--force' => $args]));
      
  • Service Provider:

    • Bind CliApp to Laravel’s container for dependency injection:
      $this->app->singleton(CliApp::class, fn() => CliApp::new('laravel:cli-utils'));
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity