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

Bash Echolorized Laravel Package

barthy-koeln/bash-echolorized

Minimal bash helper for clean, colorized CLI output in CI/CD scripts and git hooks. Source it via Composer or npm/yarn and use e_info/e_success/e_warning/e_error plus colored_output and tagged_output for readable, tagged status lines.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation Download the Bash script directly (no Composer package exists—use the raw script from the repo):

    curl -o echorized https://raw.githubusercontent.com/barthy-koeln/bash-echolorized/main/echolorized
    chmod +x echorized
    

    Place it in a /bin or /scripts directory in your Laravel project.

  2. Basic Usage in Laravel Call the script from PHP using shell_exec or Laravel’s Process facade:

    use Symfony\Component\Process\Process;
    use Symfony\Component\Process\Exception\ProcessFailedException;
    
    $process = new Process(['./echolorized', '--color', 'red', 'Error: Task failed']);
    $process->run();
    echo $process->getOutput();
    
  3. First Laravel Integration Add a helper method in a service class (e.g., app/Services/ConsoleHelper.php):

    namespace App\Services;
    
    class ConsoleHelper {
        public static function coloredEcho(string $message, string $color = 'default'): void {
            $command = './echolorized --color ' . $color . ' "' . escapeshellarg($message) . '"';
            shell_exec($command);
        }
    }
    

    Use it in an Artisan command:

    use App\Services\ConsoleHelper;
    
    class MyCommand extends Command {
        protected $signature = 'my:command';
        protected $description = 'Demonstrates colored output';
    
        public function handle() {
            ConsoleHelper::coloredEcho('Success!', 'green');
            ConsoleHelper::coloredEcho('Warning!', 'yellow');
        }
    }
    

Implementation Patterns

Usage Patterns

  1. Artisan Command Styling Replace echo or $this->info() calls with echolorized for consistent styling:

    // Before
    $this->info('User created: ' . $user->name);
    
    // After
    ConsoleHelper::coloredEcho("User created: {$user->name}", 'blue');
    
  2. Dynamic Styling in Loops Use conditional logic to style output dynamically:

    foreach ($tasks as $task) {
        $color = $task->completed ? 'green' : 'red';
        ConsoleHelper::coloredEcho($task->name, $color);
    }
    
  3. Background/Foreground Combinations Leverage ANSI codes for advanced styling (e.g., red text on yellow background):

    echorized --fg red --bg yellow "Critical Alert"
    

    Call from PHP:

    shell_exec('echolorized --fg red --bg yellow "Critical Alert"');
    
  4. Integration with Laravel’s Console Component Extend Symfony’s Output class to support echolorized:

    use Symfony\Component\Console\Output\OutputInterface;
    
    class ColoredOutput extends OutputInterface {
        public function styled(string $message, string $style): void {
            $command = './echolorized --style ' . $style . ' "' . escapeshellarg($message) . '"';
            shell_exec($command);
        }
    }
    

Workflows

  1. CI/CD Pipeline Feedback Use echolorized to highlight build stages:

    echorized --color green "Tests passed!"
    echorized --color red "Tests failed: 2 errors"
    

    Call from Laravel’s Artisan::call() in a deployment script.

  2. Debugging and Logging Add context to log messages in development:

    if (config('app.debug')) {
        ConsoleHelper::coloredEcho('Debug: ' . $variable, 'cyan');
    }
    
  3. User Feedback in Queues Style job completion messages (if output is viewed in a terminal):

    dispatch(new ProcessPodcast)->after(function ($job, $podcast) {
        ConsoleHelper::coloredEcho("Podcast processed: {$podcast->title}", 'green');
    });
    

Integration Tips

  1. Environment Awareness Check if output is a TTY before coloring:

    if (stream_isatty(STDOUT)) {
        ConsoleHelper::coloredEcho('Colored message', 'blue');
    } else {
        echo 'Colored message (fallback)' . PHP_EOL;
    }
    
  2. Bundling the Script Include echolorized in your Laravel project’s /vendor/bin or /scripts directory to ensure it’s version-controlled and portable.

  3. Cross-Platform Compatibility Handle Windows Terminal limitations:

    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        putenv('ANSICON=1'); // Enable ANSI on Windows
    }
    
  4. Laravel Service Provider Register a facade for cleaner syntax:

    // In a service provider
    Facades\Facade::register('Echolorized', 'App\Facades\EcholorizedFacade');
    
    // Facade class
    namespace App\Facades;
    use Illuminate\Support\Facades\Facade as BaseFacade;
    
    class EcholorizedFacade extends BaseFacade {
        public static function coloredEcho(string $message, string $color) {
            return (new \App\Services\ConsoleHelper())->coloredEcho($message, $color);
        }
    }
    

    Usage:

    Echolorized::coloredEcho('Hello, world!', 'magenta');
    

Gotchas and Tips

Pitfalls

  1. ANSI Code Corruption

    • Issue: ANSI escape sequences may break log files or CI/CD pipelines (e.g., GitHub Actions, Jenkins).
    • Fix: Filter ANSI codes in logs:
      $log = preg_replace('/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?m/', '', $log);
      
  2. Windows Compatibility

    • Issue: Colors may not render in cmd.exe (requires Windows Terminal or WSL).
    • Fix: Document requirements or use a polyfill like win-ansi-escapes.
  3. Shell Injection Risks

    • Issue: Directly passing user input to shell_exec is unsafe.
    • Fix: Always use escapeshellarg():
      $message = escapeshellarg($userInput);
      shell_exec("./echolorized --color red {$message}");
      
  4. Non-TTY Output

    • Issue: Colors are ignored if output isn’t a terminal (e.g., queues, cron).
    • Fix: Detect TTY and fallback:
      if (!stream_isatty(STDOUT)) {
          echo "Fallback: {$message}\n";
          return;
      }
      
  5. Script Location Dependencies

    • Issue: Hardcoding paths to echolorized breaks portability.
    • Fix: Use absolute paths or ensure the script is in $PATH:
      $scriptPath = base_path('scripts/echolorized');
      shell_exec("{$scriptPath} --color blue 'Message'");
      

Debugging

  1. Verify ANSI Support Test if your terminal supports ANSI:

    echo -e "\e[31mRed text\e[0m"
    

    If it doesn’t render, use a tool like ANSI Escape for Node.js or a PHP polyfill.

  2. Check Script Permissions Ensure echolorized is executable:

    chmod +x ./echolorized
    
  3. Inspect Output Pipe output to cat -v to see hidden ANSI codes:

    ./echolorized "Test" | cat -v
    

Configuration Quirks

  1. Default Colors The script uses a predefined palette. To customize, edit the Bash script’s color_map array or pass custom ANSI codes:

    echorized --fg "\e[38;5;202m" "Custom color"
    
  2. Style Shortcuts Use built-in styles (success, error, warn) for consistency:

    echorized --style success "Operation completed"
    
  3. Bold/Italic Text Combine styles for emphasis:

    echorized --fg red --bold "Critical Error"
    

Extension Points

  1. Add Custom Colors Extend the Bash script’s color_map to support additional colors:

    declare -A color_map=(
        ["custom"]="\e[38;5;196m"  # Custom RGB color
    )
    
  2. PHP Wrapper Enhancements Add methods for common use cases in your ConsoleHelper:

    class ConsoleHelper {
        public
    
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.
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
christhompsontldr/laravel-inky