better support for installing plugins via composer (#5112)

* merge installation and update commands
* generate metadata from array
* new command to list available packages
* added a management script to simplify updates
* added directory for dev files
* helper functions for installation and listing of packages
* run plugin database installers
This commit is contained in:
Kevin Papst
2024-10-14 21:44:42 +02:00
committed by GitHub
parent 255c7d77d6
commit 96043afd6a
18 changed files with 518 additions and 336 deletions

View File

@@ -11,14 +11,13 @@ namespace App\Command;
use App\Constants;
use Doctrine\DBAL\Connection;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
@@ -26,10 +25,10 @@ use Symfony\Component\Console\Style\SymfonyStyle;
*
* @codeCoverageIgnore
*/
#[AsCommand(name: 'kimai:install')]
#[AsCommand(name: 'kimai:install', description: 'Kimai installation command', aliases: ['kimai:update'])]
final class InstallCommand extends Command
{
public function __construct(private Connection $connection, private string $kernelEnvironment)
public function __construct(private readonly Connection $connection)
{
parent::__construct();
}
@@ -37,8 +36,7 @@ final class InstallCommand extends Command
protected function configure(): void
{
$this
->setDescription('Basic installation for Kimai')
->setHelp('This command will perform the basic installation steps to get Kimai up and running.')
->setHelp('This command will perform the installation steps to bootstrap the application, database and plugins.')
->addOption('no-cache', null, InputOption::VALUE_NONE, 'Skip cache re-generation')
;
}
@@ -47,19 +45,23 @@ final class InstallCommand extends Command
{
$io = new SymfonyStyle($input, $output);
$io->title('Kimai installation running ...');
$io->text('Start installation ...');
/** @var Application $application */
$application = $this->getApplication();
$environment = $application->getKernel()->getEnvironment();
// create the database, in case it is not yet existing
try {
$this->createDatabase($io, $input, $output);
// creates the database if it is not yet existing
$this->createDatabase($io, $output);
} catch (\Exception $ex) {
$io->error('Failed to create database: ' . $ex->getMessage());
return Command::FAILURE;
}
// bootstrap database ONLY via doctrine migrations, so all installation will have the correct and same state
try {
// bootstrap database ONLY via doctrine migrations, so all installation will have the same state
$this->importMigrations($io, $output);
} catch (\Exception $ex) {
$io->error('Failed to set migration status: ' . $ex->getMessage());
@@ -68,12 +70,22 @@ final class InstallCommand extends Command
}
if (!$input->getOption('no-cache')) {
// flush the cache, just to make sure ... and ignore result
$this->rebuildCaches($this->kernelEnvironment, $io, $input, $output);
// show manual steps in case this fails
$cacheResult = $this->rebuildCaches($environment, $io, $input, $output);
if ($cacheResult !== Command::SUCCESS) {
$io->warning(
[
'Please run the cache commands manually:',
'bin/console cache:clear --env=' . $environment . PHP_EOL .
'bin/console cache:warmup --env=' . $environment
]
);
}
}
$io->success(
\sprintf('Congratulations! Successfully installed %s version %s', Constants::SOFTWARE, Constants::VERSION)
\sprintf('Successfully installed %s version %s 🎉', Constants::SOFTWARE, Constants::VERSION)
);
return Command::SUCCESS;
@@ -81,11 +93,13 @@ final class InstallCommand extends Command
private function rebuildCaches(string $environment, SymfonyStyle $io, InputInterface $input, OutputInterface $output): int
{
$io->text('Rebuilding your cache, please be patient ...');
$io->text('Rebuilding your cache ...');
$command = $this->getApplication()->find('cache:clear');
try {
$command->run(new ArrayInput(['--env' => $environment]), $output);
if (0 !== $command->run(new ArrayInput(['--env' => $environment]), $output)) {
throw new \RuntimeException('Invalid file permissions?');
}
} catch (\Exception $ex) {
$io->error('Failed to clear cache: ' . $ex->getMessage());
@@ -94,7 +108,9 @@ final class InstallCommand extends Command
$command = $this->getApplication()->find('cache:warmup');
try {
$command->run(new ArrayInput(['--env' => $environment]), $output);
if (0 !== $command->run(new ArrayInput(['--env' => $environment]), $output)) {
throw new \RuntimeException('Invalid file permissions?');
}
} catch (\Exception $ex) {
$io->error('Failed to warmup cache: ' . $ex->getMessage());
@@ -106,15 +122,27 @@ final class InstallCommand extends Command
private function importMigrations(SymfonyStyle $io, OutputInterface $output): void
{
try {
if (!$this->connection->createSchemaManager()->tablesExist(['migration_versions'])) {
throw new \RuntimeException('Migration table does not exist');
}
} catch (\Exception $ex) {
$io->error(['Failed to detect migration status, aborting update.', $ex->getMessage()]);
return;
}
$command = $this->getApplication()->find('doctrine:migrations:migrate');
$cmdInput = new ArrayInput(['--allow-no-migration' => true]);
$cmdInput->setInteractive(false);
$command->run($cmdInput, $output);
$result = $command->run($cmdInput, $output);
$io->writeln('');
if (0 !== $result) {
throw new \Exception('Failed updating database.');
}
}
private function createDatabase(SymfonyStyle $io, InputInterface $input, OutputInterface $output): void
private function createDatabase(SymfonyStyle $io, OutputInterface $output): void
{
try {
if ($this->connection->isConnected()) {
@@ -122,39 +150,17 @@ final class InstallCommand extends Command
return;
}
if (!$this->askConfirmation($input, $output, \sprintf('Create the database "%s" (yes) or skip (no)?', $this->connection->getDatabase()), true)) {
throw new \Exception('Skipped database creation, aborting installation');
}
} catch (\Exception $exception) {
// this likely means that the database does not exist. the latest doctrine release
// changed the behavior: in previous version this code did not throw an exception.
} catch (\Exception $ex) {
// this likely means that the database does not exist and the connection failed
}
$options = ['--if-not-exists' => true];
$command = $this->getApplication()->find('doctrine:database:create');
$result = $command->run(new ArrayInput($options), $output);
$cmdInput = new ArrayInput(['--if-not-exists' => true]);
$cmdInput->setInteractive(false);
$result = $command->run($cmdInput, $output);
if (0 !== $result) {
throw new \Exception('Failed creating database. Check your credentials in DATABASE_URL');
throw new \Exception('Failed creating database: check your DATABASE_URL.');
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @param string $question
* @param bool $default
* @return bool
*/
private function askConfirmation(InputInterface $input, OutputInterface $output, $question, $default = false): bool
{
/** @var QuestionHelper $questionHelper */
$questionHelper = $this->getHelperSet()->get('question');
$text = \sprintf('<info>%s (yes/no)</info> [<comment>%s</comment>]:', $question, $default ? 'yes' : 'no');
$question = new ConfirmationQuestion(' ' . $text . ' ', $default, '/^y|yes/i');
return $questionHelper->ask($input, $output, $question);
}
}

View File

@@ -9,37 +9,130 @@
namespace App\Command;
use App\Plugin\Package;
use App\Plugin\PackageManager;
use App\Plugin\Plugin;
use App\Plugin\PluginManager;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Command used to fetch plugin information.
*/
#[AsCommand(name: 'kimai:plugins')]
#[AsCommand(name: 'kimai:plugins', description: 'Manage Kimai plugins')]
final class PluginCommand extends Command
{
public function __construct(private PluginManager $plugins)
public function __construct(
private readonly PluginManager $pluginManager,
private readonly PackageManager $packageManager
)
{
parent::__construct();
}
protected function configure(): void
{
$this
->setDescription('Receive plugin information')
->setHelp('This command prints detailed plugin information.')
;
$this->setHelp('Shows information about already installed plugins by default.');
$this->addOption('available', null, InputOption::VALUE_NONE, 'Show list of available plugins in ' . PackageManager::PACKAGE_DIR);
$this->addOption('composer', null, InputOption::VALUE_NONE, 'Dump list of available composer packages in ' . PackageManager::PACKAGE_DIR);
$this->addOption('install', null, InputOption::VALUE_NONE, 'Run plugins installer, previously installed via ./kimai.sh');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$plugins = $this->plugins->getPlugins();
if ($input->getOption('available')) {
return $this->listPackages($io, $this->packageManager->getAvailablePackages());
} elseif ($input->getOption('composer')) {
return $this->listComposerPackages($io, $this->packageManager->getAvailablePackages());
} elseif ($input->getOption('install')) {
return $this->installPlugins($io, $output, $this->pluginManager->getPlugins());
}
return $this->listInstalledPlugins($io, $this->pluginManager->getPlugins());
}
/**
* @param Plugin[] $plugins
*/
private function installPlugins(SymfonyStyle $io, OutputInterface $output, array $plugins): int
{
foreach ($plugins as $plugin) {
$config = $plugin->getPath() . '/migrations/doctrine_migrations.yaml';
if (!file_exists($config)) {
$config = $plugin->getPath() . '/Migrations/doctrine_migrations.yaml';
if (!file_exists($config)) {
continue;
}
}
$command = $this->getApplication()?->find('doctrine:migrations:migrate');
if ($command === null) {
throw new \RuntimeException('Failed finding doctrine migrations command');
}
$cmdInput = new ArrayInput(['--allow-no-migration' => true, '--configuration' => $config]);
$cmdInput->setInteractive(false);
if (0 !== $command->run($cmdInput, $output)) {
$io->error('Failed to install bundle database: ' . $config);
}
}
return Command::SUCCESS;
}
/**
* @param Package[] $packages
*/
private function listComposerPackages(SymfonyStyle $io, array $packages): int
{
if (empty($packages)) {
return Command::SUCCESS;
}
$all = [];
foreach ($packages as $package) {
$all[] = $package->getMetadata()->getPackage();
}
$io->write(implode(' ', $all));
return Command::SUCCESS;
}
/**
* @param Package[] $packages
*/
private function listPackages(SymfonyStyle $io, array $packages): int
{
if (empty($packages)) {
$io->warning('No packages to install found');
return Command::SUCCESS;
}
$rows = [];
foreach ($packages as $package) {
$metadata = $package->getMetadata();
$rows[] = [
$metadata->getName(),
$metadata->getVersion(),
$metadata->getKimaiVersion(),
$metadata->getPackage(),
$package->getPackageFile()->getPathname(),
];
}
$io->table(['Name', 'Version', 'Requires', 'Package', 'Directory'], $rows);
return Command::SUCCESS;
}
/**
* @param array<Plugin> $plugins
*/
private function listInstalledPlugins(SymfonyStyle $io, array $plugins): int
{
if (empty($plugins)) {
$io->warning('No plugins installed');

View File

@@ -1,137 +0,0 @@
<?php
/*
* This file is part of the Kimai time-tracking app.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Command;
use App\Constants;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception\ConnectionException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Command used to update a Kimai installation.
*/
#[AsCommand(name: 'kimai:update')]
final class UpdateCommand extends Command
{
public function __construct(private Connection $connection, private string $kernelEnvironment)
{
parent::__construct();
}
protected function configure(): void
{
$this
->setDescription('Update your Kimai installation')
->setHelp('This command will execute all required steps to update your Kimai installation.')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->title('Kimai updates running ...');
$environment = $this->kernelEnvironment;
// make sure database is available, Kimai running and installed
try {
if (!$this->connection->createSchemaManager()->tablesExist(['kimai2_users', 'kimai2_timesheet'])) {
$io->error('Tables missing. Did you run the installer already?');
return Command::FAILURE;
}
if (!$this->connection->createSchemaManager()->tablesExist(['migration_versions'])) {
$io->error('Unknown migration status, aborting database update');
return Command::FAILURE;
}
} catch (ConnectionException $e) {
$io->error(['Database connection could not be established.', $e->getMessage()]);
return Command::FAILURE;
} catch (\Exception $ex) {
$io->error(['Failed to validate database.', $ex->getMessage()]);
return Command::FAILURE;
}
// execute latest doctrine migrations
try {
$command = $this->getApplication()->find('doctrine:migrations:migrate');
$cmdInput = new ArrayInput(['--allow-no-migration' => true]);
$cmdInput->setInteractive(false);
if (0 !== $command->run($cmdInput, $output)) {
throw new \RuntimeException('CRITICAL: problem when migrating database');
}
$io->writeln('');
} catch (\Exception $ex) {
$io->error($ex->getMessage());
return Command::FAILURE;
}
// flush the cache, in case values from the database are cached
$cacheResult = $this->rebuildCaches($environment, $io, $input, $output);
if ($cacheResult !== Command::SUCCESS) {
$io->warning(
[
\sprintf('Updated %s to version %s but the cache could not be rebuilt.', Constants::SOFTWARE, Constants::VERSION),
'Please run the cache commands manually:',
'bin/console cache:clear --env=' . $environment . PHP_EOL .
'bin/console cache:warmup --env=' . $environment
]
);
} else {
$io->success(
\sprintf('Congratulations! Successfully updated %s to version %s', Constants::SOFTWARE, Constants::VERSION)
);
}
return Command::SUCCESS;
}
private function rebuildCaches(string $environment, SymfonyStyle $io, InputInterface $input, OutputInterface $output): int
{
$io->text('Rebuilding your cache, please be patient ...');
$command = $this->getApplication()->find('cache:clear');
try {
if (0 !== $command->run(new ArrayInput(['--env' => $environment]), $output)) {
throw new \RuntimeException('Could not clear cache, missing permissions?');
}
} catch (\Exception $ex) {
$io->error($ex->getMessage());
return Command::FAILURE;
}
$command = $this->getApplication()->find('cache:warmup');
try {
if (0 !== $command->run(new ArrayInput(['--env' => $environment]), $output)) {
throw new \RuntimeException('Could not warmup cache, missing permissions?');
}
} catch (\Exception $ex) {
$io->error($ex->getMessage());
return Command::FAILURE;
}
return Command::SUCCESS;
}
}