Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace fswatch with spatie/file-system-watcher (#1) #16

Draft
wants to merge 1 commit into
base: 1.x
Choose a base branch
from
Draft
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
8 changes: 4 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
}
],
"require": {
"php": "^7.3 || ^8.0",
"php": "^8.1",
"pestphp/pest-plugin": "^1.0",
"react/child-process": "^0.6.1",
"react/event-loop": "^1.1"
"nunomaduro/termwind": "^1.13",
"spatie/file-system-watcher": "^1.1"
},
"conflict": {
"evenement/evenement": "^1.0",
Expand All @@ -35,7 +35,7 @@
},
"require-dev": {
"pestphp/pest": "^1.0",
"pestphp/pest-dev-tools": "dev-master"
"pestphp/pest-dev-tools": "^1.0.0"
},
"minimum-stability": "dev",
"prefer-stable": true,
Expand Down
147 changes: 100 additions & 47 deletions src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

use Pest\Contracts\Plugins\HandlesArguments;
use Pest\Support\Str;
use React\ChildProcess\Process;
use React\EventLoop\Factory;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;

use function Termwind\render;
use function Termwind\terminal;

/**
* @internal
Expand All @@ -22,20 +24,40 @@ final class Plugin implements HandlesArguments

private const WATCH_OPTION = 'watch';

/**
* @var OutputInterface
*/
private $output;
private string $command = 'vendor/bin/pest';

public Process $pestProcess;

/** @var array<int, string> */
private $watchedDirectories = self::WATCHED_DIRECTORIES;
private array|string $watchedDirectories;

public function __construct(OutputInterface $output)
{
$this->output = $output;
public function __construct(
private OutputInterface $output
) {
// remove non-existing directories from watched directories
$this->watchedDirectories = array_filter(self::WATCHED_DIRECTORIES, fn ($directory) => is_dir($directory));
}

public function handleArguments(array $originals): array
{
if (!$this->userWantsToWatch($originals)) {
return $originals;
}

$this->info('Watching for changes...');

// dd('end', $this->getCommand());
$processStarted = $this->startProcess();

// if the process failed to start, exit
if (!$processStarted) {
exit(1);
}

$this->listenForChanges();
}

private function userWantsToWatch(array $originals): bool
{
$arguments = array_merge([''], array_values(array_filter($originals, function ($original): bool {
return $original === sprintf('--%s', self::WATCH_OPTION) || Str::startsWith($original, sprintf('--%s=', self::WATCH_OPTION));
Expand All @@ -45,70 +67,101 @@ public function handleArguments(array $originals): array
foreach ($arguments as $argument) {
unset($originals[$argument]);
}
$originals = array_flip($originals);

$inputs = [];
$inputs[] = new InputOption(self::WATCH_OPTION, null, InputOption::VALUE_OPTIONAL, '', true);

$input = new ArgvInput($arguments, new InputDefinition($inputs));

if (!$input->hasParameterOption(sprintf('--%s', self::WATCH_OPTION))) {
return $originals;
return false;
}

$this->checkFswatchIsAvailable();

// set the watched directories
if ($input->getOption(self::WATCH_OPTION) !== null) {
/* @phpstan-ignore-next-line */
$this->watchedDirectories = explode(',', $input->getOption(self::WATCH_OPTION));
}

$loop = Factory::create();
$watcher = new Watch($loop, $this->watchedDirectories);
$watcher->run();
// set command to run
$this->setCommand(implode(' ', array_flip($originals)));

return true;
}

private function listenForChanges(): self
{
\Spatie\Watcher\Watch::paths(...$this->watchedDirectories)
->onAnyChange(function (string $event, string $path) {
if ($this->changedPathShouldRestartPest($path)) {
$this->restartProcess();
}
})
->start();

return $this;
}

private function startProcess(): bool
{
terminal()->clear();

$this->pestProcess = Process::fromShellCommandline($this->getCommand());

$this->pestProcess->setTty(true)->setTimeout(null);

$command = implode(' ', $originals);
$this->pestProcess->start(fn ($type, $output) => $this->output->write($output));

$output = $this->output;
sleep(1);

$watcher->on('change', static function () use ($command, $output): void {
$loop = Factory::create();
$process = new Process($command);
$process->start($loop);
// @phpstan-ignore-next-line
$process->stdout->on('data', function ($line) use ($output): void {
$output->write($line);
});
$process->on('exit', function () use ($output): void {
$output->writeln('');
});
$loop->run();
});
return !$this->pestProcess->isTerminated();
}

private function restartProcess(): self
{
$this->info('Change detected! Restarting Pest...');

$watcher->emit('change');
$this->pestProcess->stop(0);

$loop->run();
$this->startProcess();

exit(0);
return $this;
}

private function checkFswatchIsAvailable(): void
private function changedPathShouldRestartPest(string $path): bool
{
exec('fswatch 2>&1', $output);
if ($this->isPhpFile($path)) {
return true;
}

if (strpos(implode(' ', $output), 'command not found') === false) {
return;
foreach ($this->watchedDirectories as $configuredPath) {
if ($path === $configuredPath) {
return true;
}
}

$this->output->writeln(sprintf(
"\n <fg=white;bg=red;options=bold> ERROR </> fswatch was not found.</>",
));
return false;
}

private function isPhpFile(string $path): bool
{
return str_ends_with(strtolower($path), '.php');
}

public function getCommand(): string
{
return $this->command;
}

public function setCommand(string $command): void
{
$this->command = $command;
}

$this->output->writeln(sprintf(
"\n Install it from: %s",
'https://github.com/emcrisostomo/fswatch#getting-fswatch',
));
private function info(string $message): void
{
$html = "<div class='mx-2 mb-1 mt-1'><span class='px-1 bg-blue text-white uppercase'>info</span><span class='ml-1'>{$message}</span></div>";

exit(1);
render($html);
}
}
67 changes: 0 additions & 67 deletions src/Watch.php

This file was deleted.