|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Butschster\ContextGenerator\Lib\Git; |
| 6 | + |
| 7 | +use Butschster\ContextGenerator\Application\Logger\LoggerPrefix; |
| 8 | +use Butschster\ContextGenerator\DirectoriesInterface; |
| 9 | +use Butschster\ContextGenerator\Lib\Git\Exception\GitCommandException; |
| 10 | +use Psr\Log\LoggerInterface; |
| 11 | +use Spiral\Files\Exception\FilesException; |
| 12 | +use Spiral\Files\FilesInterface; |
| 13 | +use Symfony\Component\Process\Exception\ProcessFailedException; |
| 14 | +use Symfony\Component\Process\Process; |
| 15 | + |
| 16 | +final class CommandsExecutor implements CommandsExecutorInterface |
| 17 | +{ |
| 18 | + /** |
| 19 | + * Static cache of validated repositories |
| 20 | + * @var array<string, bool> |
| 21 | + */ |
| 22 | + private static array $validatedRepositories = []; |
| 23 | + |
| 24 | + public function __construct( |
| 25 | + private readonly FilesInterface $files, |
| 26 | + private readonly DirectoriesInterface $dirs, |
| 27 | + #[LoggerPrefix(prefix: 'git-commands-executor')] |
| 28 | + private readonly ?LoggerInterface $logger = null, |
| 29 | + ) {} |
| 30 | + |
| 31 | + public function executeString(Command $command): string |
| 32 | + { |
| 33 | + $repository = $command->repository; |
| 34 | + $repositoryPath = $this->resolvePath($repository); |
| 35 | + |
| 36 | + if (!$this->isValidRepository($repositoryPath)) { |
| 37 | + $this->logger?->error('Not a valid Git repository', [ |
| 38 | + 'repository' => $repositoryPath, |
| 39 | + ]); |
| 40 | + |
| 41 | + throw new \InvalidArgumentException(\sprintf('"%s" is not a valid Git repository', $repositoryPath)); |
| 42 | + } |
| 43 | + |
| 44 | + $commandParts = ['git', ...$command->getCommandParts()]; |
| 45 | + |
| 46 | + $this->logger?->debug('Executing Git command', [ |
| 47 | + 'command' => \implode(' ', $commandParts), |
| 48 | + 'repository' => $repositoryPath, |
| 49 | + ]); |
| 50 | + |
| 51 | + try { |
| 52 | + $process = new Process($commandParts, $repositoryPath); |
| 53 | + $process->run(); |
| 54 | + |
| 55 | + if (!$process->isSuccessful()) { |
| 56 | + $this->logger?->error('Git command failed', [ |
| 57 | + 'command' => \implode(' ', $commandParts), |
| 58 | + 'exitCode' => $process->getExitCode(), |
| 59 | + 'errorOutput' => $process->getErrorOutput(), |
| 60 | + ]); |
| 61 | + |
| 62 | + throw new GitCommandException( |
| 63 | + \sprintf( |
| 64 | + 'Git command "%s" failed with exit code %d: %s', |
| 65 | + \implode(' ', $commandParts), |
| 66 | + $process->getExitCode(), |
| 67 | + $process->getErrorOutput(), |
| 68 | + ), |
| 69 | + $process->getExitCode(), |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | + $this->logger?->debug('Git command executed successfully', [ |
| 74 | + 'command' => \implode(' ', $commandParts), |
| 75 | + 'outputLength' => \strlen($process->getOutput()), |
| 76 | + ]); |
| 77 | + |
| 78 | + return $process->getOutput(); |
| 79 | + } catch (ProcessFailedException $e) { |
| 80 | + $this->logger?->error('Git command process failed', [ |
| 81 | + 'command' => \implode(' ', $commandParts), |
| 82 | + 'error' => $e->getMessage(), |
| 83 | + ]); |
| 84 | + |
| 85 | + throw new GitCommandException( |
| 86 | + \sprintf('Git command process failed: %s', $e->getMessage()), |
| 87 | + $e->getCode(), |
| 88 | + $e, |
| 89 | + ); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + public function isValidRepository(string $repository): bool |
| 94 | + { |
| 95 | + // Return cached result if available |
| 96 | + if (isset(self::$validatedRepositories[$repository])) { |
| 97 | + $this->logger?->debug('Using cached repository validation result', [ |
| 98 | + 'repository' => $repository, |
| 99 | + 'isValid' => self::$validatedRepositories[$repository], |
| 100 | + ]); |
| 101 | + return self::$validatedRepositories[$repository]; |
| 102 | + } |
| 103 | + |
| 104 | + $repositoryPath = $this->resolvePath($repository); |
| 105 | + |
| 106 | + if (!\is_dir($repositoryPath)) { |
| 107 | + $this->logger?->debug('Repository directory does not exist', [ |
| 108 | + 'repository' => $repository, |
| 109 | + ]); |
| 110 | + self::$validatedRepositories[$repository] = false; |
| 111 | + return false; |
| 112 | + } |
| 113 | + |
| 114 | + try { |
| 115 | + $process = new Process( |
| 116 | + ['git', 'rev-parse', '--is-inside-work-tree'], |
| 117 | + $repositoryPath, |
| 118 | + ); |
| 119 | + |
| 120 | + $process->run(); |
| 121 | + |
| 122 | + $isValid = $process->isSuccessful() && \trim($process->getOutput()) === 'true'; |
| 123 | + |
| 124 | + $this->logger?->debug('Repository validation result', [ |
| 125 | + 'repository' => $repository, |
| 126 | + 'isValid' => $isValid, |
| 127 | + ]); |
| 128 | + |
| 129 | + // Cache the result in static array |
| 130 | + self::$validatedRepositories[$repository] = $isValid; |
| 131 | + |
| 132 | + return $isValid; |
| 133 | + } catch (\Exception $e) { |
| 134 | + $this->logger?->error('Error validating repository', [ |
| 135 | + 'repository' => $repository, |
| 136 | + 'error' => $e->getMessage(), |
| 137 | + ]); |
| 138 | + self::$validatedRepositories[$repository] = false; |
| 139 | + return false; |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + public function applyPatch(string $filePath, string $patchContent): string |
| 144 | + { |
| 145 | + $rootPath = $this->dirs->getRootPath(); |
| 146 | + |
| 147 | + if (!$this->isValidRepository((string) $rootPath)) { |
| 148 | + $this->logger?->error('Not a valid Git repository', [ |
| 149 | + 'repository' => (string) $rootPath, |
| 150 | + ]); |
| 151 | + |
| 152 | + throw new \InvalidArgumentException(\sprintf('"%s" is not a valid Git repository', $rootPath)); |
| 153 | + } |
| 154 | + |
| 155 | + $file = $rootPath->join($filePath); |
| 156 | + |
| 157 | + // Ensure the file exists |
| 158 | + if (!$file->exists()) { |
| 159 | + throw new GitCommandException(\sprintf('File "%s" does not exist', $filePath)); |
| 160 | + } |
| 161 | + |
| 162 | + // Create a temporary file for the patch |
| 163 | + try { |
| 164 | + $patchFile = $this->files->tempFilename(); |
| 165 | + } catch (FilesException $e) { |
| 166 | + $this->logger?->error('Failed to create temporary file for patch', [ |
| 167 | + 'error' => $e->getMessage(), |
| 168 | + ]); |
| 169 | + |
| 170 | + throw new GitCommandException('Failed to create temporary file for patch', 0, $e); |
| 171 | + } |
| 172 | + |
| 173 | + try { |
| 174 | + // Write the patch content to a temporary file |
| 175 | + $this->files->write($patchFile, $patchContent, FilesInterface::READONLY); |
| 176 | + |
| 177 | + // Apply the patch using git apply command |
| 178 | + $process = new Process( |
| 179 | + ['git', 'apply', '--whitespace=nowarn', $patchFile], |
| 180 | + (string) $rootPath, |
| 181 | + ); |
| 182 | + |
| 183 | + $process->run(); |
| 184 | + |
| 185 | + // Check if the command was successful |
| 186 | + if (!$process->isSuccessful()) { |
| 187 | + throw new GitCommandException( |
| 188 | + \sprintf('Failed to apply patch: %s', $process->getErrorOutput()), |
| 189 | + $process->getExitCode(), |
| 190 | + ); |
| 191 | + } |
| 192 | + |
| 193 | + return \sprintf('Successfully applied patch to %s', $filePath); |
| 194 | + } finally { |
| 195 | + $this->files->delete($patchFile); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + /** |
| 200 | + * Resolve repository path relative to the root path. |
| 201 | + */ |
| 202 | + private function resolvePath(string $repository): string |
| 203 | + { |
| 204 | + return (string) $this->dirs->getRootPath()->join($repository); |
| 205 | + } |
| 206 | +} |
0 commit comments