Skip to content

Commit

Permalink
Refactor code to add sudo prefix for certain commands
Browse files Browse the repository at this point in the history
  • Loading branch information
andrasbacsai committed Apr 16, 2024
1 parent 41f4b36 commit 58523b0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
9 changes: 8 additions & 1 deletion app/Traits/ExecuteRemoteCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@ public function execute_remote_command(...$commands)
$ignore_errors = data_get($single_command, 'ignore_errors', false);
$append = data_get($single_command, 'append', true);
$this->save = data_get($single_command, 'save');

if ($this->server->isNonRoot()) {
if (str($command)->startsWith('docker exec')) {
$command = str($command)->replace('docker exec', 'sudo docker exec');
} else {
$command = parseLineForSudo($command, $this->server);
}
}
ray($command);
$remote_command = generateSshCommand($this->server, $command);
$process = Process::timeout(3600)->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {
$output = Str::of($output)->trim();
Expand Down
23 changes: 22 additions & 1 deletion bootstrap/helpers/shared.php
Original file line number Diff line number Diff line change
Expand Up @@ -1951,7 +1951,8 @@ function check_domain_usage(ServiceApplication|Application|null $resource = null
}
}

function parseCommandsByLineForSudo(Collection $commands, Server $server): array {
function parseCommandsByLineForSudo(Collection $commands, Server $server): array
{
$commands = $commands->map(function ($line) {
if (!str($line)->startSwith('cd') && !str($line)->startSwith('command')) {
return "sudo $line";
Expand Down Expand Up @@ -1979,3 +1980,23 @@ function parseCommandsByLineForSudo(Collection $commands, Server $server): array

return $commands->toArray();
}
function parseLineForSudo(string $command, Server $server): string
{
if (!str($command)->startSwith('cd') && !str($command)->startSwith('command')) {
$command = "sudo $command";
}
if (Str::startsWith($command, 'sudo mkdir -p')) {
$command = "$command && sudo chown -R $server->user:$server->user " . Str::after($command, 'sudo mkdir -p') . ' && sudo chmod -R o-rwx ' . Str::after($command, 'sudo mkdir -p');
}
if (str($command)->contains('$(') || str($command)->contains('`')) {
$command = str($command)->replace('$(', '$(sudo ')->replace('`', '`sudo ')->value();
}
if (str($command)->contains('||')) {
$command = str($command)->replace('||', '|| sudo ')->value();
}
if (str($command)->contains('&&')) {
$command = str($command)->replace('&&', '&& sudo ')->value();
}

return $command;
}

0 comments on commit 58523b0

Please sign in to comment.