Skip to content

Commit

Permalink
Check for and require tput command to be available
Browse files Browse the repository at this point in the history
The tput command isn't available by default in the Alpine Linux official
PHP docker images and this throws an InvalidArgumentException for
truncation length.

This commit replaces tput in favour of using stty on *nix OSes and mode
on Windows.
  • Loading branch information
digiservnet committed Jul 29, 2023
1 parent 079d044 commit aa415c4
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions src/Terminal.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

namespace Laravel\Prompts;

use RuntimeException;

use const PHP_OS_FAMILY;

class Terminal
{
/**
Expand Down Expand Up @@ -62,15 +66,15 @@ public function restoreTty(): void
*/
public function cols(): int
{
return $this->cols ??= (int) shell_exec('tput cols 2>/dev/null');
return $this->cols ??= $this->terminalSize()['cols'];
}

/**
* Get the number of lines in the terminal.
*/
public function lines(): int
{
return $this->lines ??= (int) shell_exec('tput lines 2>/dev/null');
return $this->lines ??= $this->terminalSize()['lines'];
}

/**
Expand All @@ -80,4 +84,40 @@ public function exit(): void
{
exit(1);
}

/**
* Get the terminal lines and columns
* from stty (*nix) or mode (windows).
*
* @return array<string, int>
* @throws RuntimeException
*/
protected function terminalSize(): array
{
if (PHP_OS_FAMILY === 'Windows') {
if (!is_string($mode = shell_exec('mode CON'))) {
throw new RuntimeException('Unable to determine terminal size.');
}

$matches = [];
preg_match('/Lines: \s+(\d+)\n.+?Columns:\s*(\d+)/i', $mode, $matches);

if (count($matches) !== 3) {
throw new RuntimeException('Unable to determine terminal size.');
}

[$lines, $cols] = [$matches[1], $matches[2]];
} else {
if (!is_string($stty = shell_exec('stty size 2>/dev/null'))) {
throw new RuntimeException('Unable to determine terminal size.');
}

[$lines, $cols] = explode(' ', rtrim($stty));
}

return [
'lines' => (int)$lines,
'cols' => (int)$cols,
];
}
}

0 comments on commit aa415c4

Please sign in to comment.