Lines 22.41% 13 / 58
Methods 53.84% 7 / 13
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 __construct 0.00% 0 / 1 0.00% 0 / 1 2
 configure 0.00% 0 / 8 0.00% 0 / 1 2
 execute 0.00% 0 / 10 0.00% 0 / 1 30
 prepareDaemon 0.00% 0 / 23 0.00% 0 / 1 20
 noteMissingConfigFile 0.00% 0 / 2 0.00% 0 / 1 6
 logFormatFromOptions 0.00% 0 / 1 0.00% 0 / 1 6
 [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
28final class RunCommand extends StewartCommand
29{
30    public const string NAME = 'run';
31
32    // sysexits EX_TEMPFAIL: the container entrypoint starts the daemon again on the staged release.
33    public const int RESTART_EXIT_CODE = 75;
34
35    public function __construct(
36        private readonly ConfigLoader $config,
37        private readonly AppDiscovery $discovery,
38        private readonly AppInstanceResolver $instances,
39        private readonly AppCatalogResolver $catalogs,
40        private readonly BrokerKernel $brokers,
41        private readonly LoggerFactory $loggers,
42        private readonly CatalogWarnings $catalogWarnings,
43    ) {
44        parent::__construct();
45    }
46
47    protected function configure(): void
48    {
49        parent::configure();
50        $this
51            ->addOption('log-level', 'l', InputOption::VALUE_REQUIRED, 'debug|info|notice|warning|error')
52            ->addOption('json-logs', null, InputOption::VALUE_NONE, 'Emit logs as JSON')
53            ->addOption('only', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Run only this automation, even if disabled; repeat for more')
54            ->addOption('trace', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Log TRACE lines for this automation at any log level; repeat for more')
55            ->addOption('watch', null, InputOption::VALUE_NONE, 'Reload after every saved change to the apps, services.php or stewart.yaml')
56            ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Log actions, event fires and registry edits instead of sending them (ha_calls.dry_run)');
57    }
58
59    protected function execute(InputInterface $input, OutputInterface $output): int
60    {
61        try {
62            $daemon = $this->prepareDaemon($input);
63        } catch (StewartException $e) {
64            $output->writeln('<error>' . $e->getMessage() . '</error>');
65
66            return Command::FAILURE;
67        }
68
69        try {
70            $outcome = $daemon->broker->run();
71        } catch (Throwable $e) {
72            $daemon->logger->error('Stewart stopped', ['exception' => $e]);
73
74            return Command::FAILURE;
75        }
76
77        return match ($outcome) {
78            BrokerStopOutcome::Stopped => Command::SUCCESS,
79            BrokerStopOutcome::RestartRequested => self::RESTART_EXIT_CODE,
80        };
81    }
82
83    /** @throws StewartException */
84    private function prepareDaemon(InputInterface $input): PreparedDaemon
85    {
86        $launch = new DaemonLaunchOptions(
87            $this->findConfigOption($input),
88            $this->readAppSelectionOption($input),
89            $this->nonEmptyStringOption($input, 'log-level'),
90            $input->getOption('watch') === true,
91            $input->getOption('dry-run') === true,
92        );
93        $config = $this->config->loadConfig($launch->configFile, $launch->listConfigOverrides());
94        // Validated before the logger exists, so a missing home_assistant section fails as a config error.
95        $config->requireHomeAssistant();
96        $discovered = $this->instances->resolveInstances($this->discovery->discover(), $config->apps);
97        $selection = $launch->selection;
98        $apps = $this->catalogs->resolveCatalog($discovered, $config->apps, $config->workers, $selection);
99        $verbosity = new LogVerbosityPolicy($config->logLevel, $apps->enabled->listVerbositiesByAppId());
100        $logger = $this->loggers->createDaemonLogger($verbosity, $this->logFormatFromOptions($input, $config->logFormat));
101
102        $this->noteMissingConfigFile($this->config->findMissingDefaultFile($launch->configFile), $logger);
103        $this->catalogWarnings->logCatalogWarnings($discovered, $apps, $this->config->locateConfigFile($launch->configFile), $logger);
104
105        if ($config->haCalls->dryRun) {
106            $logger->warning('ha_calls.dry_run is on: actions, event fires and registry edits are logged, not sent to Home Assistant.');
107        }
108
109        if ($selection->onlyIds !== null) {
110            $logger->notice('Running only the automations named by --only.', ['apps' => $selection->onlyIds->toStrings()]);
111        }
112
113        if ($selection->tracedIds !== null) {
114            $logger->notice('Tracing the automations named by --trace.', ['apps' => $selection->tracedIds->toStrings()]);
115        }
116
117        return new PreparedDaemon($this->brokers->createBroker($config, $apps, $logger, $verbosity, $launch), $logger);
118    }
119
120    private function noteMissingConfigFile(?string $missingConfigFile, LoggerInterface $logger): void
121    {
122        if ($missingConfigFile !== null) {
123            $logger->info('No config file found; using the environment only.', ['config' => $missingConfigFile]);
124        }
125    }
126
127    private function logFormatFromOptions(InputInterface $input, LogFormat $configured): LogFormat
128    {
129        return $input->getOption('json-logs') === true ? LogFormat::Json : $configured;
130    }
131}

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    }