Add sudo support for migrate commands when not running as root
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
60
app/RSpade/Commands/Migrate/PrivilegedCommandTrait.php
Executable file
60
app/RSpade/Commands/Migrate/PrivilegedCommandTrait.php
Executable file
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\RSpade\Commands\Migrate;
|
||||
|
||||
use Symfony\Component\Process\Process;
|
||||
use Symfony\Component\Process\Exception\ProcessFailedException;
|
||||
|
||||
/**
|
||||
* Trait for commands that need to run privileged operations (supervisorctl, file ops on /var/lib/mysql, etc.)
|
||||
*
|
||||
* Automatically prepends sudo when not running as root.
|
||||
*/
|
||||
trait PrivilegedCommandTrait
|
||||
{
|
||||
/**
|
||||
* Check if we're running as root
|
||||
*/
|
||||
protected function is_root(): bool
|
||||
{
|
||||
$whoami = trim(shell_exec('whoami') ?? '');
|
||||
return $whoami === 'root';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get sudo prefix if needed
|
||||
*/
|
||||
protected function sudo_prefix(): string
|
||||
{
|
||||
return $this->is_root() ? '' : 'sudo ';
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a shell command string with sudo if needed
|
||||
*/
|
||||
protected function shell_exec_privileged(string $command): ?string
|
||||
{
|
||||
$full_command = $this->sudo_prefix() . $command;
|
||||
return shell_exec($full_command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a Process command array with sudo if needed
|
||||
*/
|
||||
protected function run_privileged_command(array $command, bool $throw_on_error = true): string
|
||||
{
|
||||
if (!$this->is_root()) {
|
||||
array_unshift($command, 'sudo');
|
||||
}
|
||||
|
||||
$process = new Process($command);
|
||||
$process->setTimeout(60);
|
||||
$process->run();
|
||||
|
||||
if ($throw_on_error && !$process->isSuccessful()) {
|
||||
throw new ProcessFailedException($process);
|
||||
}
|
||||
|
||||
return $process->getOutput();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user