Skip to content

Commit

Permalink
Cache requirements to avoid running composer all the time
Browse files Browse the repository at this point in the history
  • Loading branch information
pyrech committed Feb 26, 2024
1 parent 1c7e638 commit bc9b6f4
Showing 1 changed file with 53 additions and 14 deletions.
67 changes: 53 additions & 14 deletions src/Remote/Composer.php
Expand Up @@ -10,6 +10,7 @@
class Composer
{
public const VENDOR_DIR = '/.castor/vendor/';
public const PATH_CASTOR_REQUIREMENTS = self::VENDOR_DIR . 'castor-requirements.json';

public function __construct(
private readonly LoggerInterface $logger,
Expand All @@ -21,19 +22,7 @@ public function __construct(
*/
public function getConfiguration(): array
{
$path = PathHelper::getRoot() . self::VENDOR_DIR . 'composer.json';

if (!file_exists($path)) {
return [];
}

$json = file_get_contents($path);

if (!$json) {
return [];
}

return json_decode($json, true, flags: \JSON_THROW_ON_ERROR);
return $this->readJsonFile(PathHelper::getRoot() . self::VENDOR_DIR . 'composer.json');
}

/**
Expand All @@ -52,12 +41,36 @@ public function setConfiguration(array $configuration): void
}

file_put_contents($dir . '.gitignore', "*\n");
file_put_contents($dir . 'composer.json', json_encode($configuration, \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR));

$this->writeJsonFile($dir . 'composer.json', $configuration);
}

public function require(string $package, string $version): void
{
$requirements = $this->readJsonFile(PathHelper::getRoot() . self::PATH_CASTOR_REQUIREMENTS);

if (isset($requirements[$package]) && $requirements[$package] === $version) {
$this->logger->debug('The package is already required, no need to run Composer.', [
'package' => $package,
'version' => $version,
]);

return;
}

if (isset($requirements[$package]) && $version !== $requirements[$package]) {
$this->logger->debug('The package is already required but in another version, let\'s empty requirements cache to force Composer re-installation of every package.', [
'package' => $package,
'version' => $version,
]);
$requirements = [];
}

$this->run('require', $package . ':' . $version);

$requirements[$package] = $version;

$this->writeJsonFile(PathHelper::getRoot() . self::PATH_CASTOR_REQUIREMENTS, $requirements);
}

private function run(string ...$args): void
Expand All @@ -83,4 +96,30 @@ private function run(string ...$args): void
'output' => $process->getOutput(),
]);
}

/**
* @return array<string, mixed>
*/
private function readJsonFile(string $path): array
{
if (!file_exists($path)) {
return [];
}

$json = file_get_contents($path);

if (!$json) {
return [];
}

return json_decode($json, true, flags: \JSON_THROW_ON_ERROR);
}

/**
* @param array<string, mixed> $json
*/
private function writeJsonFile(string $path, array $json): void
{
file_put_contents($path, json_encode($json, \JSON_PRETTY_PRINT | \JSON_THROW_ON_ERROR));
}
}

0 comments on commit bc9b6f4

Please sign in to comment.