Lines 100.00% 73 / 73
Methods 100.00% 19 / 19
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 configure 100.00% 6 / 6 100.00% 1 / 1 1
 execute 100.00% 10 / 10 100.00% 1 / 1 3
 copySnapshotIfRequested 100.00% 3 / 3 100.00% 1 / 1 2
 generateFromSnapshot 100.00% 5 / 5 100.00% 1 / 1 2
 selectShrinkPolicy 100.00% 1 / 1 100.00% 1 / 1 2
 loadSnapshot 100.00% 5 / 5 100.00% 1 / 1 2
 describeAutoloadMismatch 100.00% 11 / 11 100.00% 1 / 1 2
 printGenerationSummary 100.00% 3 / 3 100.00% 1 / 1 1
 printCheckResult 100.00% 11 / 11 100.00% 1 / 1 3
 printWarnings 100.00% 2 / 2 100.00% 1 / 1 2
 printFailure 100.00% 2 / 2 100.00% 1 / 1 1
 [Stewart\Runtime\Console\StewartCommand] findConfigOption 100.00% 1 / 1 100.00% 1 / 1 1
 [Stewart\Runtime\Console\StewartCommand] readAppSelectionOption 100.00% 1 / 1 100.00% 1 / 1 1
 [Stewart\Runtime\Console\StewartCommand] findAppIdsOption 100.00% 4 / 4 100.00% 1 / 1 4
 [Stewart\Runtime\Console\StewartCommand] nonEmptyStringOption 100.00% 2 / 2 100.00% 1 / 1 3
 [Stewart\Runtime\Console\StewartCommand] writeMissingConfigFileNotice 100.00% 2 / 2 100.00% 1 / 1 2
 [Stewart\Runtime\Console\StewartCommand] writeNotice 100.00% 1 / 1 100.00% 1 / 1 2
 [Stewart\Runtime\Console\StewartCommand] readStringArgument 100.00% 2 / 2 100.00% 1 / 1 2
35final class GenerateCommand extends StewartCommand
36{
37    public const string NAME = 'generate';
38
39    public function __construct(
40        private readonly ConfigLoader $config,
41        private readonly Psr4Map $psr4Map,
42        private readonly ProjectRoot $projectRoot,
43        private readonly LoggerFactory $loggers,
44        private readonly SnapshotFileReader $snapshotReader,
45        private readonly SnapshotFileWriter $snapshotWriter,
46        private readonly SnapshotFetcher $snapshotFetcher,
47        private readonly Generator $generator,
48        private readonly GenerationOptionsFactory $generationOptionsFactory,
49    ) {
50        parent::__construct();
51    }
52
53    protected function configure(): void
54    {
55        parent::configure();
56        $this
57            ->addOption('snapshot-in', null, InputOption::VALUE_REQUIRED, 'Generate from this file instead of connecting')
58            ->addOption('snapshot-out', null, InputOption::VALUE_REQUIRED, 'Write what was read to this file')
59            ->addOption('check', null, InputOption::VALUE_NONE, 'Report what would change and fail if anything would')
60            ->addOption('allow-shrink', null, InputOption::VALUE_NONE, 'Write even if that leaves fewer than half as many generated files');
61    }
62
63    protected function execute(InputInterface $input, OutputInterface $output): int
64    {
65        try {
66            $config = $this->config->loadConfig($this->findConfigOption($input));
67            $mismatch = $this->describeAutoloadMismatch($config->codegen);
68
69            if ($mismatch !== null) {
70                $output->writeln($mismatch);
71
72                return Command::FAILURE;
73            }
74
75            $snapshot = $this->loadSnapshot($input, $config);
76            $this->copySnapshotIfRequested($input, $snapshot);
77
78            return $this->generateFromSnapshot($input, $output, $config->codegen, $snapshot);
79        } catch (StewartException $e) {
80            return $this->printFailure($output, $e->getMessage());
81        }
82    }
83
84    /** @throws StewartException */
85    private function copySnapshotIfRequested(InputInterface $input, Snapshot $snapshot): void
86    {
87        $snapshotOut = $this->nonEmptyStringOption($input, 'snapshot-out');
88
89        if ($snapshotOut !== null) {
90            $this->snapshotWriter->writeSnapshot($snapshotOut, $snapshot);
91        }
92    }
93
94    /** @throws StewartException */
95    private function generateFromSnapshot(InputInterface $input, OutputInterface $output, CodegenConfig $codegen, Snapshot $snapshot): int
96    {
97        $target = new GenerationTarget($codegen->namespace->value, $codegen->outputDir->resolveWithin($this->projectRoot->path));
98        $options = $this->generationOptionsFactory->createFromCodegenConfig($codegen);
99
100        return $input->getOption('check') === true
101            ? $this->printCheckResult($this->generator->checkAgainstSnapshot($snapshot, $target, $options), $output)
102            : $this->printGenerationSummary($this->generator->writeFiles($snapshot, $target, $options, $this->selectShrinkPolicy($input)), $output);
103    }
104
105    private function selectShrinkPolicy(InputInterface $input): ShrinkPolicy
106    {
107        return $input->getOption('allow-shrink') === true ? ShrinkPolicy::Allow : ShrinkPolicy::Refuse;
108    }
109
110    private function loadSnapshot(InputInterface $input, StewartConfig $config): Snapshot
111    {
112        $snapshotIn = $this->nonEmptyStringOption($input, 'snapshot-in');
113        $logger = $this->loggers->createStdoutLogger($config->logLevel, $config->logFormat);
114
115        if ($snapshotIn !== null) {
116            return $this->snapshotReader->readSnapshot($snapshotIn, $logger);
117        }
118
119        return $this->snapshotFetcher->fetchSnapshot($config->requireHomeAssistant(), $logger);
120    }
121
122    private function describeAutoloadMismatch(CodegenConfig $codegen): ?string
123    {
124        $mapped = $this->psr4Map->listPrefixesMappedTo($codegen->outputDir->resolveWithin($this->projectRoot->path));
125
126        if (\in_array($codegen->namespace->value . '\\', $mapped, true)) {
127            return null;
128        }
129
130        return \sprintf(
131            "<error>Composer does not map %s\\ to %s/.</error>\nAdd this to composer.json, then run `make install`:\n\n"
132            . "    \"autoload\": {\n        \"psr-4\": {\n            \"%s\\\\\": \"%s/\"\n        }\n    }\n",
133            $codegen->namespace->value,
134            $codegen->outputDir->value,
135            str_replace('\\', '\\\\', $codegen->namespace->value),
136            $codegen->outputDir->value,
137        );
138    }
139
140    private function printGenerationSummary(GenerationReport $report, OutputInterface $output): int
141    {
142        $this->printWarnings($output, $report->warnings);
143        $output->writeln($report->summary());
144
145        return Command::SUCCESS;
146    }
147
148    private function printCheckResult(CheckResult $result, OutputInterface $output): int
149    {
150        $this->printWarnings($output, $result->warnings);
151
152        if ($result->isClean()) {
153            $output->writeln('<info>The generated classes match Home Assistant.</info>');
154
155            return Command::SUCCESS;
156        }
157
158        $rows = $result->listStaleFiles()->mapToList(
159            static fn(FileChange $change): array => [$change->path, $change->outcome->value],
160        );
161
162        if ($rows !== []) {
163            new Table($output)->setStyle('compact')->setHeaders(['file', 'would be'])->setRows($rows)->render();
164        }
165
166        $output->writeln('<comment>Run `make generate`.</comment>');
167
168        return Command::FAILURE;
169    }
170
171    /** @param list<GenerationWarning> $warnings */
172    private function printWarnings(OutputInterface $output, array $warnings): void
173    {
174        foreach ($warnings as $warning) {
175            $output->writeln('<comment>' . OutputFormatter::escape($warning->describeWarning()) . '</comment>');
176        }
177    }
178
179    private function printFailure(OutputInterface $output, string $message): int
180    {
181        $output->writeln('<error>' . $message . '</error>');
182
183        return Command::FAILURE;
184    }
185}

Inherited from Stewart\Runtime\Console\StewartCommand

24    protected function findConfigOption(InputInterface $input): ?string
25    {
26        return $this->nonEmptyStringOption($input, 'config');
27    }
30    protected function readAppSelectionOption(InputInterface $input): AppSelection
31    {
32        return new AppSelection($this->findAppIdsOption($input, 'only'), $this->findAppIdsOption($input, 'trace'));
33    }
36    private function findAppIdsOption(InputInterface $input, string $name): ?AppIdCollection
37    {
38        $ids = $input->hasOption($name) ? $input->getOption($name) : null;
39
40        if (!\is_array($ids) || $ids === []) {
41            return null;
42        }
43
44        return AppIdCollection::fromList(array_map(static fn(string $id): AppId => new AppId($id), array_values(array_filter($ids, \is_string(...)))));
45    }
47    protected function nonEmptyStringOption(InputInterface $input, string $name): ?string
48    {
49        $value = $input->getOption($name);
50
51        return \is_string($value) && $value !== '' ? $value : null;
52    }
54    protected function writeMissingConfigFileNotice(OutputInterface $output, ?string $missingConfigFile): void
55    {
56        if ($missingConfigFile !== null) {
57            $this->writeNotice($output, \sprintf('No config file at %s; using the environment only.', $missingConfigFile));
58        }
59    }
61    protected function writeNotice(OutputInterface $output, string $notice): void
62    {
63        ($output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output)->writeln('<comment>' . $notice . '</comment>');
64    }
66    protected function readStringArgument(InputInterface $input, string $name): string
67    {
68        $value = $input->getArgument($name);
69
70        return \is_string($value) ? $value : '';
71    }