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

[0.1.x] spin: Ensure process termination on $callback() failure #71

Merged
merged 10 commits into from
Sep 19, 2023
44 changes: 27 additions & 17 deletions src/Spinner.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ public function spin(Closure $callback): mixed
return $this->renderStatically($callback);
}

$this->hideCursor();

$originalAsync = pcntl_async_signals(true);

pcntl_signal(SIGINT, function () {
Expand All @@ -56,6 +54,7 @@ public function spin(Closure $callback): mixed
});

try {
$this->hideCursor();
$this->render();

$pid = pcntl_fork();
Expand All @@ -71,24 +70,33 @@ public function spin(Closure $callback): mixed
} else {
$result = $callback();

posix_kill($pid, SIGHUP);
pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);

$this->eraseRenderedLines();
$this->showCursor();
$this->resetTerminal($originalAsync, $pid);

return $result;
}
} catch (\Throwable $e) {
$this->showCursor();
pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);
$this->resetTerminal($originalAsync, $pid ?? null);

throw $e;
}
}

/**
* Reset the terminal.
*/
protected function resetTerminal(bool $originalAsync, ?int $pid): void
{
if ($pid) {
posix_kill($pid, SIGHUP);
}

pcntl_async_signals($originalAsync);
pcntl_signal(SIGINT, SIG_DFL);

$this->eraseRenderedLines();
$this->showCursor();
}

/**
* Render a static version of the spinner.
*
Expand All @@ -101,13 +109,15 @@ protected function renderStatically(Closure $callback): mixed
{
$this->static = true;

$this->hideCursor();
$this->render();

$result = $callback();
try {
$this->hideCursor();
$this->render();

$this->eraseRenderedLines();
$this->showCursor();
$result = $callback();
} finally {
$this->eraseRenderedLines();
$this->showCursor();
}

return $result;
}
Expand Down