Skip to content

Commit

Permalink
Allow disabling colors (#118)
Browse files Browse the repository at this point in the history
* Allow disabling colors

* Make  a public static variable

* Add documentation about disabling colors to readme

* Remove empty line

* Don't worry about missing styles if colors are disabled

* Short-circut the missing method the same way we do line function

* Rename Color's  variable to just  as we do camelcase here

* Check if NO_COLOR is set when writing to the terminal

* Add info about NO_COLOR environment variable to readme

---------

Co-authored-by: Jitendra Adhikari <[email protected]>
  • Loading branch information
kodie and adhocore authored Dec 1, 2024
1 parent bacbbda commit cd0152f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,14 @@ Ahc\Cli\Output\Color::style('error', [
]);
```

#### Disable colors

```php
Ahc\Cli\Output\Color::$enabled = false;
```

Colors will be automatically disabled if the `NO_COLOR` environment variable is set to true.

### Cursor

Move cursor around, erase line up or down, clear screen.
Expand Down
10 changes: 10 additions & 0 deletions src/Output/Color.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ class Color
const GRAY = 47;
const DARKGRAY = 100;

public static bool $enabled = true;

protected string $format = "\033[:mod:;:fg:;:bg:m:txt:\033[0m";

/** @var array Custom styles */
Expand Down Expand Up @@ -138,6 +140,10 @@ public static function fg256(int $code): string
*/
public function line(string $text, array $style = []): string
{
if (!self::$enabled || getenv('NO_COLOR')) {
return $text;
}

$style += ['bg' => null, 'fg' => static::WHITE, 'bold' => 0, 'mod' => null];

$format = $style['bg'] === null
Expand Down Expand Up @@ -229,6 +235,10 @@ public function __call(string $name, array $arguments): string
}

if (!method_exists($this, $name)) {
if (!self::$enabled || getenv('NO_COLOR')) {
return $text;
}

throw new InvalidArgumentException(sprintf('Style "%s" not defined', $name));
}

Expand Down

0 comments on commit cd0152f

Please sign in to comment.