From 4a49ff4ea030c7d11e348c1623259133de9f40ee Mon Sep 17 00:00:00 2001 From: Kay W Date: Mon, 14 Aug 2023 16:57:14 +0800 Subject: [PATCH] Prevent release on wrong branch (#43) * When executing the release, if the current branch is not the same as the default branch, user confirmation is required before proceeding --- packages/Release/Command/ReleaseCommand.php | 7 ++++++ .../ReleaseWorker/TagVersionReleaseWorker.php | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/packages/Release/Command/ReleaseCommand.php b/packages/Release/Command/ReleaseCommand.php index 0cfe004cd3..9c9293a1bd 100644 --- a/packages/Release/Command/ReleaseCommand.php +++ b/packages/Release/Command/ReleaseCommand.php @@ -81,6 +81,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->releaseWorkerReporter->printMetadata($releaseWorker); if (! $isDryRun) { + if (method_exists($releaseWorker,'shouldConfirm') + && $releaseWorker->shouldConfirm()['whenTrue']() + && ! $this->symfonyStyle->confirm($releaseWorker->shouldConfirm()['message']) + ){ + return self::FAILURE; + } + $releaseWorker->work($version); } } diff --git a/packages/Release/ReleaseWorker/TagVersionReleaseWorker.php b/packages/Release/ReleaseWorker/TagVersionReleaseWorker.php index cd70277459..3c0b67f633 100644 --- a/packages/Release/ReleaseWorker/TagVersionReleaseWorker.php +++ b/packages/Release/ReleaseWorker/TagVersionReleaseWorker.php @@ -22,6 +22,17 @@ public function __construct( $this->branchName = $parameterProvider->provideStringParameter(Option::DEFAULT_BRANCH_NAME); } + /** + * @return array + */ + public function shouldConfirm(): array + { + return [ + 'whenTrue' => fn(): bool => self::getCurrentBranch() !== self::getDefaultBranch(), + 'message'=> sprintf('Do you want to release it on the [ %s ] branch?',self::getCurrentBranch()) + ]; + } + public function work(Version $version): void { try { @@ -42,4 +53,18 @@ public function getDescription(Version $version): string { return sprintf('Add local tag "%s"', $version->getOriginalString()); } + + private function getCurrentBranch(): string + { + exec('git rev-parse --abbrev-ref HEAD',$outputs); + + return $outputs[0]; + } + + private function getDefaultBranch(): string + { + exec("git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'",$outputs); + + return $outputs[0]; + } }