Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 48 additions & 9 deletions bridge/symfony-console/src/Command/Init.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Style\SymfonyStyle;
use Testo\Output\Terminal\ProgramStatus;

/**
* Initializes Testo in the project:
Expand Down Expand Up @@ -50,12 +52,14 @@
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$status = self::programStatus($output);
$status->working();

try {
$basePath = Path::create((string) $input->getOption('path'));
self::ensureDirectory($basePath, $io);

$srcPath = self::discoverSourceDirectory($input, $basePath, $io);
$srcPath = self::discoverSourceDirectory($input, $basePath, $io, $status);

$testsPath = $basePath->join('tests');
self::ensureDirectory($testsPath, $io);
Expand All @@ -68,17 +72,21 @@
# Non-interactive + existing config: bail out before touching the file.
if ($configPath->isFile() && !$input->isInteractive()) {
$io->warning(\sprintf('%s already exists. Skipping (non-interactive mode).', $configPath));
$status->done('Configuration left untouched');
return Command::SUCCESS;
}

if (self::writeConfig($configPath, $srcPath, $suites, $io)) {
if (self::writeConfig($configPath, $srcPath, $suites, $io, $status)) {
self::printSummary($configPath, $composerKeys, $io);
$status->done('Configuration created');
} else {
$io->note(\sprintf('Left existing %s untouched.', $configPath));
$status->done('Configuration left untouched');
}
} catch (\Throwable $exception) {
$output->writeln('');
$output->writeln(\sprintf('<fg=red>%s</>', $exception->getMessage()));
$status->error('Initialization failed');
return Command::FAILURE;
}

Expand All @@ -102,8 +110,12 @@
* keeps the generated config self-consistent — paths like `src` always resolve
* next to testo.php, regardless of where the user runs the command from.
*/
private static function discoverSourceDirectory(InputInterface $input, Path $basePath, SymfonyStyle $io): Path
{
private static function discoverSourceDirectory(
InputInterface $input,
Path $basePath,
SymfonyStyle $io,
ProgramStatus $status,
): Path {
if ($basePath->join('src')->isDir()) {
return Path::create('src');
}
Expand All @@ -115,7 +127,8 @@
));
}

return Path::create((string) $io->ask(
$status->blocked('Path to source code');
$path = Path::create((string) $io->ask(
question: 'Path to source code (relative to project root)',
default: 'src',
validator: static function (?string $value) use ($basePath): string {
Expand All @@ -130,6 +143,21 @@
return $value;
},
));
$status->working();

return $path;
}

/**
* Program status goes where the prompts are drawn, and only when they are drawn for a person: a quiet
* or undecorated run gets none. The prompts go through {@see SymfonyStyle}, which the question helper
* does not treat as a console output, so they are drawn on stdout rather than on the error output.
*/
private static function programStatus(OutputInterface $output): ProgramStatus
{
return $output instanceof StreamOutput && $output->isDecorated() && !$output->isQuiet()
? ProgramStatus::detect($output->getStream())

Check warning on line 159 in bridge/symfony-console/src/Command/Init.php

View check run for this annotation

Codecov / codecov/patch

bridge/symfony-console/src/Command/Init.php#L159

Added line #L159 was not covered by tests
: ProgramStatus::disabled();
}

/**
Expand Down Expand Up @@ -213,10 +241,21 @@
*
* @param list<string> $suites
*/
private static function writeConfig(Path $configPath, Path $srcPath, array $suites, SymfonyStyle $io): bool
{
if ($configPath->isFile() && !$io->confirm(\sprintf('%s already exists. Overwrite?', $configPath), false)) {
return false;
private static function writeConfig(
Path $configPath,
Path $srcPath,
array $suites,
SymfonyStyle $io,
ProgramStatus $status,
): bool {
if ($configPath->isFile()) {
$status->blocked('Overwrite the existing configuration?');
$overwrite = $io->confirm(\sprintf('%s already exists. Overwrite?', $configPath), false);
$status->working();

if (!$overwrite) {
return false;
}
}

$suitesCode = '';
Expand Down
6 changes: 5 additions & 1 deletion core/Application/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use Testo\Event\Framework\SessionStarting;
use Testo\Event\Framework\WorkerFinished;
use Testo\Event\Framework\WorkerStarting;
use Testo\Event\TestSuite\TestSuitesLocated;
use Testo\Filter;

final readonly class Application
Expand Down Expand Up @@ -125,9 +126,12 @@ public function run(PluginConfigurator|string ...$latePlugins): RunResult
$discovery = 0.0;
$tests = 0.0;

$suites = $container->make(SuiteLocator::class)->locate($appConfig);
$dispatcher->dispatch(new TestSuitesLocated($suites));

# Iterate and run Test Suites
$suiteResults = [];
foreach ($container->make(SuiteLocator::class)->locate($appConfig) as $config) {
foreach ($suites as $config) {
# Resolve a Test Suite from config and
# run a separate container scope to isolate services and plugins.
$suiteResult = self::scope(
Expand Down
28 changes: 28 additions & 0 deletions core/Event/TestSuite/TestSuitesLocated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Testo\Event\TestSuite;

use Testo\Application\Config\SuiteConfig;

/**
* Event triggered once the run knows which test suites it will go through, before the first of them is
* scanned.
*
* The list is final: suite filters such as `--suite` have already been applied, and suites run in this
* order. A suite whose scan finds no test cases is skipped without a {@see TestSuiteStarting}, so the list
* is an upper bound of the suites that actually start.
*
* @psalm-immutable
* @api
*/
final readonly class TestSuitesLocated
{
/**
* @param list<SuiteConfig> $suites
*/
public function __construct(

Check warning on line 25 in core/Event/TestSuite/TestSuitesLocated.php

View check run for this annotation

Codecov / codecov/patch

core/Event/TestSuite/TestSuitesLocated.php#L25

Added line #L25 was not covered by tests
public array $suites,
) {}

Check warning on line 27 in core/Event/TestSuite/TestSuitesLocated.php

View check run for this annotation

Codecov / codecov/patch

core/Event/TestSuite/TestSuitesLocated.php#L27

Added line #L27 was not covered by tests
}
157 changes: 157 additions & 0 deletions core/Output/Terminal/ProgramStatus.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php

declare(strict_types=1);

namespace Testo\Output\Terminal;

/**
* Reports what the program is doing to the terminal it runs in, through the OSC 7501 program status
* protocol (<https://www.superlogical.com/rex/docs/build/program-status>).
*
* The terminal shows the state in its tab or window chrome; terminals that do not know the protocol
* ignore it. A disabled instance writes nothing, so callers report unconditionally.
*
* ```php
* $status = ProgramStatus::detect(\STDOUT);
* $status->working(progress: 40, message: 'Unit');
* $status->done('120 passed');
* ```
*
* @api
*/
final class ProgramStatus
{
/**
* Opt-out switch: `0`, `false`, `off` or `no` turns the reports off.
*/
public const ENV_SWITCH = 'TESTO_TERMINAL_STATUS';

private const APP = 'testo';

/**
* The protocol's limit on a decoded `msg`.
*/
private const MESSAGE_LIMIT = 2048;

private ?string $last = null;

/**
* @param resource|null $stream Where the sequences go; null disables the reports.
*/
public function __construct(
private readonly mixed $stream,
) {}

/**
* A reporter for `$stream` that writes only where a person watches a terminal: the stream is an
* interactive TTY that understands escape sequences, and the user has not switched the reports off.
*
* @param resource $stream
*/
public static function detect(mixed $stream): self
{
return new self(self::isSupported($stream) && !self::isSwitchedOff() ? $stream : null);
}

public static function disabled(): self
{
return new self(null);
}

public function isEnabled(): bool
{
return $this->stream !== null;
}

/**
* @param int<0, 100>|null $progress Percent done; null for an indeterminate state.
*/
public function working(?int $progress = null, string $message = ''): void
{
$this->report('working', $progress, $message);
}

/**
* Waiting for the user to answer a question.
*/
public function blocked(string $message = ''): void
{
$this->report('blocked', null, $message, kind: 'question');
}

public function done(string $message = ''): void
{
$this->report('done', null, $message);
}

public function error(string $message = ''): void
{
$this->report('error', null, $message);
}

/**
* Removes the program's state from the terminal.
*/
public function clear(): void
{
$this->report('clear', null, '');
}

/**
* @param resource $stream
*/
private static function isSupported(mixed $stream): bool
{
if (!\is_resource($stream) || !\stream_isatty($stream)) {
return false;
}

# A Windows console prints escape sequences as text unless VT processing is on for it.
return \DIRECTORY_SEPARATOR !== '\\'

Check warning on line 110 in core/Output/Terminal/ProgramStatus.php

View check run for this annotation

Codecov / codecov/patch

core/Output/Terminal/ProgramStatus.php#L110

Added line #L110 was not covered by tests
|| (\function_exists('sapi_windows_vt100_support') && @sapi_windows_vt100_support($stream));
}

private static function isSwitchedOff(): bool
{
$value = $_SERVER[self::ENV_SWITCH] ?? $_ENV[self::ENV_SWITCH] ?? \getenv(self::ENV_SWITCH);

Check warning on line 116 in core/Output/Terminal/ProgramStatus.php

View check run for this annotation

Codecov / codecov/patch

core/Output/Terminal/ProgramStatus.php#L116

Added line #L116 was not covered by tests

return \is_string($value) && \in_array(\strtolower(\trim($value)), ['0', 'false', 'off', 'no'], true);

Check warning on line 118 in core/Output/Terminal/ProgramStatus.php

View check run for this annotation

Codecov / codecov/patch

core/Output/Terminal/ProgramStatus.php#L118

Added line #L118 was not covered by tests
}

/**
* The protocol discards a whole report whose message is not valid UTF-8, holds a control character
* (C0, DEL or C1) or runs past the limit, so all three are fixed here rather than losing the report.
*/
private static function singleLine(string $message): string
{
$message = \mb_scrub($message, 'UTF-8');
$message = \trim((string) \preg_replace('/\p{Cc}+/u', ' ', $message));

return \strlen($message) <= self::MESSAGE_LIMIT
? $message
: \mb_strcut($message, 0, self::MESSAGE_LIMIT, 'UTF-8');
}

private function report(string $state, ?int $progress, string $message, ?string $kind = null): void
{
if ($this->stream === null) {
return;
}

$pairs = ['state=' . $state, 'app=' . self::APP];
$progress === null or $pairs[] = 'progress=' . \max(0, \min(100, $progress));
$kind === null or $pairs[] = 'kind=' . $kind;
$message = self::singleLine($message);
$message === '' or $pairs[] = 'msg=' . \base64_encode($message);

$sequence = "\033]7501;" . \implode(':', $pairs) . "\033\\";

# Each report replaces the previous one whole, so a repeat changes nothing on the terminal side.
if ($sequence === $this->last) {
return;
}

$this->last = $sequence;
@\fwrite($this->stream, $sequence);
}
}
Loading
Loading