debug = $debug ?? defined('DEBUG_MODE'); } public function cd(string $dir): UnixShell { logger()->info('Entering dir: ' . $dir); $c = clone $this; $c->cd = $dir; return $c; } /** * @throws RuntimeException */ public function exec(string $cmd): UnixShell { /* @phpstan-ignore-next-line */ logger()->info(ConsoleColor::yellow('[EXEC] ') . ConsoleColor::green($cmd)); logger()->debug('Executed at: ' . debug_backtrace()[0]['file'] . ':' . debug_backtrace()[0]['line']); if ($this->cd !== null) { $cmd = 'cd ' . escapeshellarg($this->cd) . ' && ' . $cmd; } if (!$this->debug) { $cmd .= ' 1>/dev/null 2>&1'; } $env_str = $this->getEnvString(); if (!empty($env_str)) { $env_str = "{$env_str} "; } f_passthru("{$env_str}{$cmd}"); return $this; } /** * Init the environment variable that common build will be used. * * @param BSDLibraryBase|LinuxLibraryBase|MacOSLibraryBase $library Library class */ public function initializeEnv(BSDLibraryBase|LinuxLibraryBase|MacOSLibraryBase $library): UnixShell { $this->setEnv([ 'CFLAGS' => $library->getLibExtraCFlags(), 'LDFLAGS' => $library->getLibExtraLdFlags(), 'LIBS' => $library->getLibExtraLibs(), ]); return $this; } public function appendEnv(array $env): UnixShell { foreach ($env as $k => $v) { if ($v === '') { continue; } if (!isset($this->env[$k])) { $this->env[$k] = $v; } else { $this->env[$k] = "{$v} {$this->env[$k]}"; } } return $this; } public function execWithResult(string $cmd, bool $with_log = true): array { if ($with_log) { /* @phpstan-ignore-next-line */ logger()->info(ConsoleColor::blue('[EXEC] ') . ConsoleColor::green($cmd)); } else { /* @phpstan-ignore-next-line */ logger()->debug(ConsoleColor::blue('[EXEC] ') . ConsoleColor::gray($cmd)); } logger()->debug('Executed at: ' . debug_backtrace()[0]['file'] . ':' . debug_backtrace()[0]['line']); if ($this->cd !== null) { $cmd = 'cd ' . escapeshellarg($this->cd) . ' && ' . $cmd; } exec($cmd, $out, $code); return [$code, $out]; } public function setEnv(array $env): UnixShell { foreach ($env as $k => $v) { if ($v === '') { continue; } $this->env[$k] = $v; } return $this; } private function getEnvString(): string { $str = ''; foreach ($this->env as $k => $v) { $str .= ' ' . $k . '="' . $v . '"'; } return trim($str); } }