From 59dc3d7bf75bacf3c4141edff7c09e5e9a40a14f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Glawaty?= Date: Sat, 26 Aug 2023 02:32:21 +0200 Subject: [PATCH] Condig style + Helper command fix - updated Php-Cs-Fixer config - updated coding style - fixed `help` command for cli script --- .php-cs-fixer.dist.php | 130 ++++++--- src/Bridge/Nette/DI/TracyGitVersionConfig.php | 8 +- .../Nette/DI/TracyGitVersionExportConfig.php | 8 +- .../DI/TracyGitVersionExportExtension.php | 96 +++---- .../Nette/DI/TracyGitVersionExtension.php | 245 +++++++++-------- .../Nette/DI/TracyGitVersionPanelConfig.php | 4 +- src/Bridge/Symfony/Console/Application.php | 26 +- .../Command/ExportRepositoryCommand.php | 232 ++++++++-------- src/Bridge/Tracy/Block/BlockInterface.php | 10 +- src/Bridge/Tracy/Block/CurrentStateBlock.php | 32 +-- src/Bridge/Tracy/Block/SimpleTableBlock.php | 36 +-- src/Bridge/Tracy/GitVersionPanel.php | 104 +++---- src/Bridge/Tracy/Helpers.php | 54 ++-- src/Exception/BadMethodCallException.php | 42 +-- src/Exception/ExportConfigException.php | 44 +-- src/Exception/GitDirectoryException.php | 50 ++-- src/Exception/UnhandledCommandException.php | 14 +- src/Export/Config.php | 194 ++++++------- src/Export/ExporterInterface.php | 11 +- src/Export/LocalDirectoryExporter.php | 38 +-- src/Export/PartialExporter/HeadExporter.php | 45 +-- .../PartialExporter/LatestTagExporter.php | 59 ++-- src/Repository/AbstractGitRepository.php | 72 ++--- src/Repository/Command/GetHeadCommand.php | 8 +- .../Command/GetLatestTagCommand.php | 8 +- src/Repository/Entity/CommitHash.php | 26 +- src/Repository/Entity/Head.php | 48 ++-- src/Repository/Entity/Tag.php | 30 +- .../AbstractExportedCommandHandler.php | 44 +-- .../ExportedGitCommandHandlerInterface.php | 8 +- .../CommandHandler/GetHeadCommandHandler.php | 20 +- .../GetLatestTagCommandHandler.php | 20 +- src/Repository/ExportedGitRepository.php | 146 +++++----- src/Repository/GitCommandInterface.php | 2 +- src/Repository/GitRepositoryInterface.php | 36 +-- .../AbstractLocalDirectoryCommandHandler.php | 52 ++-- .../CommandHandler/GetHeadCommandHandler.php | 63 ++--- .../GetLatestTagCommandHandler.php | 83 +++--- ...calDirectoryGitCommandHandlerInterface.php | 2 +- .../LocalDirectory/GitDirectory.php | 158 +++++------ src/Repository/LocalGitRepository.php | 84 +++--- src/Repository/ResolvableGitRepository.php | 102 +++---- src/Repository/RuntimeCachedGitRepository.php | 72 ++--- tests/Bridge/Nette/DI/ContainerFactory.php | 64 ++--- .../DI/TracyGitVersionExportExtensionTest.php | 30 +- .../Nette/DI/TracyGitVersionExtensionTest.php | 40 +-- .../Command/ExportRepositoryCommandTest.phpt | 256 +++++++++--------- tests/Bridge/Tracy/GitVersionPanelTest.php | 26 +- tests/Bridge/Tracy/HelpersTest.php | 16 +- tests/Export/ConfigTest.php | 108 ++++---- tests/Export/LocalDirectoryExporterTest.php | 82 +++--- .../PartialExporter/HeadExporterTest.php | 70 ++--- .../PartialExporter/LatestTagExporterTest.php | 60 ++-- tests/Fixtures/Command/BarCommand.php | 26 +- tests/Fixtures/Command/FooCommand.php | 8 +- .../CommandHandler/BarCommandHandler.php | 14 +- .../ExportedFooCommandHandler.php | 14 +- .../CommandHandler/FooCommandHandler.php | 14 +- .../LocalDirectoryFooCommandHandler.php | 30 +- .../Repository/SimpleGitRepository.php | 32 +-- .../GetHeadCommandHandlerTest.php | 68 ++--- .../GetLatestTagCommandHandlerTest.php | 44 +-- .../Repository/ExportedGitRepositoryTest.phpt | 200 +++++++------- .../GetHeadCommandHandlerTest.php | 50 ++-- .../GetLatestTagCommandHandlerTest.php | 42 +-- .../LocalDirectory/GitDirectoryTest.phpt | 98 +++---- tests/Repository/LocalGitRepositoryTest.phpt | 212 +++++++-------- .../ResolvableGitRepositoryTest.phpt | 208 +++++++------- .../RuntimeCachedGitRepositoryTest.phpt | 116 ++++---- tests/bootstrap.php | 6 +- tracy-git-version | 10 +- 71 files changed, 2276 insertions(+), 2234 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 3623835..9be3678 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -2,7 +2,10 @@ declare(strict_types=1); -$finder = PhpCsFixer\Finder::create() +use PhpCsFixer\Config; +use PhpCsFixer\Finder; + +$finder = Finder::create() ->in(__DIR__ . '/src') ->in(__DIR__ . '/tests') ->name(['*.php', '*.phpt']) @@ -10,42 +13,89 @@ __DIR__ . '/tracy-git-version', ]); -return (new PhpCsFixer\Config()) - ->setUsingCache(false) - ->setIndent("\t") - ->setRules([ - '@PSR2' => true, - 'array_syntax' => ['syntax' => 'short'], - 'trailing_comma_in_multiline' => true, - 'constant_case' => [ - 'case' => 'lower', - ], - 'declare_strict_types' => true, - 'phpdoc_align' => true, - 'blank_line_after_opening_tag' => true, - 'blank_line_before_statement' => [ - 'statements' => ['break', 'continue', 'declare', 'return'], - ], - 'blank_line_after_namespace' => true, - 'single_blank_line_before_namespace' => true, - 'return_type_declaration' => [ - 'space_before' => 'none', - ], - 'ordered_imports' => [ - 'sort_algorithm' => 'length', - 'imports_order' => ['class', 'function', 'const'], - ], - 'no_unused_imports' => true, - 'single_line_after_imports' => true, - 'no_leading_import_slash' => true, - 'global_namespace_import' => [ - 'import_constants' => true, - 'import_functions' => true, - 'import_classes' => true, - ], - 'concat_space' => [ - 'spacing' => 'one', - ], - ]) - ->setRiskyAllowed(true) - ->setFinder($finder); +return (new Config()) + ->setUsingCache(false) + ->setIndent(" ") + ->setRules([ + '@PSR2' => true, + 'array_syntax' => [ + 'syntax' => 'short' + ], + 'trailing_comma_in_multiline' => [ + 'elements' => [ + 'arguments', + 'arrays', + 'match', + 'parameters', + ], + ], + 'constant_case' => [ + 'case' => 'lower', + ], + 'declare_strict_types' => true, + 'phpdoc_align' => true, + 'blank_line_after_opening_tag' => true, + 'blank_line_before_statement' => [ + 'statements' => [ + 'break', + 'continue', + 'declare', + 'return' + ], + ], + 'blank_line_after_namespace' => true, + 'single_blank_line_before_namespace' => true, + 'return_type_declaration' => [ + 'space_before' => 'none', + ], + 'ordered_imports' => [ + 'sort_algorithm' => 'alpha', + 'imports_order' => [ + 'class', + 'function', + 'const' + ], + ], + 'no_unused_imports' => true, + 'single_line_after_imports' => true, + 'no_leading_import_slash' => true, + 'global_namespace_import' => [ + 'import_constants' => true, + 'import_functions' => true, + 'import_classes' => true, + ], + 'fully_qualified_strict_types' => true, + 'concat_space' => [ + 'spacing' => 'one', + ], + 'no_superfluous_phpdoc_tags' => [ + 'allow_mixed' => false, + 'remove_inheritdoc' => true, + 'allow_unused_params' => false, + ], + 'no_empty_phpdoc' => true, + 'no_blank_lines_after_phpdoc' => true, + 'phpdoc_trim_consecutive_blank_line_separation' => true, + 'phpdoc_trim' => true, + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'curly_brace_block', + 'extra', + 'parenthesis_brace_block', + 'return', + 'square_brace_block', + 'throw', + 'use', + ], + ], + 'single_trait_insert_per_statement' => true, + 'single_class_element_per_statement' => [ + 'elements' => [ + 'const', + 'property', + ] + ], + 'function_typehint_space' => true, + ]) + ->setRiskyAllowed(true) + ->setFinder($finder); diff --git a/src/Bridge/Nette/DI/TracyGitVersionConfig.php b/src/Bridge/Nette/DI/TracyGitVersionConfig.php index 151cf93..88da482 100644 --- a/src/Bridge/Nette/DI/TracyGitVersionConfig.php +++ b/src/Bridge/Nette/DI/TracyGitVersionConfig.php @@ -8,10 +8,10 @@ final class TracyGitVersionConfig { - public string $source_name; + public string $source_name; - /** @var array */ - public array $command_handlers; + /** @var array */ + public array $command_handlers; - public TracyGitVersionPanelConfig $panel; + public TracyGitVersionPanelConfig $panel; } diff --git a/src/Bridge/Nette/DI/TracyGitVersionExportConfig.php b/src/Bridge/Nette/DI/TracyGitVersionExportConfig.php index f658df0..55d154e 100644 --- a/src/Bridge/Nette/DI/TracyGitVersionExportConfig.php +++ b/src/Bridge/Nette/DI/TracyGitVersionExportConfig.php @@ -8,10 +8,10 @@ final class TracyGitVersionExportConfig { - public string $source_name; + public string $source_name; - public string $export_filename; + public string $export_filename; - /** @var array */ - public array $command_handlers; + /** @var array */ + public array $command_handlers; } diff --git a/src/Bridge/Nette/DI/TracyGitVersionExportExtension.php b/src/Bridge/Nette/DI/TracyGitVersionExportExtension.php index 59929d6..8e3ef87 100644 --- a/src/Bridge/Nette/DI/TracyGitVersionExportExtension.php +++ b/src/Bridge/Nette/DI/TracyGitVersionExportExtension.php @@ -4,67 +4,67 @@ namespace SixtyEightPublishers\TracyGitVersion\Bridge\Nette\DI; -use RuntimeException; -use Nette\Schema\Expect; -use Nette\Schema\Schema; use Nette\DI\CompilerExtension; use Nette\DI\Definitions\Statement; -use SixtyEightPublishers\TracyGitVersion\Repository\ExportedGitRepository; +use Nette\Schema\Expect; +use Nette\Schema\Schema; +use RuntimeException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\GetHeadCommandHandler; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\GetLatestTagCommandHandler; -use function count; +use SixtyEightPublishers\TracyGitVersion\Repository\ExportedGitRepository; +use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; +use function array_map; use function assert; +use function count; use function sprintf; -use function array_map; final class TracyGitVersionExportExtension extends CompilerExtension { - public function getConfigSchema(): Schema - { - $tempDir = $this->getContainerBuilder()->parameters['tempDir'] ?? null; + public function getConfigSchema(): Schema + { + $tempDir = $this->getContainerBuilder()->parameters['tempDir'] ?? null; - return Expect::structure([ - 'source_name' => Expect::string(GitRepositoryInterface::SOURCE_EXPORT), - 'export_filename' => Expect::string($tempDir ? $tempDir . '/git-version/repository.json' : null)->required(null === $tempDir), - 'command_handlers' => Expect::arrayOf(Expect::anyOf(Expect::type(Statement::class), Expect::string()), 'string') - ->default([ - GetHeadCommand::class => new Statement(GetHeadCommandHandler::class), - GetLatestTagCommand::class => new Statement(GetLatestTagCommandHandler::class), - ]) - ->mergeDefaults() - ->before(static function (array $items) { - return array_map(static function ($item) { - return $item instanceof Statement ? $item : new Statement($item); - }, $items); - }), - ])->castTo(TracyGitVersionExportConfig::class); - } + return Expect::structure([ + 'source_name' => Expect::string(GitRepositoryInterface::SOURCE_EXPORT), + 'export_filename' => Expect::string($tempDir ? $tempDir . '/git-version/repository.json' : null)->required(null === $tempDir), + 'command_handlers' => Expect::arrayOf(Expect::anyOf(Expect::type(Statement::class), Expect::string()), 'string') + ->default([ + GetHeadCommand::class => new Statement(GetHeadCommandHandler::class), + GetLatestTagCommand::class => new Statement(GetLatestTagCommandHandler::class), + ]) + ->mergeDefaults() + ->before(static function (array $items) { + return array_map(static function ($item) { + return $item instanceof Statement ? $item : new Statement($item); + }, $items); + }), + ])->castTo(TracyGitVersionExportConfig::class); + } - public function loadConfiguration(): void - { - if (0 >= count($this->compiler->getExtensions(TracyGitVersionExtension::class))) { - throw new RuntimeException(sprintf( - 'The extension %s can be used only with %s.', - self::class, - TracyGitVersionExtension::class - )); - } + public function loadConfiguration(): void + { + if (0 >= count($this->compiler->getExtensions(TracyGitVersionExtension::class))) { + throw new RuntimeException(sprintf( + 'The extension %s can be used only with %s.', + self::class, + TracyGitVersionExtension::class, + )); + } - $builder = $this->getContainerBuilder(); - $config = $this->getConfig(); - assert($config instanceof TracyGitVersionExportConfig); + $builder = $this->getContainerBuilder(); + $config = $this->getConfig(); + assert($config instanceof TracyGitVersionExportConfig); - # exported git repository - $builder->addDefinition($this->prefix('git_repository.exported')) - ->setAutowired(false) - ->setFactory(ExportedGitRepository::class, [ - 'file' => $config->export_filename, - 'handlers' => $config->command_handlers, - 'source' => $config->source_name, - ]) - ->addTag(TracyGitVersionExtension::TAG_GIT_REPOSITORY, 50); - } + # exported git repository + $builder->addDefinition($this->prefix('git_repository.exported')) + ->setAutowired(false) + ->setFactory(ExportedGitRepository::class, [ + 'file' => $config->export_filename, + 'handlers' => $config->command_handlers, + 'source' => $config->source_name, + ]) + ->addTag(TracyGitVersionExtension::TAG_GIT_REPOSITORY, 50); + } } diff --git a/src/Bridge/Nette/DI/TracyGitVersionExtension.php b/src/Bridge/Nette/DI/TracyGitVersionExtension.php index bd86aa1..6bb052f 100644 --- a/src/Bridge/Nette/DI/TracyGitVersionExtension.php +++ b/src/Bridge/Nette/DI/TracyGitVersionExtension.php @@ -4,140 +4,137 @@ namespace SixtyEightPublishers\TracyGitVersion\Bridge\Nette\DI; -use Tracy\Bar; -use Nette\Schema\Expect; -use Nette\Schema\Schema; use Nette\DI\CompilerExtension; -use Nette\DI\Definitions\Statement; use Nette\DI\Definitions\ServiceDefinition; +use Nette\DI\Definitions\Statement; +use Nette\Schema\Expect; +use Nette\Schema\Schema; +use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Block\CurrentStateBlock; use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\GitVersionPanel; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; -use SixtyEightPublishers\TracyGitVersion\Repository\ResolvableGitRepository; -use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Block\CurrentStateBlock; -use SixtyEightPublishers\TracyGitVersion\Repository\RuntimeCachedGitRepository; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetHeadCommandHandler; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetLatestTagCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; +use SixtyEightPublishers\TracyGitVersion\Repository\ResolvableGitRepository; +use SixtyEightPublishers\TracyGitVersion\Repository\RuntimeCachedGitRepository; +use Tracy\Bar; +use function array_keys; +use function array_map; use function arsort; use function assert; -use function array_map; -use function array_keys; final class TracyGitVersionExtension extends CompilerExtension { - public const TAG_GIT_REPOSITORY = '68publishers.tracy_git_version_panel.tag.git_repository'; - - public function getConfigSchema(): Schema - { - return Expect::structure([ - 'source_name' => Expect::string(GitRepositoryInterface::SOURCE_GIT_DIRECTORY), - 'command_handlers' => Expect::arrayOf(Expect::anyOf(Expect::type(Statement::class), Expect::string()), 'string') - ->default([ - GetHeadCommand::class => new Statement(GetHeadCommandHandler::class), - GetLatestTagCommand::class => new Statement(GetLatestTagCommandHandler::class), - ]) - ->mergeDefaults() - ->before(static function (array $items) { - return array_map(static function ($item) { - return $item instanceof Statement ? $item : new Statement($item); - }, $items); - }), - 'panel' => Expect::structure([ - 'blocks' => Expect::listOf(Expect::anyOf(Expect::type(Statement::class), Expect::string())) - ->default([ - new Statement(CurrentStateBlock::class), - ]) - ->mergeDefaults() - ->before(static function (array $items) { - return array_map(static function ($item) { - return $item instanceof Statement ? $item : new Statement($item); - }, $items); - }), - ])->castTo(TracyGitVersionPanelConfig::class), - ])->castTo(TracyGitVersionConfig::class); - } - - public function loadConfiguration(): void - { - $builder = $this->getContainerBuilder(); - $config = $this->getConfig(); - assert($config instanceof TracyGitVersionConfig); - - # default git repository service - $builder->addDefinition($this->prefix('git_repository')) - ->setAutowired(GitRepositoryInterface::class) - ->setType(GitRepositoryInterface::class) - ->setFactory($this->prefix('@git_repository.runtime_cached')); - - # runtime cached git repository - $builder->addDefinition($this->prefix('git_repository.runtime_cached')) - ->setAutowired(false) - ->setFactory(RuntimeCachedGitRepository::class, [$this->prefix('@git_repository.resolvable')]); - - # resolvable git repository - $builder->addDefinition($this->prefix('git_repository.resolvable')) - ->setAutowired(false) - ->setType(ResolvableGitRepository::class); - - # local directory git repository - $builder->addDefinition($this->prefix('git_repository.local_directory')) - ->setAutowired(false) - ->setFactory(LocalGitRepository::class, [ - 'gitDirectory' => new Statement([GitDirectory::class, 'createAutoDetected']), - 'handlers' => $config->command_handlers, - 'source' => $config->source_name, - ]) - ->addTag(self::TAG_GIT_REPOSITORY, 100); - } - - /** - * {@inheritDoc} - */ - public function beforeCompile(): void - { - $builder = $this->getContainerBuilder(); - $config = $this->getConfig(); - assert($config instanceof TracyGitVersionConfig); - - # pass git repositories into resolvable repository - $resolvableGitRepository = $builder->getDefinition($this->prefix('git_repository.resolvable')); - assert($resolvableGitRepository instanceof ServiceDefinition); - - $repositories = array_map('intval', $builder->findByTag(self::TAG_GIT_REPOSITORY)); - - arsort($repositories); - - $resolvableGitRepository->setArguments([ - array_map(static fn (string $serviceName): string => '@' . $serviceName, array_keys($repositories)), - ]); - - # add panel into Tracy - if (!$this->isDebugMode()) { - return; - } - - $barServiceName = $builder->getByType(Bar::class, false); - - if (null === $barServiceName) { - return; - } - - $barService = $builder->getDefinition($barServiceName); - assert($barService instanceof ServiceDefinition); - - $barService->addSetup('addPanel', [ - new Statement(GitVersionPanel::class, [ - $this->prefix('@git_repository'), - $config->panel->blocks, - ]), - ]); - } - - private function isDebugMode(): bool - { - return $this->getContainerBuilder()->parameters['debugMode'] ?? false; - } + public const TAG_GIT_REPOSITORY = '68publishers.tracy_git_version_panel.tag.git_repository'; + + public function getConfigSchema(): Schema + { + return Expect::structure([ + 'source_name' => Expect::string(GitRepositoryInterface::SOURCE_GIT_DIRECTORY), + 'command_handlers' => Expect::arrayOf(Expect::anyOf(Expect::type(Statement::class), Expect::string()), 'string') + ->default([ + GetHeadCommand::class => new Statement(GetHeadCommandHandler::class), + GetLatestTagCommand::class => new Statement(GetLatestTagCommandHandler::class), + ]) + ->mergeDefaults() + ->before(static function (array $items) { + return array_map(static function ($item) { + return $item instanceof Statement ? $item : new Statement($item); + }, $items); + }), + 'panel' => Expect::structure([ + 'blocks' => Expect::listOf(Expect::anyOf(Expect::type(Statement::class), Expect::string())) + ->default([ + new Statement(CurrentStateBlock::class), + ]) + ->mergeDefaults() + ->before(static function (array $items) { + return array_map(static function ($item) { + return $item instanceof Statement ? $item : new Statement($item); + }, $items); + }), + ])->castTo(TracyGitVersionPanelConfig::class), + ])->castTo(TracyGitVersionConfig::class); + } + + public function loadConfiguration(): void + { + $builder = $this->getContainerBuilder(); + $config = $this->getConfig(); + assert($config instanceof TracyGitVersionConfig); + + # default git repository service + $builder->addDefinition($this->prefix('git_repository')) + ->setAutowired(GitRepositoryInterface::class) + ->setType(GitRepositoryInterface::class) + ->setFactory($this->prefix('@git_repository.runtime_cached')); + + # runtime cached git repository + $builder->addDefinition($this->prefix('git_repository.runtime_cached')) + ->setAutowired(false) + ->setFactory(RuntimeCachedGitRepository::class, [$this->prefix('@git_repository.resolvable')]); + + # resolvable git repository + $builder->addDefinition($this->prefix('git_repository.resolvable')) + ->setAutowired(false) + ->setType(ResolvableGitRepository::class); + + # local directory git repository + $builder->addDefinition($this->prefix('git_repository.local_directory')) + ->setAutowired(false) + ->setFactory(LocalGitRepository::class, [ + 'gitDirectory' => new Statement([GitDirectory::class, 'createAutoDetected']), + 'handlers' => $config->command_handlers, + 'source' => $config->source_name, + ]) + ->addTag(self::TAG_GIT_REPOSITORY, 100); + } + + public function beforeCompile(): void + { + $builder = $this->getContainerBuilder(); + $config = $this->getConfig(); + assert($config instanceof TracyGitVersionConfig); + + # pass git repositories into resolvable repository + $resolvableGitRepository = $builder->getDefinition($this->prefix('git_repository.resolvable')); + assert($resolvableGitRepository instanceof ServiceDefinition); + + $repositories = array_map('intval', $builder->findByTag(self::TAG_GIT_REPOSITORY)); + + arsort($repositories); + + $resolvableGitRepository->setArguments([ + array_map(static fn (string $serviceName): string => '@' . $serviceName, array_keys($repositories)), + ]); + + # add panel into Tracy + if (!$this->isDebugMode()) { + return; + } + + $barServiceName = $builder->getByType(Bar::class, false); + + if (null === $barServiceName) { + return; + } + + $barService = $builder->getDefinition($barServiceName); + assert($barService instanceof ServiceDefinition); + + $barService->addSetup('addPanel', [ + new Statement(GitVersionPanel::class, [ + $this->prefix('@git_repository'), + $config->panel->blocks, + ]), + ]); + } + + private function isDebugMode(): bool + { + return $this->getContainerBuilder()->parameters['debugMode'] ?? false; + } } diff --git a/src/Bridge/Nette/DI/TracyGitVersionPanelConfig.php b/src/Bridge/Nette/DI/TracyGitVersionPanelConfig.php index d079d96..befcf91 100644 --- a/src/Bridge/Nette/DI/TracyGitVersionPanelConfig.php +++ b/src/Bridge/Nette/DI/TracyGitVersionPanelConfig.php @@ -8,6 +8,6 @@ final class TracyGitVersionPanelConfig { - /** @var array */ - public array $blocks; + /** @var array */ + public array $blocks; } diff --git a/src/Bridge/Symfony/Console/Application.php b/src/Bridge/Symfony/Console/Application.php index ed407f4..f9def7d 100644 --- a/src/Bridge/Symfony/Console/Application.php +++ b/src/Bridge/Symfony/Console/Application.php @@ -4,24 +4,24 @@ namespace SixtyEightPublishers\TracyGitVersion\Bridge\Symfony\Console; -use PhpCsFixer\Console\Command\HelpCommand; -use Symfony\Component\Console\Command\ListCommand; -use Symfony\Component\Console\Application as BaseApplication; use SixtyEightPublishers\TracyGitVersion\Bridge\Symfony\Console\Command\ExportRepositoryCommand; +use Symfony\Component\Console\Application as BaseApplication; +use Symfony\Component\Console\Command\HelpCommand; +use Symfony\Component\Console\Command\ListCommand; final class Application extends BaseApplication { - private const VERSION = '1.0'; + private const VERSION = '1.0'; - public function __construct() - { - parent::__construct('Tracy git version panel', self::VERSION); + public function __construct() + { + parent::__construct('Tracy git version panel', self::VERSION); - $this->add(new ExportRepositoryCommand()); - } + $this->add(new ExportRepositoryCommand()); + } - protected function getDefaultCommands(): array - { - return [new HelpCommand(), new ListCommand()]; - } + protected function getDefaultCommands(): array + { + return [new HelpCommand(), new ListCommand()]; + } } diff --git a/src/Bridge/Symfony/Console/Command/ExportRepositoryCommand.php b/src/Bridge/Symfony/Console/Command/ExportRepositoryCommand.php index 8f2d27e..27d7245 100644 --- a/src/Bridge/Symfony/Console/Command/ExportRepositoryCommand.php +++ b/src/Bridge/Symfony/Console/Command/ExportRepositoryCommand.php @@ -6,131 +6,131 @@ use JsonException; use RuntimeException; +use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; +use SixtyEightPublishers\TracyGitVersion\Export\Config; +use SixtyEightPublishers\TracyGitVersion\Export\LocalDirectoryExporter; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Logger\ConsoleLogger; use Symfony\Component\Console\Output\OutputInterface; -use SixtyEightPublishers\TracyGitVersion\Export\Config; -use SixtyEightPublishers\TracyGitVersion\Export\LocalDirectoryExporter; -use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; -use function chmod; -use function mkdir; use function assert; -use function is_dir; +use function chmod; use function dirname; -use function sprintf; -use function is_string; use function file_exists; -use function json_encode; use function file_put_contents; +use function is_dir; +use function is_string; +use function json_encode; +use function mkdir; +use function sprintf; final class ExportRepositoryCommand extends Command { - protected static $defaultName = 'export-repository'; - - protected function configure(): void - { - $this->setDescription('Clones important things from a git repository to the output directory.') - ->addOption('config', null, InputOption::VALUE_REQUIRED, 'The path to a config file.') - ->addOption('output-file', null, InputOption::VALUE_REQUIRED, 'The filename of the output file.') - ->addOption('dump-only', null, InputOption::VALUE_NONE, 'Dumps exported file into the console only.'); - } - - /** - * @throws JsonException - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException - */ - protected function execute(InputInterface $input, OutputInterface $output): int - { - $logger = new ConsoleLogger($output); - $outputFile = $input->getOption('output-file'); - $dumpOnly = $input->getOption('dump-only'); - - $configPath = $input->getOption('config'); - assert(null === $configPath || is_string($configPath)); - $config = $this->getConfig($configPath); - - if (is_string($outputFile)) { - $config->setOutputFile($outputFile); - } - - $export = (new LocalDirectoryExporter())->export($config, null); - - $pretty = $dumpOnly ? JSON_PRETTY_PRINT : 0; - $json = json_encode($export, JSON_THROW_ON_ERROR | $pretty); - - if ($dumpOnly) { - $output->writeln($json); - - return 0; - } - - $outputFile = $config->getOption(Config::OPTION_OUTPUT_FILE); - assert(is_string($outputFile)); - - $this->writeExport($json, $outputFile); - - $logger->info(sprintf( - 'Repository has been successfully exported into %s.', - $outputFile - )); - - return 0; - } - - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException - */ - private function getConfig(?string $configFile): Config - { - return null !== $configFile ? $this->loadConfig($configFile) : Config::createDefault(); - } - - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException - */ - private function loadConfig(string $configFile): Config - { - if (!file_exists($configFile)) { - throw ExportConfigException::configFileNotFound($configFile); - } - - $config = include $configFile; - - if (!$config instanceof Config) { - throw ExportConfigException::configCantBeLoadedFromFile($configFile); - } - - return $config; - } - - /** - * @throws RuntimeException - */ - private function writeExport(string $export, string $outputFile): void - { - $dir = dirname($outputFile); - - if (!is_dir($dir) && !@mkdir($dir, 0777, true) && !is_dir($dir)) { - throw new RuntimeException(sprintf( - 'Unable to create directory %s', - $dir - )); - } - - if (false === @file_put_contents($outputFile, $export)) { - throw new RuntimeException(sprintf( - 'Unable to write config into file %s', - $outputFile - )); - } - - if (false === @chmod($outputFile, 0666)) { - throw new RuntimeException(sprintf( - 'Unable to chmod config file %s with mode 0666.', - $outputFile - )); - } - } + protected static $defaultName = 'export-repository'; + + protected function configure(): void + { + $this->setDescription('Clones important things from a git repository to the output directory.') + ->addOption('config', null, InputOption::VALUE_REQUIRED, 'The path to a config file.') + ->addOption('output-file', null, InputOption::VALUE_REQUIRED, 'The filename of the output file.') + ->addOption('dump-only', null, InputOption::VALUE_NONE, 'Dumps exported file into the console only.'); + } + + /** + * @throws JsonException + * @throws ExportConfigException + */ + protected function execute(InputInterface $input, OutputInterface $output): int + { + $logger = new ConsoleLogger($output); + $outputFile = $input->getOption('output-file'); + $dumpOnly = $input->getOption('dump-only'); + + $configPath = $input->getOption('config'); + assert(null === $configPath || is_string($configPath)); + $config = $this->getConfig($configPath); + + if (is_string($outputFile)) { + $config->setOutputFile($outputFile); + } + + $export = (new LocalDirectoryExporter())->export($config, null); + + $pretty = $dumpOnly ? JSON_PRETTY_PRINT : 0; + $json = json_encode($export, JSON_THROW_ON_ERROR | $pretty); + + if ($dumpOnly) { + $output->writeln($json); + + return 0; + } + + $outputFile = $config->getOption(Config::OPTION_OUTPUT_FILE); + assert(is_string($outputFile)); + + $this->writeExport($json, $outputFile); + + $logger->info(sprintf( + 'Repository has been successfully exported into %s.', + $outputFile, + )); + + return 0; + } + + /** + * @throws ExportConfigException + */ + private function getConfig(?string $configFile): Config + { + return null !== $configFile ? $this->loadConfig($configFile) : Config::createDefault(); + } + + /** + * @throws ExportConfigException + */ + private function loadConfig(string $configFile): Config + { + if (!file_exists($configFile)) { + throw ExportConfigException::configFileNotFound($configFile); + } + + $config = include $configFile; + + if (!$config instanceof Config) { + throw ExportConfigException::configCantBeLoadedFromFile($configFile); + } + + return $config; + } + + /** + * @throws RuntimeException + */ + private function writeExport(string $export, string $outputFile): void + { + $dir = dirname($outputFile); + + if (!is_dir($dir) && !@mkdir($dir, 0777, true) && !is_dir($dir)) { + throw new RuntimeException(sprintf( + 'Unable to create directory %s', + $dir, + )); + } + + if (false === @file_put_contents($outputFile, $export)) { + throw new RuntimeException(sprintf( + 'Unable to write config into file %s', + $outputFile, + )); + } + + if (false === @chmod($outputFile, 0666)) { + throw new RuntimeException(sprintf( + 'Unable to chmod config file %s with mode 0666.', + $outputFile, + )); + } + } } diff --git a/src/Bridge/Tracy/Block/BlockInterface.php b/src/Bridge/Tracy/Block/BlockInterface.php index d2385d1..e7fa8fe 100644 --- a/src/Bridge/Tracy/Block/BlockInterface.php +++ b/src/Bridge/Tracy/Block/BlockInterface.php @@ -4,13 +4,13 @@ namespace SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Block; -use Throwable; use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; +use Throwable; interface BlockInterface { - /** - * @throws Throwable - */ - public function render(GitRepositoryInterface $gitRepository): string; + /** + * @throws Throwable + */ + public function render(GitRepositoryInterface $gitRepository): string; } diff --git a/src/Bridge/Tracy/Block/CurrentStateBlock.php b/src/Bridge/Tracy/Block/CurrentStateBlock.php index 35f3f69..4d6752c 100644 --- a/src/Bridge/Tracy/Block/CurrentStateBlock.php +++ b/src/Bridge/Tracy/Block/CurrentStateBlock.php @@ -4,30 +4,30 @@ namespace SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Block; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; +use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use function assert; use function sprintf; final class CurrentStateBlock implements BlockInterface { - public function render(GitRepositoryInterface $gitRepository): string - { - $head = $gitRepository->supports(GetHeadCommand::class) ? $gitRepository->handle(new GetHeadCommand()) : new Head(null, null); - $latestTag = $gitRepository->supports(GetLatestTagCommand::class) ? $gitRepository->handle(new GetLatestTagCommand()) : null; - assert($head instanceof Head && (null === $latestTag || $latestTag instanceof Tag)); + public function render(GitRepositoryInterface $gitRepository): string + { + $head = $gitRepository->supports(GetHeadCommand::class) ? $gitRepository->handle(new GetHeadCommand()) : new Head(null, null); + $latestTag = $gitRepository->supports(GetLatestTagCommand::class) ? $gitRepository->handle(new GetLatestTagCommand()) : null; + assert($head instanceof Head && (null === $latestTag || $latestTag instanceof Tag)); - $isHeadOnLatestTag = $latestTag instanceof Tag && null !== $head->getCommitHash() && $head->getCommitHash()->compare($latestTag->getCommitHash()); + $isHeadOnLatestTag = $latestTag instanceof Tag && null !== $head->getCommitHash() && $head->getCommitHash()->compare($latestTag->getCommitHash()); - $block = new SimpleTableBlock([ - 'Branch' => $head->getBranch() ?? ($head->isDetached() ? 'detached' : 'not versioned'), - 'Commit' => null !== $head->getCommitHash() ? $head->getCommitHash()->getValue() : 'not versioned', - 'Latest tag' => $latestTag instanceof Tag ? sprintf('%s (%s)', $latestTag->getName(), $isHeadOnLatestTag ? 'current commit' : 'last known') : 'unknown', - ], 'Current state'); + $block = new SimpleTableBlock([ + 'Branch' => $head->getBranch() ?? ($head->isDetached() ? 'detached' : 'not versioned'), + 'Commit' => null !== $head->getCommitHash() ? $head->getCommitHash()->getValue() : 'not versioned', + 'Latest tag' => $latestTag instanceof Tag ? sprintf('%s (%s)', $latestTag->getName(), $isHeadOnLatestTag ? 'current commit' : 'last known') : 'unknown', + ], 'Current state'); - return $block->render($gitRepository); - } + return $block->render($gitRepository); + } } diff --git a/src/Bridge/Tracy/Block/SimpleTableBlock.php b/src/Bridge/Tracy/Block/SimpleTableBlock.php index 8c7f64f..ab53cdf 100644 --- a/src/Bridge/Tracy/Block/SimpleTableBlock.php +++ b/src/Bridge/Tracy/Block/SimpleTableBlock.php @@ -9,25 +9,25 @@ final class SimpleTableBlock implements BlockInterface { - /** @var array */ - private array $rows; + /** @var array */ + private array $rows; - private ?string $caption; + private ?string $caption; - /** - * @param array $rows - */ - public function __construct(array $rows, ?string $caption = null) - { - $this->rows = $rows; - $this->caption = $caption; - } + /** + * @param array $rows + */ + public function __construct(array $rows, ?string $caption = null) + { + $this->rows = $rows; + $this->caption = $caption; + } - public function render(GitRepositoryInterface $gitRepository): string - { - return Helpers::renderTemplate(__DIR__ . '/../templates/SimpleTable.block.phtml', [ - 'caption' => $this->caption, - 'rows' => $this->rows, - ]); - } + public function render(GitRepositoryInterface $gitRepository): string + { + return Helpers::renderTemplate(__DIR__ . '/../templates/SimpleTable.block.phtml', [ + 'caption' => $this->caption, + 'rows' => $this->rows, + ]); + } } diff --git a/src/Bridge/Tracy/GitVersionPanel.php b/src/Bridge/Tracy/GitVersionPanel.php index 3a89e54..ac37d1a 100644 --- a/src/Bridge/Tracy/GitVersionPanel.php +++ b/src/Bridge/Tracy/GitVersionPanel.php @@ -4,72 +4,72 @@ namespace SixtyEightPublishers\TracyGitVersion\Bridge\Tracy; -use Throwable; -use Tracy\IBarPanel; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Block\BlockInterface; -use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Block\CurrentStateBlock; use SixtyEightPublishers\TracyGitVersion\Repository\GitCommandHandlerInterface; +use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; use SixtyEightPublishers\TracyGitVersion\Repository\RuntimeCachedGitRepository; +use Throwable; +use Tracy\IBarPanel; final class GitVersionPanel implements IBarPanel { - private GitRepositoryInterface $gitRepository; + private GitRepositoryInterface $gitRepository; - /** @var array */ - private array $blocks; + /** @var array */ + private array $blocks; - /** - * @param array $blocks - */ - public function __construct(GitRepositoryInterface $gitRepository, array $blocks) - { - $this->gitRepository = $gitRepository; - $this->blocks = (static fn (BlockInterface ...$blocks): array => $blocks)(...$blocks); - } + /** + * @param array $blocks + */ + public function __construct(GitRepositoryInterface $gitRepository, array $blocks) + { + $this->gitRepository = $gitRepository; + $this->blocks = (static fn (BlockInterface ...$blocks): array => $blocks)(...$blocks); + } - /** - * @param array $handlers - */ - public static function createDefault(?string $workingDirectory = null, string $directoryName = '.git', array $handlers = []): self - { - $repository = new RuntimeCachedGitRepository(LocalGitRepository::createDefault($workingDirectory, $directoryName)); + /** + * @param array $handlers + */ + public static function createDefault(?string $workingDirectory = null, string $directoryName = '.git', array $handlers = []): self + { + $repository = new RuntimeCachedGitRepository(LocalGitRepository::createDefault($workingDirectory, $directoryName)); - foreach ($handlers as $command => $handler) { - $repository->addHandler($command, $handler); - } + foreach ($handlers as $command => $handler) { + $repository->addHandler($command, $handler); + } - return new self($repository, [ - new CurrentStateBlock(), - ]); - } + return new self($repository, [ + new CurrentStateBlock(), + ]); + } - public function addBlock(BlockInterface $block): self - { - $this->blocks[] = $block; + public function addBlock(BlockInterface $block): self + { + $this->blocks[] = $block; - return $this; - } + return $this; + } - /** - * @throws Throwable - */ - public function getTab(): string - { - return Helpers::renderTemplate(__DIR__ . '/templates/GitVersionPanel.tab.phtml', [ - 'gitRepository' => $this->gitRepository, - ]); - } + /** + * @throws Throwable + */ + public function getTab(): string + { + return Helpers::renderTemplate(__DIR__ . '/templates/GitVersionPanel.tab.phtml', [ + 'gitRepository' => $this->gitRepository, + ]); + } - /** - * @throws Throwable - */ - public function getPanel(): string - { - return Helpers::renderTemplate(__DIR__ . '/templates/GitVersionPanel.panel.phtml', [ - 'gitRepository' => $this->gitRepository, - 'blocks' => $this->blocks, - ]); - } + /** + * @throws Throwable + */ + public function getPanel(): string + { + return Helpers::renderTemplate(__DIR__ . '/templates/GitVersionPanel.panel.phtml', [ + 'gitRepository' => $this->gitRepository, + 'blocks' => $this->blocks, + ]); + } } diff --git a/src/Bridge/Tracy/Helpers.php b/src/Bridge/Tracy/Helpers.php index 53906cf..c6f6480 100644 --- a/src/Bridge/Tracy/Helpers.php +++ b/src/Bridge/Tracy/Helpers.php @@ -6,36 +6,36 @@ use Throwable; use function extract; -use function ob_start; use function ob_end_clean; use function ob_get_clean; +use function ob_start; final class Helpers { - private function __construct() - { - } - - /** - * @param array $params - * - * @throws Throwable - */ - public static function renderTemplate(string $templatePath, array $params = []): string - { - ob_start(static function () { - }); - - try { - extract($params, EXTR_OVERWRITE); - - require $templatePath; - - return (string) ob_get_clean(); - } catch (Throwable $e) { - ob_end_clean(); - - throw $e; - } - } + private function __construct() + { + } + + /** + * @param array $params + * + * @throws Throwable + */ + public static function renderTemplate(string $templatePath, array $params = []): string + { + ob_start(static function () { + }); + + try { + extract($params, EXTR_OVERWRITE); + + require $templatePath; + + return (string) ob_get_clean(); + } catch (Throwable $e) { + ob_end_clean(); + + throw $e; + } + } } diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index fc94526..b2ea79f 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -6,30 +6,30 @@ use SixtyEightPublishers\TracyGitVersion\Export\ExporterInterface; use SixtyEightPublishers\TracyGitVersion\Repository\ResolvableGitRepository; -use function sprintf; use function get_class; +use function sprintf; final class BadMethodCallException extends \BadMethodCallException implements ExceptionInterface { - public static function gitRepositoryNotProvidedForPartialExporter(ExporterInterface $exporter): self - { - return new self(sprintf( - 'Git repository for a partial exporter %s must be provided.', - get_class($exporter) - )); - } + public static function gitRepositoryNotProvidedForPartialExporter(ExporterInterface $exporter): self + { + return new self(sprintf( + 'Git repository for a partial exporter %s must be provided.', + get_class($exporter), + )); + } - /** - * @param class-string $commandClassname - * @param class-string $handlerClassname - */ - public static function cantAddHandlerToResolvableGitRepository(string $commandClassname, string $handlerClassname): self - { - return new self(sprintf( - 'Can\'t add new handler %s for the command %s into Git repository of type %s.', - $commandClassname, - $handlerClassname, - ResolvableGitRepository::class - )); - } + /** + * @param class-string $commandClassname + * @param class-string $handlerClassname + */ + public static function cantAddHandlerToResolvableGitRepository(string $commandClassname, string $handlerClassname): self + { + return new self(sprintf( + 'Can\'t add new handler %s for the command %s into Git repository of type %s.', + $commandClassname, + $handlerClassname, + ResolvableGitRepository::class, + )); + } } diff --git a/src/Exception/ExportConfigException.php b/src/Exception/ExportConfigException.php index affac00..6c66efb 100644 --- a/src/Exception/ExportConfigException.php +++ b/src/Exception/ExportConfigException.php @@ -10,28 +10,28 @@ final class ExportConfigException extends Exception implements ExceptionInterface { - public static function missingOption(string $name): self - { - return new self(sprintf( - 'Missing the option %s in export config.', - $name - )); - } + public static function missingOption(string $name): self + { + return new self(sprintf( + 'Missing the option %s in export config.', + $name, + )); + } - public static function configFileNotFound(string $filename): self - { - return new self(sprintf( - 'Config file %s not found.', - $filename - )); - } + public static function configFileNotFound(string $filename): self + { + return new self(sprintf( + 'Config file %s not found.', + $filename, + )); + } - public static function configCantBeLoadedFromFile(string $filename): self - { - return new self(sprintf( - 'Config from the file %s can\'t be loaded. The file must return instance of %s.', - $filename, - Config::class - )); - } + public static function configCantBeLoadedFromFile(string $filename): self + { + return new self(sprintf( + 'Config from the file %s can\'t be loaded. The file must return instance of %s.', + $filename, + Config::class, + )); + } } diff --git a/src/Exception/GitDirectoryException.php b/src/Exception/GitDirectoryException.php index 13dc472..eb821c6 100644 --- a/src/Exception/GitDirectoryException.php +++ b/src/Exception/GitDirectoryException.php @@ -9,32 +9,32 @@ final class GitDirectoryException extends Exception implements ExceptionInterface { - public static function invalidWorkingDirectory(string $directory): self - { - return new self(sprintf( - 'The path %s is not valid directory.', - $directory - )); - } + public static function invalidWorkingDirectory(string $directory): self + { + return new self(sprintf( + 'The path %s is not valid directory.', + $directory, + )); + } - public static function gitDirectoryNotProvided(): self - { - return new self('Git directory is not provided.'); - } + public static function gitDirectoryNotProvided(): self + { + return new self('Git directory is not provided.'); + } - public static function invalidGitDirectory(string $directory): self - { - return new self(sprintf( - 'The path %s is not valid git directory.', - $directory - )); - } + public static function invalidGitDirectory(string $directory): self + { + return new self(sprintf( + 'The path %s is not valid git directory.', + $directory, + )); + } - public static function gitDirectoryNotFound(string $workingDirectory): self - { - return new self(sprintf( - 'Git directory from the working directory %s not found.', - $workingDirectory - )); - } + public static function gitDirectoryNotFound(string $workingDirectory): self + { + return new self(sprintf( + 'Git directory from the working directory %s not found.', + $workingDirectory, + )); + } } diff --git a/src/Exception/UnhandledCommandException.php b/src/Exception/UnhandledCommandException.php index d6127bf..b5a9745 100644 --- a/src/Exception/UnhandledCommandException.php +++ b/src/Exception/UnhandledCommandException.php @@ -10,11 +10,11 @@ final class UnhandledCommandException extends Exception implements ExceptionInterface { - public static function cantHandleCommand(GitCommandInterface $command): self - { - return new self(sprintf( - 'Can\'t handle git command %s.', - $command - )); - } + public static function cantHandleCommand(GitCommandInterface $command): self + { + return new self(sprintf( + 'Can\'t handle git command %s.', + $command, + )); + } } diff --git a/src/Export/Config.php b/src/Export/Config.php index 26316c7..857b9dc 100644 --- a/src/Export/Config.php +++ b/src/Export/Config.php @@ -5,109 +5,109 @@ namespace SixtyEightPublishers\TracyGitVersion\Export; use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; -use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; use SixtyEightPublishers\TracyGitVersion\Export\PartialExporter\HeadExporter; -use SixtyEightPublishers\TracyGitVersion\Repository\GitCommandHandlerInterface; -use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; use SixtyEightPublishers\TracyGitVersion\Export\PartialExporter\LatestTagExporter; +use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\GitCommandHandlerInterface; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetHeadCommandHandler; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetLatestTagCommandHandler; -use function array_merge; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; use function array_key_exists; +use function array_merge; final class Config { - public const OPTION_GIT_DIRECTORY = 'git_directory'; - public const OPTION_COMMAND_HANDLERS = 'command_handlers'; - public const OPTION_EXPORTERS = 'exporters'; - public const OPTION_OUTPUT_FILE = 'output_file'; - - /** @var array */ - private array $options = []; - - public static function create(): self - { - return new self(); - } - - public static function createDefault(): self - { - return self::create() - ->setGitDirectory(GitDirectory::createAutoDetected()) - ->addCommandHandlers([ - GetHeadCommand::class => new GetHeadCommandHandler(), - GetLatestTagCommand::class => new GetLatestTagCommandHandler(), - ]) - ->addExporters([ - new HeadExporter(), - new LatestTagExporter(), - ]); - } - - /** - * @param mixed $value - */ - public function setOption(string $name, $value): self - { - $this->options[$name] = $value; - - return $this; - } - - /** - * @param mixed $value - */ - public function mergeOption(string $name, $value): self - { - $this->options[$name] = array_merge((array) ($this->options[$name] ?? []), (array) $value); - - return $this; - } - - public function hasOption(string $name): bool - { - return array_key_exists($name, $this->options); - } - - /** - * @return mixed - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException - */ - public function getOption(string $name) - { - if (!$this->hasOption($name)) { - throw ExportConfigException::missingOption($name); - } - - return $this->options[$name]; - } - - public function setGitDirectory(GitDirectory $gitDirectory): self - { - return $this->setOption(self::OPTION_GIT_DIRECTORY, $gitDirectory); - } - - /** - * @param array $handlers - */ - public function addCommandHandlers(array $handlers): self - { - return $this->mergeOption(self::OPTION_COMMAND_HANDLERS, $handlers); - } - - /** - * @param array $exporters - * - * @return $this - */ - public function addExporters(array $exporters): self - { - return $this->mergeOption(self::OPTION_EXPORTERS, $exporters); - } - - public function setOutputFile(string $outputFile): self - { - return $this->setOption(self::OPTION_OUTPUT_FILE, $outputFile); - } + public const OPTION_GIT_DIRECTORY = 'git_directory'; + public const OPTION_COMMAND_HANDLERS = 'command_handlers'; + public const OPTION_EXPORTERS = 'exporters'; + public const OPTION_OUTPUT_FILE = 'output_file'; + + /** @var array */ + private array $options = []; + + public static function create(): self + { + return new self(); + } + + public static function createDefault(): self + { + return self::create() + ->setGitDirectory(GitDirectory::createAutoDetected()) + ->addCommandHandlers([ + GetHeadCommand::class => new GetHeadCommandHandler(), + GetLatestTagCommand::class => new GetLatestTagCommandHandler(), + ]) + ->addExporters([ + new HeadExporter(), + new LatestTagExporter(), + ]); + } + + /** + * @param mixed $value + */ + public function setOption(string $name, $value): self + { + $this->options[$name] = $value; + + return $this; + } + + /** + * @param mixed $value + */ + public function mergeOption(string $name, $value): self + { + $this->options[$name] = array_merge((array) ($this->options[$name] ?? []), (array) $value); + + return $this; + } + + public function hasOption(string $name): bool + { + return array_key_exists($name, $this->options); + } + + /** + * @return mixed + * @throws ExportConfigException + */ + public function getOption(string $name) + { + if (!$this->hasOption($name)) { + throw ExportConfigException::missingOption($name); + } + + return $this->options[$name]; + } + + public function setGitDirectory(GitDirectory $gitDirectory): self + { + return $this->setOption(self::OPTION_GIT_DIRECTORY, $gitDirectory); + } + + /** + * @param array $handlers + */ + public function addCommandHandlers(array $handlers): self + { + return $this->mergeOption(self::OPTION_COMMAND_HANDLERS, $handlers); + } + + /** + * @param array $exporters + * + * @return $this + */ + public function addExporters(array $exporters): self + { + return $this->mergeOption(self::OPTION_EXPORTERS, $exporters); + } + + public function setOutputFile(string $outputFile): self + { + return $this->setOption(self::OPTION_OUTPUT_FILE, $outputFile); + } } diff --git a/src/Export/ExporterInterface.php b/src/Export/ExporterInterface.php index 7cce5e9..8b1b8b0 100644 --- a/src/Export/ExporterInterface.php +++ b/src/Export/ExporterInterface.php @@ -4,13 +4,14 @@ namespace SixtyEightPublishers\TracyGitVersion\Export; +use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; interface ExporterInterface { - /** - * @return array - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException - */ - public function export(Config $config, ?GitRepositoryInterface $gitRepository): array; + /** + * @return array + * @throws ExportConfigException + */ + public function export(Config $config, ?GitRepositoryInterface $gitRepository): array; } diff --git a/src/Export/LocalDirectoryExporter.php b/src/Export/LocalDirectoryExporter.php index 6856777..88a7138 100644 --- a/src/Export/LocalDirectoryExporter.php +++ b/src/Export/LocalDirectoryExporter.php @@ -4,34 +4,34 @@ namespace SixtyEightPublishers\TracyGitVersion\Export; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; -use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use SixtyEightPublishers\TracyGitVersion\Repository\GitCommandHandlerInterface; +use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; -use function assert; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; use function array_merge; +use function assert; final class LocalDirectoryExporter implements ExporterInterface { - public function export(Config $config, ?GitRepositoryInterface $gitRepository): array - { - $directory = $config->getOption(Config::OPTION_GIT_DIRECTORY); - assert($directory instanceof GitDirectory); + public function export(Config $config, ?GitRepositoryInterface $gitRepository): array + { + $directory = $config->getOption(Config::OPTION_GIT_DIRECTORY); + assert($directory instanceof GitDirectory); - /** @var array $commandHandlers */ - $commandHandlers = (array) $config->getOption(Config::OPTION_COMMAND_HANDLERS); + /** @var array $commandHandlers */ + $commandHandlers = (array) $config->getOption(Config::OPTION_COMMAND_HANDLERS); - $gitRepository = $gitRepository ?? new LocalGitRepository($directory, $commandHandlers); - $results = [[]]; + $gitRepository = $gitRepository ?? new LocalGitRepository($directory, $commandHandlers); + $results = [[]]; - /** @var array $exporters */ - $exporters = (array) $config->getOption(Config::OPTION_EXPORTERS); - $exporters = (static fn (ExporterInterface ...$exporters): array => $exporters)(...$exporters); + /** @var array $exporters */ + $exporters = (array) $config->getOption(Config::OPTION_EXPORTERS); + $exporters = (static fn (ExporterInterface ...$exporters): array => $exporters)(...$exporters); - foreach ($exporters as $exporter) { - $results[] = $exporter->export($config, $gitRepository); - } + foreach ($exporters as $exporter) { + $results[] = $exporter->export($config, $gitRepository); + } - return array_merge(...$results); - } + return array_merge(...$results); + } } diff --git a/src/Export/PartialExporter/HeadExporter.php b/src/Export/PartialExporter/HeadExporter.php index 0b385cb..03318aa 100644 --- a/src/Export/PartialExporter/HeadExporter.php +++ b/src/Export/PartialExporter/HeadExporter.php @@ -4,37 +4,38 @@ namespace SixtyEightPublishers\TracyGitVersion\Export\PartialExporter; +use SixtyEightPublishers\TracyGitVersion\Exception\BadMethodCallException; +use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; use SixtyEightPublishers\TracyGitVersion\Export\Config; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Export\ExporterInterface; -use SixtyEightPublishers\TracyGitVersion\Exception\BadMethodCallException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; use function assert; final class HeadExporter implements ExporterInterface { - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException - */ - public function export(Config $config, ?GitRepositoryInterface $gitRepository): array - { - if (null === $gitRepository) { - throw BadMethodCallException::gitRepositoryNotProvidedForPartialExporter($this); - } + /** + * @throws UnhandledCommandException + */ + public function export(Config $config, ?GitRepositoryInterface $gitRepository): array + { + if (null === $gitRepository) { + throw BadMethodCallException::gitRepositoryNotProvidedForPartialExporter($this); + } - if (!$gitRepository->supports(GetHeadCommand::class)) { - return []; - } + if (!$gitRepository->supports(GetHeadCommand::class)) { + return []; + } - $head = $gitRepository->handle(new GetHeadCommand()); - assert($head instanceof Head); + $head = $gitRepository->handle(new GetHeadCommand()); + assert($head instanceof Head); - return [ - 'head' => [ - 'branch' => $head->getBranch(), - 'commit_hash' => null !== $head->getCommitHash() ? $head->getCommitHash()->getValue() : null, - ], - ]; - } + return [ + 'head' => [ + 'branch' => $head->getBranch(), + 'commit_hash' => null !== $head->getCommitHash() ? $head->getCommitHash()->getValue() : null, + ], + ]; + } } diff --git a/src/Export/PartialExporter/LatestTagExporter.php b/src/Export/PartialExporter/LatestTagExporter.php index a37267d..fe99225 100644 --- a/src/Export/PartialExporter/LatestTagExporter.php +++ b/src/Export/PartialExporter/LatestTagExporter.php @@ -4,39 +4,40 @@ namespace SixtyEightPublishers\TracyGitVersion\Export\PartialExporter; +use SixtyEightPublishers\TracyGitVersion\Exception\BadMethodCallException; use SixtyEightPublishers\TracyGitVersion\Export\Config; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; use SixtyEightPublishers\TracyGitVersion\Export\ExporterInterface; -use SixtyEightPublishers\TracyGitVersion\Exception\BadMethodCallException; -use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; +use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; +use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; final class LatestTagExporter implements ExporterInterface { - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException - */ - public function export(Config $config, ?GitRepositoryInterface $gitRepository): array - { - if (null === $gitRepository) { - throw BadMethodCallException::gitRepositoryNotProvidedForPartialExporter($this); - } - - if (!$gitRepository->supports(GetLatestTagCommand::class)) { - return []; - } - - $tag = $gitRepository->handle(new GetLatestTagCommand()); - - if (!$tag instanceof Tag) { - return []; - } - - return [ - 'latest_tag' => [ - 'name' => $tag->getName(), - 'commit_hash' => $tag->getCommitHash()->getValue(), - ], - ]; - } + /** + * @throws UnhandledCommandException + */ + public function export(Config $config, ?GitRepositoryInterface $gitRepository): array + { + if (null === $gitRepository) { + throw BadMethodCallException::gitRepositoryNotProvidedForPartialExporter($this); + } + + if (!$gitRepository->supports(GetLatestTagCommand::class)) { + return []; + } + + $tag = $gitRepository->handle(new GetLatestTagCommand()); + + if (!$tag instanceof Tag) { + return []; + } + + return [ + 'latest_tag' => [ + 'name' => $tag->getName(), + 'commit_hash' => $tag->getCommitHash()->getValue(), + ], + ]; + } } diff --git a/src/Repository/AbstractGitRepository.php b/src/Repository/AbstractGitRepository.php index 695eceb..3f76f44 100644 --- a/src/Repository/AbstractGitRepository.php +++ b/src/Repository/AbstractGitRepository.php @@ -11,40 +11,40 @@ abstract class AbstractGitRepository implements GitRepositoryInterface { - /** @var array */ - private array $handlers = []; - - /** - * @param array $handlers - */ - public function __construct(array $handlers = []) - { - foreach ($handlers as $commandClassname => $handler) { - $this->addHandler($commandClassname, $handler); - } - } - - public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void - { - $this->handlers[$commandClassname] = $handler; - } - - public function handle(GitCommandInterface $command) - { - $classname = get_class($command); - - if (!$this->supports($classname)) { - throw UnhandledCommandException::cantHandleCommand($command); - } - - $handler = $this->handlers[$classname]; - assert(is_callable($handler)); - - return $handler($command); - } - - public function supports(string $commandClassname): bool - { - return isset($this->handlers[$commandClassname]) && $this->isAccessible(); - } + /** @var array */ + private array $handlers = []; + + /** + * @param array $handlers + */ + public function __construct(array $handlers = []) + { + foreach ($handlers as $commandClassname => $handler) { + $this->addHandler($commandClassname, $handler); + } + } + + public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void + { + $this->handlers[$commandClassname] = $handler; + } + + public function handle(GitCommandInterface $command) + { + $classname = get_class($command); + + if (!$this->supports($classname)) { + throw UnhandledCommandException::cantHandleCommand($command); + } + + $handler = $this->handlers[$classname]; + assert(is_callable($handler)); + + return $handler($command); + } + + public function supports(string $commandClassname): bool + { + return isset($this->handlers[$commandClassname]) && $this->isAccessible(); + } } diff --git a/src/Repository/Command/GetHeadCommand.php b/src/Repository/Command/GetHeadCommand.php index 39af688..99676a4 100644 --- a/src/Repository/Command/GetHeadCommand.php +++ b/src/Repository/Command/GetHeadCommand.php @@ -8,8 +8,8 @@ final class GetHeadCommand implements GitCommandInterface { - public function __toString(): string - { - return 'GET_HEAD()'; - } + public function __toString(): string + { + return 'GET_HEAD()'; + } } diff --git a/src/Repository/Command/GetLatestTagCommand.php b/src/Repository/Command/GetLatestTagCommand.php index 6d02a4f..dea9340 100644 --- a/src/Repository/Command/GetLatestTagCommand.php +++ b/src/Repository/Command/GetLatestTagCommand.php @@ -8,8 +8,8 @@ final class GetLatestTagCommand implements GitCommandInterface { - public function __toString(): string - { - return 'GET_LATEST_TAG()'; - } + public function __toString(): string + { + return 'GET_LATEST_TAG()'; + } } diff --git a/src/Repository/Entity/CommitHash.php b/src/Repository/Entity/CommitHash.php index 3f259e1..d4ff2d6 100644 --- a/src/Repository/Entity/CommitHash.php +++ b/src/Repository/Entity/CommitHash.php @@ -6,20 +6,20 @@ final class CommitHash { - private string $value; + private string $value; - public function __construct(string $value) - { - $this->value = $value; - } + public function __construct(string $value) + { + $this->value = $value; + } - public function getValue(): string - { - return $this->value; - } + public function getValue(): string + { + return $this->value; + } - public function compare(self $commitHash): bool - { - return $this->getValue() === $commitHash->getValue(); - } + public function compare(self $commitHash): bool + { + return $this->getValue() === $commitHash->getValue(); + } } diff --git a/src/Repository/Entity/Head.php b/src/Repository/Entity/Head.php index e9bf6e9..d9459f5 100644 --- a/src/Repository/Entity/Head.php +++ b/src/Repository/Entity/Head.php @@ -6,28 +6,28 @@ final class Head { - private ?string $branch; - - private ?CommitHash $commitHash; - - public function __construct(?string $branch, ?CommitHash $commitHash) - { - $this->branch = $branch; - $this->commitHash = $commitHash; - } - - public function getBranch(): ?string - { - return $this->branch; - } - - public function getCommitHash(): ?CommitHash - { - return $this->commitHash; - } - - public function isDetached(): bool - { - return null === $this->branch && null !== $this->commitHash; - } + private ?string $branch; + + private ?CommitHash $commitHash; + + public function __construct(?string $branch, ?CommitHash $commitHash) + { + $this->branch = $branch; + $this->commitHash = $commitHash; + } + + public function getBranch(): ?string + { + return $this->branch; + } + + public function getCommitHash(): ?CommitHash + { + return $this->commitHash; + } + + public function isDetached(): bool + { + return null === $this->branch && null !== $this->commitHash; + } } diff --git a/src/Repository/Entity/Tag.php b/src/Repository/Entity/Tag.php index dcd1004..f805f42 100644 --- a/src/Repository/Entity/Tag.php +++ b/src/Repository/Entity/Tag.php @@ -6,23 +6,23 @@ final class Tag { - private string $name; + private string $name; - private CommitHash $commitHash; + private CommitHash $commitHash; - public function __construct(string $name, CommitHash $commitHash) - { - $this->name = $name; - $this->commitHash = $commitHash; - } + public function __construct(string $name, CommitHash $commitHash) + { + $this->name = $name; + $this->commitHash = $commitHash; + } - public function getName(): string - { - return $this->name; - } + public function getName(): string + { + return $this->name; + } - public function getCommitHash(): CommitHash - { - return $this->commitHash; - } + public function getCommitHash(): CommitHash + { + return $this->commitHash; + } } diff --git a/src/Repository/Export/CommandHandler/AbstractExportedCommandHandler.php b/src/Repository/Export/CommandHandler/AbstractExportedCommandHandler.php index a3dbb51..a26c114 100644 --- a/src/Repository/Export/CommandHandler/AbstractExportedCommandHandler.php +++ b/src/Repository/Export/CommandHandler/AbstractExportedCommandHandler.php @@ -6,30 +6,30 @@ abstract class AbstractExportedCommandHandler implements ExportedGitCommandHandlerInterface { - /** @var array|null */ - private ?array $exportedValue; + /** @var array|null */ + private ?array $exportedValue; - /** - * @param array|null $exportedValue - */ - public function __construct(?array $exportedValue = null) - { - $this->exportedValue = $exportedValue; - } + /** + * @param array|null $exportedValue + */ + public function __construct(?array $exportedValue = null) + { + $this->exportedValue = $exportedValue; + } - public function withExportedValue(array $exportedValue): ExportedGitCommandHandlerInterface - { - $handler = clone $this; - $handler->exportedValue = $exportedValue; + public function withExportedValue(array $exportedValue): ExportedGitCommandHandlerInterface + { + $handler = clone $this; + $handler->exportedValue = $exportedValue; - return $handler; - } + return $handler; + } - /** - * @return array - */ - protected function getExportedValue(): array - { - return $this->exportedValue ?? []; - } + /** + * @return array + */ + protected function getExportedValue(): array + { + return $this->exportedValue ?? []; + } } diff --git a/src/Repository/Export/CommandHandler/ExportedGitCommandHandlerInterface.php b/src/Repository/Export/CommandHandler/ExportedGitCommandHandlerInterface.php index f3f4f2c..35ac903 100644 --- a/src/Repository/Export/CommandHandler/ExportedGitCommandHandlerInterface.php +++ b/src/Repository/Export/CommandHandler/ExportedGitCommandHandlerInterface.php @@ -8,8 +8,8 @@ interface ExportedGitCommandHandlerInterface extends GitCommandHandlerInterface { - /** - * @param array $exportedValue - */ - public function withExportedValue(array $exportedValue): self; + /** + * @param array $exportedValue + */ + public function withExportedValue(array $exportedValue): self; } diff --git a/src/Repository/Export/CommandHandler/GetHeadCommandHandler.php b/src/Repository/Export/CommandHandler/GetHeadCommandHandler.php index baa260a..66876ef 100644 --- a/src/Repository/Export/CommandHandler/GetHeadCommandHandler.php +++ b/src/Repository/Export/CommandHandler/GetHeadCommandHandler.php @@ -4,19 +4,19 @@ namespace SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; final class GetHeadCommandHandler extends AbstractExportedCommandHandler { - public function __invoke(GetHeadCommand $command): Head - { - $value = $this->getExportedValue(); + public function __invoke(GetHeadCommand $command): Head + { + $value = $this->getExportedValue(); - return new Head( - $value['head']['branch'] ?? null, - isset($value['head']['commit_hash']) ? new CommitHash($value['head']['commit_hash']) : null - ); - } + return new Head( + $value['head']['branch'] ?? null, + isset($value['head']['commit_hash']) ? new CommitHash($value['head']['commit_hash']) : null, + ); + } } diff --git a/src/Repository/Export/CommandHandler/GetLatestTagCommandHandler.php b/src/Repository/Export/CommandHandler/GetLatestTagCommandHandler.php index 3a781e9..cca3d5e 100644 --- a/src/Repository/Export/CommandHandler/GetLatestTagCommandHandler.php +++ b/src/Repository/Export/CommandHandler/GetLatestTagCommandHandler.php @@ -4,20 +4,20 @@ namespace SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; final class GetLatestTagCommandHandler extends AbstractExportedCommandHandler { - public function __invoke(GetLatestTagCommand $command): ?Tag - { - $value = $this->getExportedValue(); + public function __invoke(GetLatestTagCommand $command): ?Tag + { + $value = $this->getExportedValue(); - if (!isset($value['latest_tag']['name'], $value['latest_tag']['commit_hash'])) { - return null; - } + if (!isset($value['latest_tag']['name'], $value['latest_tag']['commit_hash'])) { + return null; + } - return new Tag($value['latest_tag']['name'], new CommitHash($value['latest_tag']['commit_hash'])); - } + return new Tag($value['latest_tag']['name'], new CommitHash($value['latest_tag']['commit_hash'])); + } } diff --git a/src/Repository/ExportedGitRepository.php b/src/Repository/ExportedGitRepository.php index 29e9dd7..5a47f94 100644 --- a/src/Repository/ExportedGitRepository.php +++ b/src/Repository/ExportedGitRepository.php @@ -7,84 +7,84 @@ use JsonException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\ExportedGitCommandHandlerInterface; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\GetHeadCommandHandler; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\GetLatestTagCommandHandler; -use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\ExportedGitCommandHandlerInterface; +use function file_get_contents; use function is_readable; use function json_decode; -use function file_get_contents; final class ExportedGitRepository extends AbstractGitRepository { - private string $file; - - private string $source; - - /** @var array|null */ - private ?array $json = null; - - private ?bool $valid = null; - - /** - * @param array $handlers - */ - public function __construct(string $file, array $handlers = [], string $source = self::SOURCE_EXPORT) - { - $this->file = $file; - $this->source = $source; - - parent::__construct($handlers); - } - - public static function createDefault(string $file): self - { - return new self($file, [ - GetHeadCommand::class => new GetHeadCommandHandler(), - GetLatestTagCommand::class => new GetLatestTagCommandHandler(), - ]); - } - - public function getSource(): string - { - return $this->source; - } - - public function isAccessible(): bool - { - return $this->isValid(); - } - - public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void - { - if ($handler instanceof ExportedGitCommandHandlerInterface && $this->isValid()) { - $handler = $handler->withExportedValue($this->json ?? []); - } - - parent::addHandler($commandClassname, $handler); - } - - private function isValid(): bool - { - if (null !== $this->valid) { - return $this->valid; - } - - if (!is_readable($this->file)) { - return $this->valid = false; - } - - $content = @file_get_contents($this->file); - - if (false === $content) { - return $this->valid = false; - } - - try { - $this->json = (array) json_decode($content, true, 512, JSON_THROW_ON_ERROR); - - return $this->valid = true; - } catch (JsonException $e) { - return $this->valid = false; - } - } + private string $file; + + private string $source; + + /** @var array|null */ + private ?array $json = null; + + private ?bool $valid = null; + + /** + * @param array $handlers + */ + public function __construct(string $file, array $handlers = [], string $source = self::SOURCE_EXPORT) + { + $this->file = $file; + $this->source = $source; + + parent::__construct($handlers); + } + + public static function createDefault(string $file): self + { + return new self($file, [ + GetHeadCommand::class => new GetHeadCommandHandler(), + GetLatestTagCommand::class => new GetLatestTagCommandHandler(), + ]); + } + + public function getSource(): string + { + return $this->source; + } + + public function isAccessible(): bool + { + return $this->isValid(); + } + + public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void + { + if ($handler instanceof ExportedGitCommandHandlerInterface && $this->isValid()) { + $handler = $handler->withExportedValue($this->json ?? []); + } + + parent::addHandler($commandClassname, $handler); + } + + private function isValid(): bool + { + if (null !== $this->valid) { + return $this->valid; + } + + if (!is_readable($this->file)) { + return $this->valid = false; + } + + $content = @file_get_contents($this->file); + + if (false === $content) { + return $this->valid = false; + } + + try { + $this->json = (array) json_decode($content, true, 512, JSON_THROW_ON_ERROR); + + return $this->valid = true; + } catch (JsonException $e) { + return $this->valid = false; + } + } } diff --git a/src/Repository/GitCommandInterface.php b/src/Repository/GitCommandInterface.php index 5f212c9..c235b28 100644 --- a/src/Repository/GitCommandInterface.php +++ b/src/Repository/GitCommandInterface.php @@ -6,5 +6,5 @@ interface GitCommandInterface { - public function __toString(): string; + public function __toString(): string; } diff --git a/src/Repository/GitRepositoryInterface.php b/src/Repository/GitRepositoryInterface.php index 4536f52..619c50e 100644 --- a/src/Repository/GitRepositoryInterface.php +++ b/src/Repository/GitRepositoryInterface.php @@ -4,28 +4,30 @@ namespace SixtyEightPublishers\TracyGitVersion\Repository; +use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; + interface GitRepositoryInterface { - public const SOURCE_GIT_DIRECTORY = 'git directory'; - public const SOURCE_EXPORT = 'export'; + public const SOURCE_GIT_DIRECTORY = 'git directory'; + public const SOURCE_EXPORT = 'export'; - public function getSource(): string; + public function getSource(): string; - public function isAccessible(): bool; + public function isAccessible(): bool; - /** - * @param class-string $commandClassname - */ - public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void; + /** + * @param class-string $commandClassname + */ + public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void; - /** - * @return mixed - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException - */ - public function handle(GitCommandInterface $command); + /** + * @return mixed + * @throws UnhandledCommandException + */ + public function handle(GitCommandInterface $command); - /** - * @param class-string $commandClassname - */ - public function supports(string $commandClassname): bool; + /** + * @param class-string $commandClassname + */ + public function supports(string $commandClassname): bool; } diff --git a/src/Repository/LocalDirectory/CommandHandler/AbstractLocalDirectoryCommandHandler.php b/src/Repository/LocalDirectory/CommandHandler/AbstractLocalDirectoryCommandHandler.php index 8c320b7..3ca075b 100644 --- a/src/Repository/LocalDirectory/CommandHandler/AbstractLocalDirectoryCommandHandler.php +++ b/src/Repository/LocalDirectory/CommandHandler/AbstractLocalDirectoryCommandHandler.php @@ -9,30 +9,30 @@ abstract class AbstractLocalDirectoryCommandHandler implements LocalDirectoryGitCommandHandlerInterface { - private ?GitDirectory $gitDirectory; - - public function __construct(?GitDirectory $gitDirectory = null) - { - $this->gitDirectory = $gitDirectory; - } - - public function withGitDirectory(GitDirectory $gitDirectory): LocalDirectoryGitCommandHandlerInterface - { - $handler = clone $this; - $handler->gitDirectory = $gitDirectory; - - return $handler; - } - - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException - */ - protected function getGitDirectory(): GitDirectory - { - if (null === $this->gitDirectory) { - throw GitDirectoryException::gitDirectoryNotProvided(); - } - - return $this->gitDirectory; - } + private ?GitDirectory $gitDirectory; + + public function __construct(?GitDirectory $gitDirectory = null) + { + $this->gitDirectory = $gitDirectory; + } + + public function withGitDirectory(GitDirectory $gitDirectory): LocalDirectoryGitCommandHandlerInterface + { + $handler = clone $this; + $handler->gitDirectory = $gitDirectory; + + return $handler; + } + + /** + * @throws GitDirectoryException + */ + protected function getGitDirectory(): GitDirectory + { + if (null === $this->gitDirectory) { + throw GitDirectoryException::gitDirectoryNotProvided(); + } + + return $this->gitDirectory; + } } diff --git a/src/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandler.php b/src/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandler.php index a6e36a2..b412425 100644 --- a/src/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandler.php +++ b/src/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandler.php @@ -4,42 +4,43 @@ namespace SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; +use SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; -use function trim; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; +use function explode; +use function file_get_contents; +use function is_readable; use function strlen; use function strpos; use function substr; -use function explode; -use function is_readable; -use function file_get_contents; +use function trim; final class GetHeadCommandHandler extends AbstractLocalDirectoryCommandHandler { - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException - */ - public function __invoke(GetHeadCommand $command): Head - { - $headFile = $this->getGitDirectory() . DIRECTORY_SEPARATOR . 'HEAD'; - - # not versioned - if (!is_readable($headFile) || false === ($content = @file_get_contents($headFile))) { - return new Head(null, null); - } - - # detached head - if (0 !== strpos($content, 'ref:')) { - return new Head(null, new CommitHash(trim($content))); - } - - $branchParts = explode('/', $content, 3); - $commitFile = $this->getGitDirectory() . DIRECTORY_SEPARATOR . trim(substr($content, 5, strlen($content))); - - return new Head( - isset($branchParts[2]) ? trim($branchParts[2]) : null, - is_readable($commitFile) && false !== ($commitHash = @file_get_contents($commitFile)) ? new CommitHash(trim($commitHash)) : null - ); - } + /** + * @throws GitDirectoryException + */ + public function __invoke(GetHeadCommand $command): Head + { + $headFile = $this->getGitDirectory() . DIRECTORY_SEPARATOR . 'HEAD'; + + # not versioned + if (!is_readable($headFile) || false === ($content = @file_get_contents($headFile))) { + return new Head(null, null); + } + + # detached head + if (0 !== strpos($content, 'ref:')) { + return new Head(null, new CommitHash(trim($content))); + } + + $branchParts = explode('/', $content, 3); + $commitFile = $this->getGitDirectory() . DIRECTORY_SEPARATOR . trim(substr($content, 5, strlen($content))); + + return new Head( + isset($branchParts[2]) ? trim($branchParts[2]) : null, + is_readable($commitFile) && false !== ($commitHash = @file_get_contents($commitFile)) ? new CommitHash(trim($commitHash)) : null, + ); + } } diff --git a/src/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandler.php b/src/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandler.php index 79a2036..c09e7cc 100644 --- a/src/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandler.php +++ b/src/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandler.php @@ -4,63 +4,64 @@ namespace SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; +use SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\CommitHash; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; +use function current; +use function file_exists; +use function file_get_contents; +use function filectime; +use function in_array; +use function is_readable; use function key; -use function trim; use function krsort; -use function current; use function scandir; use function sprintf; -use function in_array; -use function filectime; -use function file_exists; -use function is_readable; -use function file_get_contents; +use function trim; final class GetLatestTagCommandHandler extends AbstractLocalDirectoryCommandHandler { - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException - */ - public function __invoke(GetLatestTagCommand $getLatestTag): ?Tag - { - $tagsDirectory = sprintf('%s%srefs%stags', $this->getGitDirectory(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); + /** + * @throws GitDirectoryException + */ + public function __invoke(GetLatestTagCommand $getLatestTag): ?Tag + { + $tagsDirectory = sprintf('%s%srefs%stags', $this->getGitDirectory(), DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR); - if (!file_exists($tagsDirectory)) { - return null; - } + if (!file_exists($tagsDirectory)) { + return null; + } - $latestTagNames = []; - $latestTimestamp = 0; - $tagNames = scandir($tagsDirectory); + $latestTagNames = []; + $latestTimestamp = 0; + $tagNames = scandir($tagsDirectory); - foreach ($tagNames ?: [] as $tagName) { - if (in_array($tagName, ['.', '..'], true)) { - continue; - } + foreach ($tagNames ?: [] as $tagName) { + if (in_array($tagName, ['.', '..'], true)) { + continue; + } - $filename = $tagsDirectory . DIRECTORY_SEPARATOR . $tagName; + $filename = $tagsDirectory . DIRECTORY_SEPARATOR . $tagName; - if (!is_readable($filename)) { - continue; - } + if (!is_readable($filename)) { + continue; + } - $creationTime = @filectime($filename); + $creationTime = @filectime($filename); - if (false !== $creationTime && $creationTime >= $latestTimestamp) { - $latestTimestamp = $creationTime; - $latestTagNames[$tagName] = $filename; - } - } + if (false !== $creationTime && $creationTime >= $latestTimestamp) { + $latestTimestamp = $creationTime; + $latestTagNames[$tagName] = $filename; + } + } - if (empty($latestTagNames)) { - return null; - } + if (empty($latestTagNames)) { + return null; + } - krsort($latestTagNames); + krsort($latestTagNames); - return new Tag((string) key($latestTagNames), new CommitHash(trim((string) @file_get_contents(current($latestTagNames))))); - } + return new Tag((string) key($latestTagNames), new CommitHash(trim((string) @file_get_contents(current($latestTagNames))))); + } } diff --git a/src/Repository/LocalDirectory/CommandHandler/LocalDirectoryGitCommandHandlerInterface.php b/src/Repository/LocalDirectory/CommandHandler/LocalDirectoryGitCommandHandlerInterface.php index f5de1d2..2ee83e5 100644 --- a/src/Repository/LocalDirectory/CommandHandler/LocalDirectoryGitCommandHandlerInterface.php +++ b/src/Repository/LocalDirectory/CommandHandler/LocalDirectoryGitCommandHandlerInterface.php @@ -9,5 +9,5 @@ interface LocalDirectoryGitCommandHandlerInterface extends GitCommandHandlerInterface { - public function withGitDirectory(GitDirectory $gitDirectory): self; + public function withGitDirectory(GitDirectory $gitDirectory): self; } diff --git a/src/Repository/LocalDirectory/GitDirectory.php b/src/Repository/LocalDirectory/GitDirectory.php index d3828e0..0687a81 100644 --- a/src/Repository/LocalDirectory/GitDirectory.php +++ b/src/Repository/LocalDirectory/GitDirectory.php @@ -5,88 +5,88 @@ namespace SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory; use SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException; -use function is_dir; use function dirname; -use function realpath; use function file_exists; +use function is_dir; +use function realpath; final class GitDirectory { - private ?string $workingDirectory; - - private ?string $workingDirectoryPath = null; - - private ?string $gitDirectory; - - private string $directoryName; - - private function __construct(?string $gitDirectory, ?string $workingDirectory = null, string $directoryName = '.git') - { - $this->workingDirectory = $workingDirectory; - $this->gitDirectory = $gitDirectory; - $this->directoryName = $directoryName; - } - - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException - */ - public static function createFromGitDirectory(string $gitDirectory): self - { - $realGitDirectory = realpath($gitDirectory); - - if (false === $realGitDirectory || !file_exists($realGitDirectory)) { - throw GitDirectoryException::invalidGitDirectory($gitDirectory); - } - - return new self($realGitDirectory, null); - } - - public static function createAutoDetected(?string $workingDirectory = null, string $directoryName = '.git'): self - { - return new self(null, $workingDirectory, $directoryName); - } - - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException - */ - public function __toString(): string - { - if (null !== $this->gitDirectory) { - return $this->gitDirectory; - } - - $workingDirectory = $this->getWorkingDirectoryPath(); - - do { - $currentDirectory = $workingDirectory; - $gitDirectory = $workingDirectory . DIRECTORY_SEPARATOR . $this->directoryName; - - if (is_dir($gitDirectory)) { - return $this->gitDirectory = $gitDirectory; - } - - $workingDirectory = dirname($workingDirectory); - } while ($workingDirectory !== $currentDirectory); - - throw GitDirectoryException::gitDirectoryNotFound($workingDirectory); - } - - /** - * @throws \SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException - */ - private function getWorkingDirectoryPath(): string - { - if (null !== $this->workingDirectoryPath) { - return $this->workingDirectoryPath; - } - - $workingDirectory = $this->workingDirectory ?? dirname($_SERVER['SCRIPT_FILENAME']); - $workingDirectoryPath = realpath($workingDirectory); - - if (false === $workingDirectoryPath) { - throw GitDirectoryException::invalidWorkingDirectory($workingDirectory); - } - - return $this->workingDirectoryPath = $workingDirectoryPath; - } + private ?string $workingDirectory; + + private ?string $workingDirectoryPath = null; + + private ?string $gitDirectory; + + private string $directoryName; + + private function __construct(?string $gitDirectory, ?string $workingDirectory = null, string $directoryName = '.git') + { + $this->workingDirectory = $workingDirectory; + $this->gitDirectory = $gitDirectory; + $this->directoryName = $directoryName; + } + + /** + * @throws GitDirectoryException + */ + public static function createFromGitDirectory(string $gitDirectory): self + { + $realGitDirectory = realpath($gitDirectory); + + if (false === $realGitDirectory || !file_exists($realGitDirectory)) { + throw GitDirectoryException::invalidGitDirectory($gitDirectory); + } + + return new self($realGitDirectory, null); + } + + public static function createAutoDetected(?string $workingDirectory = null, string $directoryName = '.git'): self + { + return new self(null, $workingDirectory, $directoryName); + } + + /** + * @throws GitDirectoryException + */ + public function __toString(): string + { + if (null !== $this->gitDirectory) { + return $this->gitDirectory; + } + + $workingDirectory = $this->getWorkingDirectoryPath(); + + do { + $currentDirectory = $workingDirectory; + $gitDirectory = $workingDirectory . DIRECTORY_SEPARATOR . $this->directoryName; + + if (is_dir($gitDirectory)) { + return $this->gitDirectory = $gitDirectory; + } + + $workingDirectory = dirname($workingDirectory); + } while ($workingDirectory !== $currentDirectory); + + throw GitDirectoryException::gitDirectoryNotFound($workingDirectory); + } + + /** + * @throws GitDirectoryException + */ + private function getWorkingDirectoryPath(): string + { + if (null !== $this->workingDirectoryPath) { + return $this->workingDirectoryPath; + } + + $workingDirectory = $this->workingDirectory ?? dirname($_SERVER['SCRIPT_FILENAME']); + $workingDirectoryPath = realpath($workingDirectory); + + if (false === $workingDirectoryPath) { + throw GitDirectoryException::invalidWorkingDirectory($workingDirectory); + } + + return $this->workingDirectoryPath = $workingDirectoryPath; + } } diff --git a/src/Repository/LocalGitRepository.php b/src/Repository/LocalGitRepository.php index 49efd58..d46e6e5 100644 --- a/src/Repository/LocalGitRepository.php +++ b/src/Repository/LocalGitRepository.php @@ -7,61 +7,61 @@ use SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetHeadCommandHandler; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetLatestTagCommandHandler; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\LocalDirectoryGitCommandHandlerInterface; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; final class LocalGitRepository extends AbstractGitRepository { - private GitDirectory $gitDirectory; + private GitDirectory $gitDirectory; - private string $source; + private string $source; - /** - * @param array $handlers - */ - public function __construct(GitDirectory $gitDirectory, array $handlers = [], string $source = self::SOURCE_GIT_DIRECTORY) - { - $this->gitDirectory = $gitDirectory; - $this->source = $source; + /** + * @param array $handlers + */ + public function __construct(GitDirectory $gitDirectory, array $handlers = [], string $source = self::SOURCE_GIT_DIRECTORY) + { + $this->gitDirectory = $gitDirectory; + $this->source = $source; - parent::__construct($handlers); - } + parent::__construct($handlers); + } - public static function createDefault(?string $workingDirectory = null, string $directoryName = '.git'): self - { - return new self( - GitDirectory::createAutoDetected($workingDirectory, $directoryName), - [ - GetHeadCommand::class => new GetHeadCommandHandler(), - GetLatestTagCommand::class => new GetLatestTagCommandHandler(), - ] - ); - } + public static function createDefault(?string $workingDirectory = null, string $directoryName = '.git'): self + { + return new self( + GitDirectory::createAutoDetected($workingDirectory, $directoryName), + [ + GetHeadCommand::class => new GetHeadCommandHandler(), + GetLatestTagCommand::class => new GetLatestTagCommandHandler(), + ], + ); + } - public function getSource(): string - { - return $this->source; - } + public function getSource(): string + { + return $this->source; + } - public function isAccessible(): bool - { - try { - $this->gitDirectory->__toString(); + public function isAccessible(): bool + { + try { + $this->gitDirectory->__toString(); - return true; - } catch (GitDirectoryException $e) { - return false; - } - } + return true; + } catch (GitDirectoryException $e) { + return false; + } + } - public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void - { - if ($handler instanceof LocalDirectoryGitCommandHandlerInterface) { - $handler = $handler->withGitDirectory($this->gitDirectory); - } + public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void + { + if ($handler instanceof LocalDirectoryGitCommandHandlerInterface) { + $handler = $handler->withGitDirectory($this->gitDirectory); + } - parent::addHandler($commandClassname, $handler); - } + parent::addHandler($commandClassname, $handler); + } } diff --git a/src/Repository/ResolvableGitRepository.php b/src/Repository/ResolvableGitRepository.php index 7712e3d..d9ded62 100644 --- a/src/Repository/ResolvableGitRepository.php +++ b/src/Repository/ResolvableGitRepository.php @@ -10,72 +10,72 @@ final class ResolvableGitRepository implements GitRepositoryInterface { - /** @var array */ - private array $repositories; + /** @var array */ + private array $repositories; - private bool $resolved = false; + private bool $resolved = false; - private ?GitRepositoryInterface $resolvedRepository = null; + private ?GitRepositoryInterface $resolvedRepository = null; - /** - * @param array $repositories - */ - public function __construct(array $repositories) - { - $this->repositories = (static fn (GitRepositoryInterface ...$repositories): array => $repositories)(...$repositories); - } + /** + * @param array $repositories + */ + public function __construct(array $repositories) + { + $this->repositories = (static fn (GitRepositoryInterface ...$repositories): array => $repositories)(...$repositories); + } - public function getSource(): string - { - $repository = $this->getResolvedRepository(); + public function getSource(): string + { + $repository = $this->getResolvedRepository(); - return null !== $repository ? $repository->getSource() : 'unresolved'; - } + return null !== $repository ? $repository->getSource() : 'unresolved'; + } - public function isAccessible(): bool - { - $repository = $this->getResolvedRepository(); + public function isAccessible(): bool + { + $repository = $this->getResolvedRepository(); - return null !== $repository ? $repository->isAccessible() : false; - } + return null !== $repository && $repository->isAccessible(); + } - public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void - { - throw BadMethodCallException::cantAddHandlerToResolvableGitRepository($commandClassname, get_class($handler)); - } + public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void + { + throw BadMethodCallException::cantAddHandlerToResolvableGitRepository($commandClassname, get_class($handler)); + } - public function handle(GitCommandInterface $command) - { - $repository = $this->getResolvedRepository(); + public function handle(GitCommandInterface $command) + { + $repository = $this->getResolvedRepository(); - if (null === $repository) { - throw UnhandledCommandException::cantHandleCommand($command); - } + if (null === $repository) { + throw UnhandledCommandException::cantHandleCommand($command); + } - return $repository->handle($command); - } + return $repository->handle($command); + } - public function supports(string $commandClassname): bool - { - $repository = $this->getResolvedRepository(); + public function supports(string $commandClassname): bool + { + $repository = $this->getResolvedRepository(); - return null !== $repository && $repository->supports($commandClassname); - } + return null !== $repository && $repository->supports($commandClassname); + } - private function getResolvedRepository(): ?GitRepositoryInterface - { - if (false === $this->resolved) { - foreach ($this->repositories as $repository) { - if ($repository->isAccessible()) { - $this->resolvedRepository = $repository; + private function getResolvedRepository(): ?GitRepositoryInterface + { + if (false === $this->resolved) { + foreach ($this->repositories as $repository) { + if ($repository->isAccessible()) { + $this->resolvedRepository = $repository; - break; - } - } + break; + } + } - $this->resolved = true; - } + $this->resolved = true; + } - return $this->resolvedRepository; - } + return $this->resolvedRepository; + } } diff --git a/src/Repository/RuntimeCachedGitRepository.php b/src/Repository/RuntimeCachedGitRepository.php index e469b86..580cbf8 100644 --- a/src/Repository/RuntimeCachedGitRepository.php +++ b/src/Repository/RuntimeCachedGitRepository.php @@ -6,40 +6,40 @@ final class RuntimeCachedGitRepository implements GitRepositoryInterface { - private GitRepositoryInterface $inner; - - /** @var array */ - private array $cache = []; - - public function __construct(GitRepositoryInterface $inner) - { - $this->inner = $inner; - } - - public function getSource(): string - { - return $this->inner->getSource(); - } - - public function isAccessible(): bool - { - return $this->inner->isAccessible(); - } - - public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void - { - $this->inner->addHandler($commandClassname, $handler); - } - - public function handle(GitCommandInterface $command) - { - $commandId = (string) $command; - - return $this->cache[$commandId] ?? $this->cache[$commandId] = $this->inner->handle($command); - } - - public function supports(string $commandClassname): bool - { - return $this->inner->supports($commandClassname); - } + private GitRepositoryInterface $inner; + + /** @var array */ + private array $cache = []; + + public function __construct(GitRepositoryInterface $inner) + { + $this->inner = $inner; + } + + public function getSource(): string + { + return $this->inner->getSource(); + } + + public function isAccessible(): bool + { + return $this->inner->isAccessible(); + } + + public function addHandler(string $commandClassname, GitCommandHandlerInterface $handler): void + { + $this->inner->addHandler($commandClassname, $handler); + } + + public function handle(GitCommandInterface $command) + { + $commandId = (string) $command; + + return $this->cache[$commandId] ?? $this->cache[$commandId] = $this->inner->handle($command); + } + + public function supports(string $commandClassname): bool + { + return $this->inner->supports($commandClassname); + } } diff --git a/tests/Bridge/Nette/DI/ContainerFactory.php b/tests/Bridge/Nette/DI/ContainerFactory.php index 254bb96..08ddd71 100644 --- a/tests/Bridge/Nette/DI/ContainerFactory.php +++ b/tests/Bridge/Nette/DI/ContainerFactory.php @@ -4,42 +4,42 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Bridge\Nette\DI; -use Tester\Helpers; -use Nette\DI\Container; use Nette\Bootstrap\Configurator; -use function uniqid; -use function dirname; +use Nette\DI\Container; +use Tester\Helpers; use function debug_backtrace; +use function dirname; use function sys_get_temp_dir; +use function uniqid; final class ContainerFactory { - private function __construct() - { - } - - /** - * @param string|array $configFiles - */ - public static function create($configFiles, bool $debugMode): Container - { - $tempDir = sys_get_temp_dir() . '/' . uniqid('68publishers:TracyGitVersionPanel', true); - $backtrace = debug_backtrace(); - - Helpers::purge($tempDir); - - $configurator = new Configurator(); - $configurator->setTempDirectory($tempDir); - $configurator->setDebugMode($debugMode); - - $configurator->addParameters([ - 'cwd' => dirname($backtrace[0]['file']), - ]); - - foreach ((array) $configFiles as $configFile) { - $configurator->addConfig($configFile); - } - - return $configurator->createContainer(); - } + private function __construct() + { + } + + /** + * @param string|array $configFiles + */ + public static function create($configFiles, bool $debugMode): Container + { + $tempDir = sys_get_temp_dir() . '/' . uniqid('68publishers:TracyGitVersionPanel', true); + $backtrace = debug_backtrace(); + + Helpers::purge($tempDir); + + $configurator = new Configurator(); + $configurator->setTempDirectory($tempDir); + $configurator->setDebugMode($debugMode); + + $configurator->addParameters([ + 'cwd' => dirname($backtrace[0]['file']), + ]); + + foreach ((array) $configFiles as $configFile) { + $configurator->addConfig($configFile); + } + + return $configurator->createContainer(); + } } diff --git a/tests/Bridge/Nette/DI/TracyGitVersionExportExtensionTest.php b/tests/Bridge/Nette/DI/TracyGitVersionExportExtensionTest.php index 8091406..204a5ce 100644 --- a/tests/Bridge/Nette/DI/TracyGitVersionExportExtensionTest.php +++ b/tests/Bridge/Nette/DI/TracyGitVersionExportExtensionTest.php @@ -4,30 +4,30 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Bridge\Nette\DI; -use Tester\Assert; -use Tester\TestCase; use RuntimeException; -use SixtyEightPublishers\TracyGitVersion\Bridge\Nette\DI\TracyGitVersionExtension; use SixtyEightPublishers\TracyGitVersion\Bridge\Nette\DI\TracyGitVersionExportExtension; +use SixtyEightPublishers\TracyGitVersion\Bridge\Nette\DI\TracyGitVersionExtension; +use Tester\Assert; +use Tester\TestCase; use function sprintf; require __DIR__ . '/../../../bootstrap.php'; final class TracyGitVersionExportExtensionTest extends TestCase { - public function testBasicIntegration(): void - { - Assert::noError(static fn () => ContainerFactory::create(__DIR__ . '/config.export.neon', true)); - } + public function testBasicIntegration(): void + { + Assert::noError(static fn () => ContainerFactory::create(__DIR__ . '/config.export.neon', true)); + } - public function testBasicIntegrationWithoutMainExtension(): void - { - Assert::exception( - static fn () => ContainerFactory::create(__DIR__ . '/config.export.error.missingMainExtension.neon', false), - RuntimeException::class, - sprintf('The extension %s can be used only with %s.', TracyGitVersionExportExtension::class, TracyGitVersionExtension::class) - ); - } + public function testBasicIntegrationWithoutMainExtension(): void + { + Assert::exception( + static fn () => ContainerFactory::create(__DIR__ . '/config.export.error.missingMainExtension.neon', false), + RuntimeException::class, + sprintf('The extension %s can be used only with %s.', TracyGitVersionExportExtension::class, TracyGitVersionExtension::class), + ); + } } (new TracyGitVersionExportExtensionTest())->run(); diff --git a/tests/Bridge/Nette/DI/TracyGitVersionExtensionTest.php b/tests/Bridge/Nette/DI/TracyGitVersionExtensionTest.php index bb3d64b..ee58428 100644 --- a/tests/Bridge/Nette/DI/TracyGitVersionExtensionTest.php +++ b/tests/Bridge/Nette/DI/TracyGitVersionExtensionTest.php @@ -4,12 +4,12 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Bridge\Nette\DI; -use Tracy\Bar; -use Tester\Assert; -use Tester\TestCase; use Nette\DI\Container; use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\GitVersionPanel; use SixtyEightPublishers\TracyGitVersion\Repository\GitRepositoryInterface; +use Tester\Assert; +use Tester\TestCase; +use Tracy\Bar; use function assert; require __DIR__ . '/../../../bootstrap.php'; @@ -19,30 +19,30 @@ */ final class TracyGitVersionExtensionTest extends TestCase { - public function testBasicIntegrationInDebugMode(): void - { - $container = ContainerFactory::create(__DIR__ . '/config.main.neon', true); + public function testBasicIntegrationInDebugMode(): void + { + $container = ContainerFactory::create(__DIR__ . '/config.main.neon', true); - $bar = $container->getByType(Bar::class); - assert($bar instanceof Bar); + $bar = $container->getByType(Bar::class); + assert($bar instanceof Bar); - Assert::type(GitVersionPanel::class, $bar->getPanel(GitVersionPanel::class)); - Assert::type(GitRepositoryInterface::class, $container->getByType(GitRepositoryInterface::class, false)); - } + Assert::type(GitVersionPanel::class, $bar->getPanel(GitVersionPanel::class)); + Assert::type(GitRepositoryInterface::class, $container->getByType(GitRepositoryInterface::class, false)); + } - public function testBasicIntegrationWithoutDebugMode(): void - { - $container = ContainerFactory::create(__DIR__ . '/config.main.neon', false); + public function testBasicIntegrationWithoutDebugMode(): void + { + $container = ContainerFactory::create(__DIR__ . '/config.main.neon', false); - assert($container instanceof Container); + assert($container instanceof Container); - $bar = $container->getByType(Bar::class); + $bar = $container->getByType(Bar::class); - assert($bar instanceof Bar); + assert($bar instanceof Bar); - Assert::null($bar->getPanel(GitVersionPanel::class)); - Assert::type(GitRepositoryInterface::class, $container->getByType(GitRepositoryInterface::class, false)); - } + Assert::null($bar->getPanel(GitVersionPanel::class)); + Assert::type(GitRepositoryInterface::class, $container->getByType(GitRepositoryInterface::class, false)); + } } (new TracyGitVersionExtensionTest())->run(); diff --git a/tests/Bridge/Symfony/Console/Command/ExportRepositoryCommandTest.phpt b/tests/Bridge/Symfony/Console/Command/ExportRepositoryCommandTest.phpt index 661e5b0..b52e206 100644 --- a/tests/Bridge/Symfony/Console/Command/ExportRepositoryCommandTest.phpt +++ b/tests/Bridge/Symfony/Console/Command/ExportRepositoryCommandTest.phpt @@ -5,151 +5,139 @@ declare(strict_types=1); namespace SixtyEightPublishers\TracyGitVersion\Tests\Bridge\Symfony\Console\Command; use Exception; -use Tester\Assert; -use Tester\TestCase; -use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Console\Output\OutputInterface; -use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; use SixtyEightPublishers\TracyGitVersion\Bridge\Symfony\Console\Application; use SixtyEightPublishers\TracyGitVersion\Bridge\Symfony\Console\Command\ExportRepositoryCommand; -use function unlink; +use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; +use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Tester\CommandTester; +use Tester\Assert; +use Tester\TestCase; use function array_merge; use function file_exists; +use function file_get_contents; use function is_readable; use function json_decode; -use function file_get_contents; +use function unlink; require __DIR__ . '/../../../../bootstrap.php'; final class ExportRepositoryCommandTest extends TestCase { - public function testWithoutArguments(): void - { - Assert::exception( - fn () => $this->doTestExecute([]), - ExportConfigException::class, - 'Missing the option output_file in export config.' - ); - } - - public function testWithNonExistentConfig(): void - { - Assert::exception( - fn () => $this->doTestExecute([ - '--config' => __DIR__ . '/non-existent-config.php', - ]), - ExportConfigException::class, - 'Config file %a%/non-existent-config.php not found.' - ); - } - - public function testWithCustomConfig(): void - { - $commandTester = $this->doTestExecute([ - '--config' => __DIR__ . '/../../../../files/export/config.php', - ]); - - Assert::same(0, $commandTester->getStatusCode()); - - $filename = __DIR__ . '/../../../../files/output/git-repository-export.json'; - - $this->doTestExportedFile($filename); - $this->removeFile($filename); - } - - public function testWithCustomConfigAndOutputFileOption(): void - { - $filename = __DIR__ . '/../../../../files/output/git-repository-export-custom.json'; - $commandTester = $this->doTestExecute([ - '--config' => __DIR__ . '/../../../../files/export/config.php', - '--output-file' => $filename, - ]); - - Assert::same(0, $commandTester->getStatusCode()); - - $this->doTestExportedFile($filename); - $this->removeFile($filename); - } - - public function testDumpOnly(): void - { - $filename = __DIR__ . '/../../../../files/output/non-existent-export.json'; - $commandTester = $this->doTestExecute([ - '--config' => __DIR__ . '/../../../../files/export/config.php', - '--output-file' => $filename, - '--dump-only' => true, - ]); - - Assert::same(0, $commandTester->getStatusCode()); - Assert::false(file_exists($filename)); - } - - /** - * @param array $arguments - * - * @return \Symfony\Component\Console\Tester\CommandTester - */ - private function doTestExecute(array $arguments): CommandTester - { - $application = new Application(); - $application->add(new ExportRepositoryCommand()); - - $command = $application->find('export-repository'); - $commandTester = new CommandTester($command); - - $commandTester->execute( - array_merge(['command' => $command->getName()], $arguments), - [ - 'interactive' => false, - 'decorated' => false, - 'verbosity' => OutputInterface::VERBOSITY_DEBUG, - ] - ); - - return $commandTester; - } - - /** - * @param string $filename - * - * @throws Exception - */ - private function doTestExportedFile(string $filename): void - { - Assert::true(is_readable($filename)); - - $content = @file_get_contents($filename); - $json = []; - - Assert::type('string', $content); - - Assert::noError(static function () use ($content, &$json) { - $json = json_decode($content, true, 512, JSON_THROW_ON_ERROR); - }); - - Assert::equal([ - 'head' => [ - 'branch' => 'master', - 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', - ], - 'latest_tag' => [ - 'name' => 'v0.2.1', - 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114', - ], - ], $json); - } - - /** - * @param string $filename - * - * @return void - */ - private function removeFile(string $filename): void - { - if (file_exists($filename)) { - @unlink($filename); - } - } + public function testWithoutArguments(): void + { + Assert::exception( + fn () => $this->doTestExecute([]), + ExportConfigException::class, + 'Missing the option output_file in export config.', + ); + } + + public function testWithNonExistentConfig(): void + { + Assert::exception( + fn () => $this->doTestExecute([ + '--config' => __DIR__ . '/non-existent-config.php', + ]), + ExportConfigException::class, + 'Config file %a%/non-existent-config.php not found.', + ); + } + + public function testWithCustomConfig(): void + { + $commandTester = $this->doTestExecute([ + '--config' => __DIR__ . '/../../../../files/export/config.php', + ]); + + Assert::same(0, $commandTester->getStatusCode()); + + $filename = __DIR__ . '/../../../../files/output/git-repository-export.json'; + + $this->doTestExportedFile($filename); + $this->removeFile($filename); + } + + public function testWithCustomConfigAndOutputFileOption(): void + { + $filename = __DIR__ . '/../../../../files/output/git-repository-export-custom.json'; + $commandTester = $this->doTestExecute([ + '--config' => __DIR__ . '/../../../../files/export/config.php', + '--output-file' => $filename, + ]); + + Assert::same(0, $commandTester->getStatusCode()); + + $this->doTestExportedFile($filename); + $this->removeFile($filename); + } + + public function testDumpOnly(): void + { + $filename = __DIR__ . '/../../../../files/output/non-existent-export.json'; + $commandTester = $this->doTestExecute([ + '--config' => __DIR__ . '/../../../../files/export/config.php', + '--output-file' => $filename, + '--dump-only' => true, + ]); + + Assert::same(0, $commandTester->getStatusCode()); + Assert::false(file_exists($filename)); + } + + private function doTestExecute(array $arguments): CommandTester + { + $application = new Application(); + $application->add(new ExportRepositoryCommand()); + + $command = $application->find('export-repository'); + $commandTester = new CommandTester($command); + + $commandTester->execute( + array_merge(['command' => $command->getName()], $arguments), + [ + 'interactive' => false, + 'decorated' => false, + 'verbosity' => OutputInterface::VERBOSITY_DEBUG, + ], + ); + + return $commandTester; + } + + /** + * @throws Exception + */ + private function doTestExportedFile(string $filename): void + { + Assert::true(is_readable($filename)); + + $content = @file_get_contents($filename); + $json = []; + + Assert::type('string', $content); + + Assert::noError(static function () use ($content, &$json) { + $json = json_decode($content, true, 512, JSON_THROW_ON_ERROR); + }); + + Assert::equal([ + 'head' => [ + 'branch' => 'master', + 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', + ], + 'latest_tag' => [ + 'name' => 'v0.2.1', + 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114', + ], + ], $json); + } + + private function removeFile(string $filename): void + { + if (file_exists($filename)) { + @unlink($filename); + } + } } (new ExportRepositoryCommandTest())->run(); diff --git a/tests/Bridge/Tracy/GitVersionPanelTest.php b/tests/Bridge/Tracy/GitVersionPanelTest.php index 2a1e347..75b6f77 100644 --- a/tests/Bridge/Tracy/GitVersionPanelTest.php +++ b/tests/Bridge/Tracy/GitVersionPanelTest.php @@ -4,26 +4,26 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Bridge\Tracy; +use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\GitVersionPanel; use Tester\Assert; use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\GitVersionPanel; require __DIR__ . '/../../bootstrap.php'; final class GitVersionPanelTest extends TestCase { - public function testDefaultPanelRendering(): void - { - $panel = GitVersionPanel::createDefault(__DIR__ . '/../../files/nested-directory-1', 'test-git'); - - Assert::noError(static function () use ($panel) { - $panel->getTab(); - }); - - Assert::noError(static function () use ($panel) { - $panel->getPanel(); - }); - } + public function testDefaultPanelRendering(): void + { + $panel = GitVersionPanel::createDefault(__DIR__ . '/../../files/nested-directory-1', 'test-git'); + + Assert::noError(static function () use ($panel) { + $panel->getTab(); + }); + + Assert::noError(static function () use ($panel) { + $panel->getPanel(); + }); + } } (new GitVersionPanelTest())->run(); diff --git a/tests/Bridge/Tracy/HelpersTest.php b/tests/Bridge/Tracy/HelpersTest.php index 03a5920..e59147d 100644 --- a/tests/Bridge/Tracy/HelpersTest.php +++ b/tests/Bridge/Tracy/HelpersTest.php @@ -4,22 +4,22 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Bridge\Tracy; +use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Helpers; use Tester\Assert; use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Bridge\Tracy\Helpers; require __DIR__ . '/../../bootstrap.php'; final class HelpersTest extends TestCase { - public function testTemplateRendering(): void - { - $content = Helpers::renderTemplate(__DIR__ . '/../../files/templates/test.phtml', [ - 'foo' => 'FOO', - ]); + public function testTemplateRendering(): void + { + $content = Helpers::renderTemplate(__DIR__ . '/../../files/templates/test.phtml', [ + 'foo' => 'FOO', + ]); - Assert::contains("FOO", $content); - } + Assert::contains("FOO", $content); + } } (new HelpersTest())->run(); diff --git a/tests/Export/ConfigTest.php b/tests/Export/ConfigTest.php index 49af195..b09a17e 100644 --- a/tests/Export/ConfigTest.php +++ b/tests/Export/ConfigTest.php @@ -4,67 +4,67 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Export; +use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; +use SixtyEightPublishers\TracyGitVersion\Export\Config; use Tester\Assert; use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Export\Config; -use SixtyEightPublishers\TracyGitVersion\Exception\ExportConfigException; require __DIR__ . '/../bootstrap.php'; final class ConfigTest extends TestCase { - public function testBehaviourOfOptionsMethods(): void - { - $config = Config::create(); - - $config->setOption('opt_1', 'value_1'); - $config->setOption('opt_2', 'value_2'); - $config->setOption('opt_3', 'value_3_1'); - - # basic get - Assert::true($config->hasOption('opt_1')); - Assert::true($config->hasOption('opt_2')); - Assert::true($config->hasOption('opt_3')); - Assert::same('value_1', $config->getOption('opt_1')); - Assert::same('value_2', $config->getOption('opt_2')); - Assert::same('value_3_1', $config->getOption('opt_3')); - - # missing option - Assert::false($config->hasOption('opt_4')); - - Assert::exception( - static function () use ($config) { - $config->getOption('opt_4'); - }, - ExportConfigException::class, - 'Missing the option opt_4 in export config.' - ); - - # merge options => creates an array - $config->mergeOption('opt_3', 'value_3_2'); - - Assert::equal(['value_3_1', 'value_3_2'], $config->getOption('opt_3')); - - # merge options with an array - $config->mergeOption('opt_3', [ - 'value_3_3', - 'value_3_4', - ]); - - Assert::equal(['value_3_1', 'value_3_2', 'value_3_3', 'value_3_4'], $config->getOption('opt_3')); - - # merge new option (creates array) - $config->mergeOption('opt_4', 'value_4'); - - Assert::equal(['value_4'], $config->getOption('opt_4')); - - # override options - $config->setOption('opt_2', 'foo'); - $config->setOption('opt_3', 'bar'); - - Assert::same('foo', $config->getOption('opt_2')); - Assert::same('bar', $config->getOption('opt_3')); - } + public function testBehaviourOfOptionsMethods(): void + { + $config = Config::create(); + + $config->setOption('opt_1', 'value_1'); + $config->setOption('opt_2', 'value_2'); + $config->setOption('opt_3', 'value_3_1'); + + # basic get + Assert::true($config->hasOption('opt_1')); + Assert::true($config->hasOption('opt_2')); + Assert::true($config->hasOption('opt_3')); + Assert::same('value_1', $config->getOption('opt_1')); + Assert::same('value_2', $config->getOption('opt_2')); + Assert::same('value_3_1', $config->getOption('opt_3')); + + # missing option + Assert::false($config->hasOption('opt_4')); + + Assert::exception( + static function () use ($config) { + $config->getOption('opt_4'); + }, + ExportConfigException::class, + 'Missing the option opt_4 in export config.', + ); + + # merge options => creates an array + $config->mergeOption('opt_3', 'value_3_2'); + + Assert::equal(['value_3_1', 'value_3_2'], $config->getOption('opt_3')); + + # merge options with an array + $config->mergeOption('opt_3', [ + 'value_3_3', + 'value_3_4', + ]); + + Assert::equal(['value_3_1', 'value_3_2', 'value_3_3', 'value_3_4'], $config->getOption('opt_3')); + + # merge new option (creates array) + $config->mergeOption('opt_4', 'value_4'); + + Assert::equal(['value_4'], $config->getOption('opt_4')); + + # override options + $config->setOption('opt_2', 'foo'); + $config->setOption('opt_3', 'bar'); + + Assert::same('foo', $config->getOption('opt_2')); + Assert::same('bar', $config->getOption('opt_3')); + } } (new ConfigTest())->run(); diff --git a/tests/Export/LocalDirectoryExporterTest.php b/tests/Export/LocalDirectoryExporterTest.php index 17b4076..9a3abf6 100644 --- a/tests/Export/LocalDirectoryExporterTest.php +++ b/tests/Export/LocalDirectoryExporterTest.php @@ -4,55 +4,55 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Export; -use Tester\Assert; -use Tester\TestCase; use SixtyEightPublishers\TracyGitVersion\Export\Config; use SixtyEightPublishers\TracyGitVersion\Export\LocalDirectoryExporter; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../bootstrap.php'; final class LocalDirectoryExporterTest extends TestCase { - public function testWithDefaultConfig(): void - { - $exporter = new LocalDirectoryExporter(); - $config = Config::createDefault(); - - # directory must be overridden - $config->setGitDirectory(GitDirectory::createFromGitDirectory(__DIR__ . '/../files/test-git')); - - $export = $exporter->export($config, null); - - Assert::equal([ - 'head' => [ - 'branch' => 'master', - 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', - ], - 'latest_tag' => [ - 'name' => 'v0.2.1', - 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114', - ], - ], $export); - } - - public function testWithDefaultConfigAndDetachedHead(): void - { - $exporter = new LocalDirectoryExporter(); - $config = Config::createDefault(); - - # directory must be override - $config->setGitDirectory(GitDirectory::createFromGitDirectory(__DIR__ . '/../files/test-git-detached')); - - $export = $exporter->export($config, null); - - Assert::equal([ - 'head' => [ - 'branch' => null, - 'commit_hash' => '3416c5b1831774dd209e489100b3a7c1e333690d', - ], - ], $export); - } + public function testWithDefaultConfig(): void + { + $exporter = new LocalDirectoryExporter(); + $config = Config::createDefault(); + + # directory must be overridden + $config->setGitDirectory(GitDirectory::createFromGitDirectory(__DIR__ . '/../files/test-git')); + + $export = $exporter->export($config, null); + + Assert::equal([ + 'head' => [ + 'branch' => 'master', + 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', + ], + 'latest_tag' => [ + 'name' => 'v0.2.1', + 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114', + ], + ], $export); + } + + public function testWithDefaultConfigAndDetachedHead(): void + { + $exporter = new LocalDirectoryExporter(); + $config = Config::createDefault(); + + # directory must be override + $config->setGitDirectory(GitDirectory::createFromGitDirectory(__DIR__ . '/../files/test-git-detached')); + + $export = $exporter->export($config, null); + + Assert::equal([ + 'head' => [ + 'branch' => null, + 'commit_hash' => '3416c5b1831774dd209e489100b3a7c1e333690d', + ], + ], $export); + } } (new LocalDirectoryExporterTest())->run(); diff --git a/tests/Export/PartialExporter/HeadExporterTest.php b/tests/Export/PartialExporter/HeadExporterTest.php index 9fc5735..f182a7a 100644 --- a/tests/Export/PartialExporter/HeadExporterTest.php +++ b/tests/Export/PartialExporter/HeadExporterTest.php @@ -4,58 +4,58 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Export\PartialExporter; -use Tester\Assert; -use Tester\TestCase; use SixtyEightPublishers\TracyGitVersion\Export\Config; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; -use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; use SixtyEightPublishers\TracyGitVersion\Export\PartialExporter\HeadExporter; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetHeadCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../../bootstrap.php'; final class HeadExporterTest extends TestCase { - public function testExportHead(): void - { - $exporter = new HeadExporter(); + public function testExportHead(): void + { + $exporter = new HeadExporter(); - $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git'), [ - GetHeadCommand::class => new GetHeadCommandHandler(), - ]); + $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git'), [ + GetHeadCommand::class => new GetHeadCommandHandler(), + ]); - $config = Config::create(); + $config = Config::create(); - $export = $exporter->export($config, $gitRepository); + $export = $exporter->export($config, $gitRepository); - Assert::equal([ - 'head' => [ - 'branch' => 'master', - 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', - ], - ], $export); - } + Assert::equal([ + 'head' => [ + 'branch' => 'master', + 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', + ], + ], $export); + } - public function testExportDetachedHead(): void - { - $exporter = new HeadExporter(); + public function testExportDetachedHead(): void + { + $exporter = new HeadExporter(); - $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git-detached'), [ - GetHeadCommand::class => new GetHeadCommandHandler(), - ]); + $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git-detached'), [ + GetHeadCommand::class => new GetHeadCommandHandler(), + ]); - $config = Config::create(); + $config = Config::create(); - $export = $exporter->export($config, $gitRepository); + $export = $exporter->export($config, $gitRepository); - Assert::equal([ - 'head' => [ - 'branch' => null, - 'commit_hash' => '3416c5b1831774dd209e489100b3a7c1e333690d', - ], - ], $export); - } + Assert::equal([ + 'head' => [ + 'branch' => null, + 'commit_hash' => '3416c5b1831774dd209e489100b3a7c1e333690d', + ], + ], $export); + } } (new HeadExporterTest())->run(); diff --git a/tests/Export/PartialExporter/LatestTagExporterTest.php b/tests/Export/PartialExporter/LatestTagExporterTest.php index 4e5a020..8dedb0a 100644 --- a/tests/Export/PartialExporter/LatestTagExporterTest.php +++ b/tests/Export/PartialExporter/LatestTagExporterTest.php @@ -4,53 +4,53 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Export\PartialExporter; -use Tester\Assert; -use Tester\TestCase; use SixtyEightPublishers\TracyGitVersion\Export\Config; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; -use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; use SixtyEightPublishers\TracyGitVersion\Export\PartialExporter\LatestTagExporter; +use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetLatestTagCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../../bootstrap.php'; final class LatestTagExporterTest extends TestCase { - public function testExportLatestTag(): void - { - $exporter = new LatestTagExporter(); + public function testExportLatestTag(): void + { + $exporter = new LatestTagExporter(); - $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git'), [ - GetLatestTagCommand::class => new GetLatestTagCommandHandler(), - ]); + $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git'), [ + GetLatestTagCommand::class => new GetLatestTagCommandHandler(), + ]); - $config = Config::create(); + $config = Config::create(); - $export = $exporter->export($config, $gitRepository); + $export = $exporter->export($config, $gitRepository); - Assert::equal([ - 'latest_tag' => [ - 'name' => 'v0.2.1', - 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114', - ], - ], $export); - } + Assert::equal([ + 'latest_tag' => [ + 'name' => 'v0.2.1', + 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114', + ], + ], $export); + } - public function testExportWithoutTag(): void - { - $exporter = new LatestTagExporter(); + public function testExportWithoutTag(): void + { + $exporter = new LatestTagExporter(); - $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git-detached'), [ - GetLatestTagCommand::class => new GetLatestTagCommandHandler(), - ]); + $gitRepository = new LocalGitRepository(GitDirectory::createFromGitDirectory(__DIR__ . '/../../files/test-git-detached'), [ + GetLatestTagCommand::class => new GetLatestTagCommandHandler(), + ]); - $config = Config::create(); + $config = Config::create(); - $export = $exporter->export($config, $gitRepository); + $export = $exporter->export($config, $gitRepository); - Assert::equal([], $export); - } + Assert::equal([], $export); + } } (new LatestTagExporterTest())->run(); diff --git a/tests/Fixtures/Command/BarCommand.php b/tests/Fixtures/Command/BarCommand.php index 75543fc..cb3225b 100644 --- a/tests/Fixtures/Command/BarCommand.php +++ b/tests/Fixtures/Command/BarCommand.php @@ -9,20 +9,20 @@ final class BarCommand implements GitCommandInterface { - private int $num; + private int $num; - public function __construct(int $num) - { - $this->num = $num; - } + public function __construct(int $num) + { + $this->num = $num; + } - public function getNum(): int - { - return $this->num; - } + public function getNum(): int + { + return $this->num; + } - public function __toString(): string - { - return sprintf('BAR(%d)', $this->num); - } + public function __toString(): string + { + return sprintf('BAR(%d)', $this->num); + } } diff --git a/tests/Fixtures/Command/FooCommand.php b/tests/Fixtures/Command/FooCommand.php index a1fbf75..0afe7ca 100644 --- a/tests/Fixtures/Command/FooCommand.php +++ b/tests/Fixtures/Command/FooCommand.php @@ -8,8 +8,8 @@ final class FooCommand implements GitCommandInterface { - public function __toString(): string - { - return 'FOO()'; - } + public function __toString(): string + { + return 'FOO()'; + } } diff --git a/tests/Fixtures/CommandHandler/BarCommandHandler.php b/tests/Fixtures/CommandHandler/BarCommandHandler.php index cf702db..080d1a9 100644 --- a/tests/Fixtures/CommandHandler/BarCommandHandler.php +++ b/tests/Fixtures/CommandHandler/BarCommandHandler.php @@ -4,17 +4,17 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\BarCommand; use SixtyEightPublishers\TracyGitVersion\Repository\GitCommandHandlerInterface; +use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\BarCommand; final class BarCommandHandler implements GitCommandHandlerInterface { - public int $callingCounter = 0; + public int $callingCounter = 0; - public function __invoke(BarCommand $command): int - { - $this->callingCounter++; + public function __invoke(BarCommand $command): int + { + $this->callingCounter++; - return $command->getNum() * 2; - } + return $command->getNum() * 2; + } } diff --git a/tests/Fixtures/CommandHandler/ExportedFooCommandHandler.php b/tests/Fixtures/CommandHandler/ExportedFooCommandHandler.php index 7c81b1c..456dc58 100644 --- a/tests/Fixtures/CommandHandler/ExportedFooCommandHandler.php +++ b/tests/Fixtures/CommandHandler/ExportedFooCommandHandler.php @@ -4,17 +4,17 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\AbstractExportedCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; final class ExportedFooCommandHandler extends AbstractExportedCommandHandler { - public int $callingCounter = 0; + public int $callingCounter = 0; - public function __invoke(FooCommand $command): ?string - { - $this->callingCounter++; + public function __invoke(FooCommand $command): ?string + { + $this->callingCounter++; - return $this->getExportedValue()['foo'] ?? null; - } + return $this->getExportedValue()['foo'] ?? null; + } } diff --git a/tests/Fixtures/CommandHandler/FooCommandHandler.php b/tests/Fixtures/CommandHandler/FooCommandHandler.php index bca434b..845feda 100644 --- a/tests/Fixtures/CommandHandler/FooCommandHandler.php +++ b/tests/Fixtures/CommandHandler/FooCommandHandler.php @@ -4,17 +4,17 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler; -use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; use SixtyEightPublishers\TracyGitVersion\Repository\GitCommandHandlerInterface; +use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; final class FooCommandHandler implements GitCommandHandlerInterface { - public int $callingCounter = 0; + public int $callingCounter = 0; - public function __invoke(FooCommand $command): string - { - $this->callingCounter++; + public function __invoke(FooCommand $command): string + { + $this->callingCounter++; - return 'foo'; - } + return 'foo'; + } } diff --git a/tests/Fixtures/CommandHandler/LocalDirectoryFooCommandHandler.php b/tests/Fixtures/CommandHandler/LocalDirectoryFooCommandHandler.php index 77dfa41..428c977 100644 --- a/tests/Fixtures/CommandHandler/LocalDirectoryFooCommandHandler.php +++ b/tests/Fixtures/CommandHandler/LocalDirectoryFooCommandHandler.php @@ -5,26 +5,26 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler; use SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException; -use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\AbstractLocalDirectoryCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; final class LocalDirectoryFooCommandHandler extends AbstractLocalDirectoryCommandHandler { - public int $callingCounter = 0; + public int $callingCounter = 0; - public function __invoke(FooCommand $command): string - { - $this->callingCounter++; + public function __invoke(FooCommand $command): string + { + $this->callingCounter++; - return $this->getGitDirectoryPath() . '/foo'; - } + return $this->getGitDirectoryPath() . '/foo'; + } - protected function getGitDirectoryPath(): string - { - try { - return (string) $this->getGitDirectory(); - } catch (GitDirectoryException $e) { - return 'undefined'; - } - } + protected function getGitDirectoryPath(): string + { + try { + return (string) $this->getGitDirectory(); + } catch (GitDirectoryException $e) { + return 'undefined'; + } + } } diff --git a/tests/Fixtures/Repository/SimpleGitRepository.php b/tests/Fixtures/Repository/SimpleGitRepository.php index a22ca8b..fa09b3b 100644 --- a/tests/Fixtures/Repository/SimpleGitRepository.php +++ b/tests/Fixtures/Repository/SimpleGitRepository.php @@ -8,25 +8,25 @@ final class SimpleGitRepository extends AbstractGitRepository { - private string $source; + private string $source; - private bool $accessible; + private bool $accessible; - public function __construct(string $source, bool $accessible, array $handlers = []) - { - parent::__construct($handlers); + public function __construct(string $source, bool $accessible, array $handlers = []) + { + parent::__construct($handlers); - $this->source = $source; - $this->accessible = $accessible; - } + $this->source = $source; + $this->accessible = $accessible; + } - public function getSource(): string - { - return $this->source; - } + public function getSource(): string + { + return $this->source; + } - public function isAccessible(): bool - { - return $this->accessible; - } + public function isAccessible(): bool + { + return $this->accessible; + } } diff --git a/tests/Repository/Export/CommandHandler/GetHeadCommandHandlerTest.php b/tests/Repository/Export/CommandHandler/GetHeadCommandHandlerTest.php index c03defb..79fab6a 100644 --- a/tests/Repository/Export/CommandHandler/GetHeadCommandHandlerTest.php +++ b/tests/Repository/Export/CommandHandler/GetHeadCommandHandlerTest.php @@ -4,47 +4,47 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository\Export\CommandHandler; -use Tester\Assert; -use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\GetHeadCommandHandler; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../../../bootstrap.php'; final class GetHeadCommandHandlerTest extends TestCase { - public function testCommandHandling(): void - { - $handler = new GetHeadCommandHandler([ - 'head' => [ - 'branch' => 'master', - 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', - ], - ]); - $head = $handler(new GetHeadCommand()); - - Assert::type(Head::class, $head); - Assert::same('master', $head->getBranch()); - Assert::same('59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', $head->getCommitHash()->getValue()); - Assert::false($head->isDetached()); - } - - public function testCommandHandlingOnDetachedHead(): void - { - $handler = new GetHeadCommandHandler([ - 'head' => [ - 'branch' => null, - 'commit_hash' => '3416c5b1831774dd209e489100b3a7c1e333690d', - ], - ]); - $head = $handler(new GetHeadCommand()); - - Assert::type(Head::class, $head); - Assert::null($head->getBranch()); - Assert::same('3416c5b1831774dd209e489100b3a7c1e333690d', $head->getCommitHash()->getValue()); - Assert::true($head->isDetached()); - } + public function testCommandHandling(): void + { + $handler = new GetHeadCommandHandler([ + 'head' => [ + 'branch' => 'master', + 'commit_hash' => '59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', + ], + ]); + $head = $handler(new GetHeadCommand()); + + Assert::type(Head::class, $head); + Assert::same('master', $head->getBranch()); + Assert::same('59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', $head->getCommitHash()->getValue()); + Assert::false($head->isDetached()); + } + + public function testCommandHandlingOnDetachedHead(): void + { + $handler = new GetHeadCommandHandler([ + 'head' => [ + 'branch' => null, + 'commit_hash' => '3416c5b1831774dd209e489100b3a7c1e333690d', + ], + ]); + $head = $handler(new GetHeadCommand()); + + Assert::type(Head::class, $head); + Assert::null($head->getBranch()); + Assert::same('3416c5b1831774dd209e489100b3a7c1e333690d', $head->getCommitHash()->getValue()); + Assert::true($head->isDetached()); + } } (new GetHeadCommandHandlerTest())->run(); diff --git a/tests/Repository/Export/CommandHandler/GetLatestTagCommandHandlerTest.php b/tests/Repository/Export/CommandHandler/GetLatestTagCommandHandlerTest.php index 1a2818b..06b0ff7 100644 --- a/tests/Repository/Export/CommandHandler/GetLatestTagCommandHandlerTest.php +++ b/tests/Repository/Export/CommandHandler/GetLatestTagCommandHandlerTest.php @@ -4,35 +4,35 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository\Export\CommandHandler; -use Tester\Assert; -use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; use SixtyEightPublishers\TracyGitVersion\Repository\Export\CommandHandler\GetLatestTagCommandHandler; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../../../bootstrap.php'; final class GetLatestTagCommandHandlerTest extends TestCase { - public function testCommandHandling(): void - { - $handler = new GetLatestTagCommandHandler([ - 'latest_tag' => ['name' => 'v0.2.1', 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114'], - ]); - $tag = $handler(new GetLatestTagCommand()); - - Assert::type(Tag::class, $tag); - Assert::same('v0.2.1', $tag->getName()); - Assert::same('8f2c308e3a5330b7924634edd7aa38eec97a4114', $tag->getCommitHash()->getValue()); - } - - public function testCommandHandlingWithoutDefinedTag(): void - { - $handler = new GetLatestTagCommandHandler([]); - $tag = $handler(new GetLatestTagCommand()); - - Assert::null($tag); - } + public function testCommandHandling(): void + { + $handler = new GetLatestTagCommandHandler([ + 'latest_tag' => ['name' => 'v0.2.1', 'commit_hash' => '8f2c308e3a5330b7924634edd7aa38eec97a4114'], + ]); + $tag = $handler(new GetLatestTagCommand()); + + Assert::type(Tag::class, $tag); + Assert::same('v0.2.1', $tag->getName()); + Assert::same('8f2c308e3a5330b7924634edd7aa38eec97a4114', $tag->getCommitHash()->getValue()); + } + + public function testCommandHandlingWithoutDefinedTag(): void + { + $handler = new GetLatestTagCommandHandler([]); + $tag = $handler(new GetLatestTagCommand()); + + Assert::null($tag); + } } (new GetLatestTagCommandHandlerTest())->run(); diff --git a/tests/Repository/ExportedGitRepositoryTest.phpt b/tests/Repository/ExportedGitRepositoryTest.phpt index 62532d7..4116df5 100644 --- a/tests/Repository/ExportedGitRepositoryTest.phpt +++ b/tests/Repository/ExportedGitRepositoryTest.phpt @@ -4,117 +4,117 @@ declare(strict_types=1); namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository; -use Tester\Assert; -use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Repository\ExportedGitRepository; +use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\ExportedGitRepository; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\BarCommand; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; -use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\BarCommandHandler; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\ExportedFooCommandHandler; +use Tester\Assert; +use Tester\TestCase; use function sprintf; require __DIR__ . '/../bootstrap.php'; final class ExportedGitRepositoryTest extends TestCase { - public function testRepositorySource(): void - { - $repository = $this->createValidGitRepository([]); - - Assert::same('test', $repository->getSource()); - } - - public function testIsAccessibleMethod(): void - { - $repository = $this->createValidGitRepository([]); - - Assert::true($repository->isAccessible()); - - $repository = $this->createInvalidGitRepository([]); - - Assert::false($repository->isAccessible()); - } - - public function testSupportsMethod(): void - { - $handlers = [ - FooCommand::class => new ExportedFooCommandHandler(), - BarCommand::class => new BarCommandHandler(), - ]; - - # do assertions on valid repository - $repository = $this->createValidGitRepository($handlers); - - Assert::true($repository->supports(FooCommand::class)); - Assert::true($repository->supports(BarCommand::class)); - Assert::false($repository->supports('BazCommand')); - - # do assertions on invalid repository - $repository = $this->createInvalidGitRepository($handlers); - - Assert::false($repository->supports(FooCommand::class)); - Assert::false($repository->supports(BarCommand::class)); - Assert::false($repository->supports('BazCommand')); - } - - public function testCommandHandling(): void - { - # prepare commands and handlers - $handlers = [ - FooCommand::class => new ExportedFooCommandHandler(), - BarCommand::class => new BarCommandHandler(), - ]; - - $fooCommand = new FooCommand(); - $barCommand = new BarCommand(100); - - # do assertions on valid repository - $repository = $this->createValidGitRepository($handlers); - - Assert::same('FOO', $repository->handle($fooCommand)); - Assert::same(200, $repository->handle($barCommand)); - - $unhandledCommand = new GetHeadCommand(); - - Assert::exception( - static function () use ($repository, $unhandledCommand) { - $repository->handle($unhandledCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $unhandledCommand) - ); - - # do assertions on invalid repository - $repository = $this->createInvalidGitRepository($handlers); - - Assert::exception( - static function () use ($repository, $fooCommand) { - $repository->handle($fooCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $fooCommand) - ); - - Assert::exception( - static function () use ($repository, $barCommand) { - $repository->handle($barCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $barCommand) - ); - } - - private function createValidGitRepository(array $handlers): ExportedGitRepository - { - return new ExportedGitRepository(__DIR__ . '/../files/export/test.json', $handlers, 'test'); - } - - private function createInvalidGitRepository(array $handlers): ExportedGitRepository - { - return new ExportedGitRepository(__DIR__ . '/../files/export/non-existent-export.json', $handlers, 'test'); - } + public function testRepositorySource(): void + { + $repository = $this->createValidGitRepository([]); + + Assert::same('test', $repository->getSource()); + } + + public function testIsAccessibleMethod(): void + { + $repository = $this->createValidGitRepository([]); + + Assert::true($repository->isAccessible()); + + $repository = $this->createInvalidGitRepository([]); + + Assert::false($repository->isAccessible()); + } + + public function testSupportsMethod(): void + { + $handlers = [ + FooCommand::class => new ExportedFooCommandHandler(), + BarCommand::class => new BarCommandHandler(), + ]; + + # do assertions on valid repository + $repository = $this->createValidGitRepository($handlers); + + Assert::true($repository->supports(FooCommand::class)); + Assert::true($repository->supports(BarCommand::class)); + Assert::false($repository->supports('BazCommand')); + + # do assertions on invalid repository + $repository = $this->createInvalidGitRepository($handlers); + + Assert::false($repository->supports(FooCommand::class)); + Assert::false($repository->supports(BarCommand::class)); + Assert::false($repository->supports('BazCommand')); + } + + public function testCommandHandling(): void + { + # prepare commands and handlers + $handlers = [ + FooCommand::class => new ExportedFooCommandHandler(), + BarCommand::class => new BarCommandHandler(), + ]; + + $fooCommand = new FooCommand(); + $barCommand = new BarCommand(100); + + # do assertions on valid repository + $repository = $this->createValidGitRepository($handlers); + + Assert::same('FOO', $repository->handle($fooCommand)); + Assert::same(200, $repository->handle($barCommand)); + + $unhandledCommand = new GetHeadCommand(); + + Assert::exception( + static function () use ($repository, $unhandledCommand) { + $repository->handle($unhandledCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $unhandledCommand), + ); + + # do assertions on invalid repository + $repository = $this->createInvalidGitRepository($handlers); + + Assert::exception( + static function () use ($repository, $fooCommand) { + $repository->handle($fooCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $fooCommand), + ); + + Assert::exception( + static function () use ($repository, $barCommand) { + $repository->handle($barCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $barCommand), + ); + } + + private function createValidGitRepository(array $handlers): ExportedGitRepository + { + return new ExportedGitRepository(__DIR__ . '/../files/export/test.json', $handlers, 'test'); + } + + private function createInvalidGitRepository(array $handlers): ExportedGitRepository + { + return new ExportedGitRepository(__DIR__ . '/../files/export/non-existent-export.json', $handlers, 'test'); + } } (new ExportedGitRepositoryTest())->run(); diff --git a/tests/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandlerTest.php b/tests/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandlerTest.php index ed30c1e..a382ec9 100644 --- a/tests/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandlerTest.php +++ b/tests/Repository/LocalDirectory/CommandHandler/GetHeadCommandHandlerTest.php @@ -4,38 +4,38 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository\LocalDirectory\CommandHandler; -use Tester\Assert; -use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Head; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetHeadCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../../../bootstrap.php'; final class GetHeadCommandHandlerTest extends TestCase { - public function testCommandHandling(): void - { - $handler = new GetHeadCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git')); - $head = $handler(new GetHeadCommand()); - - Assert::type(Head::class, $head); - Assert::same('master', $head->getBranch()); - Assert::same('59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', $head->getCommitHash()->getValue()); - Assert::false($head->isDetached()); - } - - public function testCommandHandlingOnDetachedHead(): void - { - $handler = new GetHeadCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git-detached')); - $head = $handler(new GetHeadCommand()); - - Assert::type(Head::class, $head); - Assert::null($head->getBranch()); - Assert::same('3416c5b1831774dd209e489100b3a7c1e333690d', $head->getCommitHash()->getValue()); - Assert::true($head->isDetached()); - } + public function testCommandHandling(): void + { + $handler = new GetHeadCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git')); + $head = $handler(new GetHeadCommand()); + + Assert::type(Head::class, $head); + Assert::same('master', $head->getBranch()); + Assert::same('59d7c7f0e34f4db5ba7f5c28e3eb4630339d4382', $head->getCommitHash()->getValue()); + Assert::false($head->isDetached()); + } + + public function testCommandHandlingOnDetachedHead(): void + { + $handler = new GetHeadCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git-detached')); + $head = $handler(new GetHeadCommand()); + + Assert::type(Head::class, $head); + Assert::null($head->getBranch()); + Assert::same('3416c5b1831774dd209e489100b3a7c1e333690d', $head->getCommitHash()->getValue()); + Assert::true($head->isDetached()); + } } (new GetHeadCommandHandlerTest())->run(); diff --git a/tests/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandlerTest.php b/tests/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandlerTest.php index 8c59804..358a36f 100644 --- a/tests/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandlerTest.php +++ b/tests/Repository/LocalDirectory/CommandHandler/GetLatestTagCommandHandlerTest.php @@ -4,34 +4,34 @@ namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository\LocalDirectory\CommandHandler; -use Tester\Assert; -use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetLatestTagCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\Entity\Tag; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\CommandHandler\GetLatestTagCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../../../bootstrap.php'; final class GetLatestTagCommandHandlerTest extends TestCase { - public function testCommandHandling(): void - { - $handler = new GetLatestTagCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git')); - $tag = $handler(new GetLatestTagCommand()); - - Assert::type(Tag::class, $tag); - Assert::same('v0.2.1', $tag->getName()); - Assert::same('8f2c308e3a5330b7924634edd7aa38eec97a4114', $tag->getCommitHash()->getValue()); - } - - public function testCommandHandlingWithoutDefinedTags(): void - { - $handler = new GetLatestTagCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git-detached')); - $tag = $handler(new GetLatestTagCommand()); - - Assert::null($tag); - } + public function testCommandHandling(): void + { + $handler = new GetLatestTagCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git')); + $tag = $handler(new GetLatestTagCommand()); + + Assert::type(Tag::class, $tag); + Assert::same('v0.2.1', $tag->getName()); + Assert::same('8f2c308e3a5330b7924634edd7aa38eec97a4114', $tag->getCommitHash()->getValue()); + } + + public function testCommandHandlingWithoutDefinedTags(): void + { + $handler = new GetLatestTagCommandHandler(GitDirectory::createFromGitDirectory(__DIR__ . '/../../../files/test-git-detached')); + $tag = $handler(new GetLatestTagCommand()); + + Assert::null($tag); + } } (new GetLatestTagCommandHandlerTest())->run(); diff --git a/tests/Repository/LocalDirectory/GitDirectoryTest.phpt b/tests/Repository/LocalDirectory/GitDirectoryTest.phpt index e5d7118..90957b5 100644 --- a/tests/Repository/LocalDirectory/GitDirectoryTest.phpt +++ b/tests/Repository/LocalDirectory/GitDirectoryTest.phpt @@ -4,63 +4,63 @@ declare(strict_types=1); namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository\LocalDirectory; -use Tester\Assert; -use Tester\TestCase; use SixtyEightPublishers\TracyGitVersion\Exception\GitDirectoryException; use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; -use function sprintf; +use Tester\Assert; +use Tester\TestCase; use function realpath; +use function sprintf; require __DIR__ . '/../../bootstrap.php'; final class GitDirectoryTest extends TestCase { - public function testExceptionShouldBeThrownOnInvalidWorkingDirectory(): void - { - $workingDirectory = __DIR__ . '/non/existent/directory'; - - Assert::exception( - static function () use ($workingDirectory) { - $_ = (string) GitDirectory::createAutoDetected($workingDirectory); - }, - GitDirectoryException::class, - sprintf('The path %s is not valid directory.', $workingDirectory) - ); - } - - public function testExceptionShouldBeThrownOnInvalidGitDirectory(): void - { - $gitDirectory = __DIR__ . '/non/existent/.git'; - - Assert::exception( - static function () use ($gitDirectory) { - GitDirectory::createFromGitDirectory($gitDirectory); - }, - GitDirectoryException::class, - sprintf('The path %s is not valid git directory.', $gitDirectory) - ); - } - - public function testCreateGitDirectoryDirectly(): void - { - $dir = __DIR__ . '/../../files/test-git'; - $gitDirectory = GitDirectory::createFromGitDirectory($dir); - - Assert::same(realpath($dir), (string) $gitDirectory); - } - - public function testCreateGitDirectoryFromWorkingDirectory(): void - { - $realGitDirectoryPath = realpath(__DIR__ . '/../../files/test-git'); - - $gitDirectory = GitDirectory::createAutoDetected(__DIR__ . '/../../files', 'test-git'); - - Assert::same($realGitDirectoryPath, (string) $gitDirectory); - - $gitDirectory = GitDirectory::createAutoDetected(__DIR__ . '/../../files/nested-directory-1/nested-directory-2', 'test-git'); - - Assert::same($realGitDirectoryPath, (string) $gitDirectory); - } + public function testExceptionShouldBeThrownOnInvalidWorkingDirectory(): void + { + $workingDirectory = __DIR__ . '/non/existent/directory'; + + Assert::exception( + static function () use ($workingDirectory) { + $_ = (string) GitDirectory::createAutoDetected($workingDirectory); + }, + GitDirectoryException::class, + sprintf('The path %s is not valid directory.', $workingDirectory), + ); + } + + public function testExceptionShouldBeThrownOnInvalidGitDirectory(): void + { + $gitDirectory = __DIR__ . '/non/existent/.git'; + + Assert::exception( + static function () use ($gitDirectory) { + GitDirectory::createFromGitDirectory($gitDirectory); + }, + GitDirectoryException::class, + sprintf('The path %s is not valid git directory.', $gitDirectory), + ); + } + + public function testCreateGitDirectoryDirectly(): void + { + $dir = __DIR__ . '/../../files/test-git'; + $gitDirectory = GitDirectory::createFromGitDirectory($dir); + + Assert::same(realpath($dir), (string) $gitDirectory); + } + + public function testCreateGitDirectoryFromWorkingDirectory(): void + { + $realGitDirectoryPath = realpath(__DIR__ . '/../../files/test-git'); + + $gitDirectory = GitDirectory::createAutoDetected(__DIR__ . '/../../files', 'test-git'); + + Assert::same($realGitDirectoryPath, (string) $gitDirectory); + + $gitDirectory = GitDirectory::createAutoDetected(__DIR__ . '/../../files/nested-directory-1/nested-directory-2', 'test-git'); + + Assert::same($realGitDirectoryPath, (string) $gitDirectory); + } } (new GitDirectoryTest())->run(); diff --git a/tests/Repository/LocalGitRepositoryTest.phpt b/tests/Repository/LocalGitRepositoryTest.phpt index a9740ea..0094f2f 100644 --- a/tests/Repository/LocalGitRepositoryTest.phpt +++ b/tests/Repository/LocalGitRepositoryTest.phpt @@ -4,16 +4,16 @@ declare(strict_types=1); namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository; -use Tester\Assert; -use Tester\TestCase; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; +use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; use SixtyEightPublishers\TracyGitVersion\Repository\Command\GetHeadCommand; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; +use SixtyEightPublishers\TracyGitVersion\Repository\LocalGitRepository; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\BarCommand; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; -use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; -use SixtyEightPublishers\TracyGitVersion\Repository\LocalDirectory\GitDirectory; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\BarCommandHandler; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\LocalDirectoryFooCommandHandler; +use Tester\Assert; +use Tester\TestCase; use function sprintf; use function sys_get_temp_dir; @@ -21,107 +21,107 @@ require __DIR__ . '/../bootstrap.php'; final class LocalGitRepositoryTest extends TestCase { - public function testRepositorySource(): void - { - $repository = $this->createValidGitRepository([]); - - Assert::same('test', $repository->getSource()); - } - - public function testIsAccessibleMethod(): void - { - $repository = $this->createValidGitRepository([]); - - Assert::true($repository->isAccessible()); - - $repository = $this->createInvalidGitRepository([]); - - Assert::false($repository->isAccessible()); - } - - public function testSupportsMethod(): void - { - $handlers = [ - FooCommand::class => new LocalDirectoryFooCommandHandler(), - BarCommand::class => new BarCommandHandler(), - ]; - - # do assertions on valid repository - $repository = $this->createValidGitRepository($handlers); - - Assert::true($repository->supports(FooCommand::class)); - Assert::true($repository->supports(BarCommand::class)); - Assert::false($repository->supports('BazCommand')); - - # do assertions on invalid repository - $repository = $this->createInvalidGitRepository($handlers); - - Assert::false($repository->supports(FooCommand::class)); - Assert::false($repository->supports(BarCommand::class)); - Assert::false($repository->supports('BazCommand')); - } - - public function testCommandHandling(): void - { - # prepare commands and handlers - $handlers = [ - FooCommand::class => new LocalDirectoryFooCommandHandler(), - BarCommand::class => new BarCommandHandler(), - ]; - - $fooCommand = new FooCommand(); - $barCommand = new BarCommand(100); - - # do assertions on valid repository - $repository = $this->createValidGitRepository($handlers); - - Assert::same($this->getValidGitDirectoryPath() . '/foo', $repository->handle($fooCommand)); - Assert::same(200, $repository->handle($barCommand)); - - $unhandledCommand = new GetHeadCommand(); - - Assert::exception( - static function () use ($repository, $unhandledCommand) { - $repository->handle($unhandledCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $unhandledCommand) - ); - - # do assertions on invalid repository - $repository = $this->createInvalidGitRepository($handlers); - - Assert::exception( - static function () use ($repository, $fooCommand) { - $repository->handle($fooCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $fooCommand) - ); - - Assert::exception( - static function () use ($repository, $barCommand) { - $repository->handle($barCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $barCommand) - ); - } - - private function createValidGitRepository(array $handlers): LocalGitRepository - { - return new LocalGitRepository(GitDirectory::createFromGitDirectory($this->getValidGitDirectoryPath()), $handlers, 'test'); - } - - private function createInvalidGitRepository(array $handlers): LocalGitRepository - { - return new LocalGitRepository(GitDirectory::createAutoDetected(sys_get_temp_dir(), 'non-existent-git-directory'), $handlers, 'test'); - } - - private function getValidGitDirectoryPath(): string - { - return realpath(__DIR__ . '/../files/test-git'); - } + public function testRepositorySource(): void + { + $repository = $this->createValidGitRepository([]); + + Assert::same('test', $repository->getSource()); + } + + public function testIsAccessibleMethod(): void + { + $repository = $this->createValidGitRepository([]); + + Assert::true($repository->isAccessible()); + + $repository = $this->createInvalidGitRepository([]); + + Assert::false($repository->isAccessible()); + } + + public function testSupportsMethod(): void + { + $handlers = [ + FooCommand::class => new LocalDirectoryFooCommandHandler(), + BarCommand::class => new BarCommandHandler(), + ]; + + # do assertions on valid repository + $repository = $this->createValidGitRepository($handlers); + + Assert::true($repository->supports(FooCommand::class)); + Assert::true($repository->supports(BarCommand::class)); + Assert::false($repository->supports('BazCommand')); + + # do assertions on invalid repository + $repository = $this->createInvalidGitRepository($handlers); + + Assert::false($repository->supports(FooCommand::class)); + Assert::false($repository->supports(BarCommand::class)); + Assert::false($repository->supports('BazCommand')); + } + + public function testCommandHandling(): void + { + # prepare commands and handlers + $handlers = [ + FooCommand::class => new LocalDirectoryFooCommandHandler(), + BarCommand::class => new BarCommandHandler(), + ]; + + $fooCommand = new FooCommand(); + $barCommand = new BarCommand(100); + + # do assertions on valid repository + $repository = $this->createValidGitRepository($handlers); + + Assert::same($this->getValidGitDirectoryPath() . '/foo', $repository->handle($fooCommand)); + Assert::same(200, $repository->handle($barCommand)); + + $unhandledCommand = new GetHeadCommand(); + + Assert::exception( + static function () use ($repository, $unhandledCommand) { + $repository->handle($unhandledCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $unhandledCommand), + ); + + # do assertions on invalid repository + $repository = $this->createInvalidGitRepository($handlers); + + Assert::exception( + static function () use ($repository, $fooCommand) { + $repository->handle($fooCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $fooCommand), + ); + + Assert::exception( + static function () use ($repository, $barCommand) { + $repository->handle($barCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $barCommand), + ); + } + + private function createValidGitRepository(array $handlers): LocalGitRepository + { + return new LocalGitRepository(GitDirectory::createFromGitDirectory($this->getValidGitDirectoryPath()), $handlers, 'test'); + } + + private function createInvalidGitRepository(array $handlers): LocalGitRepository + { + return new LocalGitRepository(GitDirectory::createAutoDetected(sys_get_temp_dir(), 'non-existent-git-directory'), $handlers, 'test'); + } + + private function getValidGitDirectoryPath(): string + { + return realpath(__DIR__ . '/../files/test-git'); + } } (new LocalGitRepositoryTest())->run(); diff --git a/tests/Repository/ResolvableGitRepositoryTest.phpt b/tests/Repository/ResolvableGitRepositoryTest.phpt index cff2f69..d77d445 100644 --- a/tests/Repository/ResolvableGitRepositoryTest.phpt +++ b/tests/Repository/ResolvableGitRepositoryTest.phpt @@ -4,120 +4,120 @@ declare(strict_types=1); namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository; -use Tester\Assert; -use Tester\TestCase; +use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; +use SixtyEightPublishers\TracyGitVersion\Repository\ResolvableGitRepository; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\BarCommand; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\ResolvableGitRepository; -use SixtyEightPublishers\TracyGitVersion\Exception\UnhandledCommandException; -use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Repository\SimpleGitRepository; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\BarCommandHandler; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\FooCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Repository\SimpleGitRepository; +use Tester\Assert; +use Tester\TestCase; use function sprintf; require __DIR__ . '/../bootstrap.php'; final class ResolvableGitRepositoryTest extends TestCase { - public function testRepositorySource(): void - { - # first is accessible - $repository = $this->createRepository([ - new SimpleGitRepository('first', true, []), - new SimpleGitRepository('second', true, []), - ]); - - Assert::same('first', $repository->getSource()); - - # first is not accessible - $repository = $this->createRepository([ - new SimpleGitRepository('first', false, []), - new SimpleGitRepository('second', true, []), - ]); - - Assert::same('second', $repository->getSource()); - - # unresolved state - $repository = $this->createRepository([ - new SimpleGitRepository('first', false, []), - new SimpleGitRepository('second', false, []), - ]); - - Assert::same('unresolved', $repository->getSource()); - - $repository = $this->createRepository([]); - - Assert::same('unresolved', $repository->getSource()); - } - - public function testIsAccessibleMethod(): void - { - # first is accessible - $repository = $this->createRepository([ - new SimpleGitRepository('first', true, []), - new SimpleGitRepository('second', true, []), - ]); - - Assert::true($repository->isAccessible()); - - # second is accessible - $repository = $this->createRepository([ - new SimpleGitRepository('first', false, []), - new SimpleGitRepository('second', true, []), - ]); - - Assert::true($repository->isAccessible()); - - # none is accessible - $repository = $this->createRepository([ - new SimpleGitRepository('first', false, []), - new SimpleGitRepository('second', false, []), - ]); - - Assert::false($repository->isAccessible()); - - $repository = $this->createRepository([]); - - Assert::false($repository->isAccessible()); - } - - public function testSupportsMethod(): void - { - $repository = $this->createRepository([ - new SimpleGitRepository('first', true, [FooCommand::class => new FooCommandHandler()]), - new SimpleGitRepository('second', true, [BarCommand::class => new BarCommandHandler()]), - ]); - - Assert::true($repository->supports(FooCommand::class)); - Assert::false($repository->supports(BarCommand::class)); # false because the first one is accessible - Assert::false($repository->supports('BazCommand')); - } - - public function testCommandHandling(): void - { - $repository = $this->createRepository([ - new SimpleGitRepository('first', true, [BarCommand::class => new BarCommandHandler()]), - new SimpleGitRepository('second', true, [FooCommand::class => new FooCommandHandler()]), - ]); - - Assert::same(200, $repository->handle(new BarCommand(100))); - - # FooCommand must be unhandled because the first repository doesn't supports it - $unhandledCommand = new FooCommand(); - - Assert::exception( - static function () use ($repository, $unhandledCommand) { - $repository->handle($unhandledCommand); - }, - UnhandledCommandException::class, - sprintf('Can\'t handle git command %s.', $unhandledCommand) - ); - } - - private function createRepository(array $repositories): ResolvableGitRepository - { - return new ResolvableGitRepository($repositories); - } + public function testRepositorySource(): void + { + # first is accessible + $repository = $this->createRepository([ + new SimpleGitRepository('first', true, []), + new SimpleGitRepository('second', true, []), + ]); + + Assert::same('first', $repository->getSource()); + + # first is not accessible + $repository = $this->createRepository([ + new SimpleGitRepository('first', false, []), + new SimpleGitRepository('second', true, []), + ]); + + Assert::same('second', $repository->getSource()); + + # unresolved state + $repository = $this->createRepository([ + new SimpleGitRepository('first', false, []), + new SimpleGitRepository('second', false, []), + ]); + + Assert::same('unresolved', $repository->getSource()); + + $repository = $this->createRepository([]); + + Assert::same('unresolved', $repository->getSource()); + } + + public function testIsAccessibleMethod(): void + { + # first is accessible + $repository = $this->createRepository([ + new SimpleGitRepository('first', true, []), + new SimpleGitRepository('second', true, []), + ]); + + Assert::true($repository->isAccessible()); + + # second is accessible + $repository = $this->createRepository([ + new SimpleGitRepository('first', false, []), + new SimpleGitRepository('second', true, []), + ]); + + Assert::true($repository->isAccessible()); + + # none is accessible + $repository = $this->createRepository([ + new SimpleGitRepository('first', false, []), + new SimpleGitRepository('second', false, []), + ]); + + Assert::false($repository->isAccessible()); + + $repository = $this->createRepository([]); + + Assert::false($repository->isAccessible()); + } + + public function testSupportsMethod(): void + { + $repository = $this->createRepository([ + new SimpleGitRepository('first', true, [FooCommand::class => new FooCommandHandler()]), + new SimpleGitRepository('second', true, [BarCommand::class => new BarCommandHandler()]), + ]); + + Assert::true($repository->supports(FooCommand::class)); + Assert::false($repository->supports(BarCommand::class)); # false because the first one is accessible + Assert::false($repository->supports('BazCommand')); + } + + public function testCommandHandling(): void + { + $repository = $this->createRepository([ + new SimpleGitRepository('first', true, [BarCommand::class => new BarCommandHandler()]), + new SimpleGitRepository('second', true, [FooCommand::class => new FooCommandHandler()]), + ]); + + Assert::same(200, $repository->handle(new BarCommand(100))); + + # FooCommand must be unhandled because the first repository doesn't supports it + $unhandledCommand = new FooCommand(); + + Assert::exception( + static function () use ($repository, $unhandledCommand) { + $repository->handle($unhandledCommand); + }, + UnhandledCommandException::class, + sprintf('Can\'t handle git command %s.', $unhandledCommand), + ); + } + + private function createRepository(array $repositories): ResolvableGitRepository + { + return new ResolvableGitRepository($repositories); + } } (new ResolvableGitRepositoryTest())->run(); diff --git a/tests/Repository/RuntimeCachedGitRepositoryTest.phpt b/tests/Repository/RuntimeCachedGitRepositoryTest.phpt index 5936c1e..171ab3e 100644 --- a/tests/Repository/RuntimeCachedGitRepositoryTest.phpt +++ b/tests/Repository/RuntimeCachedGitRepositoryTest.phpt @@ -4,73 +4,73 @@ declare(strict_types=1); namespace SixtyEightPublishers\TracyGitVersion\Tests\Repository; -use Tester\Assert; -use Tester\TestCase; +use SixtyEightPublishers\TracyGitVersion\Repository\RuntimeCachedGitRepository; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\BarCommand; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Command\FooCommand; -use SixtyEightPublishers\TracyGitVersion\Repository\RuntimeCachedGitRepository; -use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Repository\SimpleGitRepository; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\BarCommandHandler; use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\CommandHandler\FooCommandHandler; +use SixtyEightPublishers\TracyGitVersion\Tests\Fixtures\Repository\SimpleGitRepository; +use Tester\Assert; +use Tester\TestCase; require __DIR__ . '/../bootstrap.php'; final class RuntimeCachedGitRepositoryTest extends TestCase { - public function testRepositorySource(): void - { - $repository = $this->createRepository([]); - - Assert::same('test', $repository->getSource()); - } - - public function testIsAccessibleMethod(): void - { - $repository = $this->createRepository([]); - - Assert::true($repository->isAccessible()); - } - - public function testSupportsMethod(): void - { - $repository = $this->createRepository([ - FooCommand::class => new FooCommandHandler(), - BarCommand::class => new BarCommandHandler(), - ]); - - Assert::true($repository->supports(FooCommand::class)); - Assert::true($repository->supports(BarCommand::class)); - Assert::false($repository->supports('BazCommand')); - } - - public function testCommandHandling(): void - { - $fooCommandHandler = new FooCommandHandler(); - $barCommandHandler = new BarCommandHandler(); - - $repository = $this->createRepository([ - FooCommand::class => $fooCommandHandler, - BarCommand::class => $barCommandHandler, - ]); - - Assert::same('foo', $repository->handle(new FooCommand())); - Assert::same(200, $repository->handle(new BarCommand(100))); - - # duplicated calling - Assert::same('foo', $repository->handle(new FooCommand())); - Assert::same(200, $repository->handle(new BarCommand(100))); - - # new calling (different argument) - Assert::same(60, $repository->handle(new BarCommand(30))); - - Assert::same(1, $fooCommandHandler->callingCounter); - Assert::same(2, $barCommandHandler->callingCounter); - } - - private function createRepository(array $handlers): RuntimeCachedGitRepository - { - return new RuntimeCachedGitRepository(new SimpleGitRepository('test', true, $handlers)); - } + public function testRepositorySource(): void + { + $repository = $this->createRepository([]); + + Assert::same('test', $repository->getSource()); + } + + public function testIsAccessibleMethod(): void + { + $repository = $this->createRepository([]); + + Assert::true($repository->isAccessible()); + } + + public function testSupportsMethod(): void + { + $repository = $this->createRepository([ + FooCommand::class => new FooCommandHandler(), + BarCommand::class => new BarCommandHandler(), + ]); + + Assert::true($repository->supports(FooCommand::class)); + Assert::true($repository->supports(BarCommand::class)); + Assert::false($repository->supports('BazCommand')); + } + + public function testCommandHandling(): void + { + $fooCommandHandler = new FooCommandHandler(); + $barCommandHandler = new BarCommandHandler(); + + $repository = $this->createRepository([ + FooCommand::class => $fooCommandHandler, + BarCommand::class => $barCommandHandler, + ]); + + Assert::same('foo', $repository->handle(new FooCommand())); + Assert::same(200, $repository->handle(new BarCommand(100))); + + # duplicated calling + Assert::same('foo', $repository->handle(new FooCommand())); + Assert::same(200, $repository->handle(new BarCommand(100))); + + # new calling (different argument) + Assert::same(60, $repository->handle(new BarCommand(30))); + + Assert::same(1, $fooCommandHandler->callingCounter); + Assert::same(2, $barCommandHandler->callingCounter); + } + + private function createRepository(array $handlers): RuntimeCachedGitRepository + { + return new RuntimeCachedGitRepository(new SimpleGitRepository('test', true, $handlers)); + } } (new RuntimeCachedGitRepositoryTest())->run(); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 513df7f..eb14668 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -5,8 +5,8 @@ use Tester\Environment; if (@!include __DIR__ . '/../vendor/autoload.php') { - echo 'Install Nette Tester using `composer install`'; - exit(1); + echo 'Install Nette Tester using `composer install`'; + exit(1); } Environment::setup(); @@ -14,5 +14,5 @@ date_default_timezone_set('Europe/Prague'); if (PHP_VERSION_ID >= 80200) { - error_reporting(~E_DEPRECATED); + error_reporting(~E_DEPRECATED); } diff --git a/tracy-git-version b/tracy-git-version index 8a398b8..30611ac 100644 --- a/tracy-git-version +++ b/tracy-git-version @@ -5,15 +5,15 @@ $possibleAutoloadFiles = [__DIR__ . '/../../autoload.php', __DIR__ . '/../autolo $autoloadFile = null; foreach ($possibleAutoloadFiles as $possibleAutoloadFile) { - if (file_exists($possibleAutoloadFile)) { - $autoloadFile = $possibleAutoloadFile; + if (file_exists($possibleAutoloadFile)) { + $autoloadFile = $possibleAutoloadFile; - break; - } + break; + } } if (null === $autoloadFile) { - throw new RuntimeException('Unable to find composer autoload.php file.'); + throw new RuntimeException('Unable to find composer autoload.php file.'); } require_once $autoloadFile;