From 02841cce8da0fb09d289ffa0b1b497743e149eb2 Mon Sep 17 00:00:00 2001 From: Ralf Lang Date: Fri, 20 Nov 2026 12:42:55 +0100 Subject: [PATCH] feat: Add an option for --clean-release This deletes any pollution in the repo not belonging to the release. It is potentially destructive, don't run this on your developer checkout. --- src/Helper/Git.php | 112 ++++++++++++++---- src/Module/Release.php | 12 +- src/Release/HordeRelease.php | 24 ++++ src/Runner/Release.php | 9 +- .../Release/HordeReleaseBranchGateTest.php | 27 +++++ test/unit/Helper/GitAuthenticationTest.php | 92 ++++++++++++++ 6 files changed, 247 insertions(+), 29 deletions(-) diff --git a/src/Helper/Git.php b/src/Helper/Git.php index ce75bb28..74c813c8 100644 --- a/src/Helper/Git.php +++ b/src/Helper/Git.php @@ -613,22 +613,7 @@ public function fetch(string $localDir, bool $force = false): SystemCallResult $cmd .= ' --force'; } - $githubHttps = false; - if ($this->authentication !== null && !$this->shell->isPretend()) { - $remotes = $this->execInDirectory($this->gitBin . ' remote -v', $localDir); - if ($remotes->getReturnValue() !== 0) { - throw new RuntimeException('Could not read Git remotes.'); - } - foreach ($remotes->getOutputArray() as $remote) { - if (preg_match('/^\S+\s+(\S+)\s+\(fetch\)$/', $remote, $matches) - && $this->isGitHubHttpsUrl($matches[1])) { - $githubHttps = true; - break; - } - } - } - - return $this->execNetwork($cmd, $localDir, $githubHttps); + return $this->execNetwork($cmd, $localDir, $this->remoteIsGitHubHttps($localDir)); } private function isGitHubHttpsUrl(string $url): bool @@ -637,6 +622,82 @@ private function isGitHubHttpsUrl(string $url): bool && strtolower((string) parse_url($url, PHP_URL_HOST)) === 'github.com'; } + /** + * Determine whether a configured remote points at an HTTPS github.com URL + * + * Only inspects remotes when authentication is attached and we are not in + * pretend mode. Otherwise there is nothing to authenticate and no command + * will actually run. + * + * @param string $localDir Full path to repo + * @param string|null $remote Restrict the check to this remote name or + * null to match any configured remote (used by + * `fetch --all`). + */ + private function remoteIsGitHubHttps(string $localDir, ?string $remote = null): bool + { + if ($this->authentication === null || $this->shell->isPretend()) { + return false; + } + + $remotes = $this->execInDirectory($this->gitBin . ' remote -v', $localDir); + if ($remotes->getReturnValue() !== 0) { + throw new RuntimeException('Could not read Git remotes.'); + } + foreach ($remotes->getOutputArray() as $line) { + if (preg_match('/^(\S+)\s+(\S+)\s+\((?:fetch|push)\)$/', $line, $matches) + && ($remote === null || $matches[1] === $remote) + && $this->isGitHubHttpsUrl($matches[2])) { + return true; + } + } + + return false; + } + + /** + * Enforce a pristine state of the checkout + * + * WARNING: This is destructive. + * + * - remote tip of a branch: fetch, + * - hard-reset onto origin/ + * - remove every untracked or ignored file + * + * `git clean -fdx` permanently deletes untracked and ignored + * files (vendor/, build output, local configs). + * + * + * In pretend mode the shell prints the commands instead of running them + * and token-authenticates the fetch when a GitHub HTTPS remote is configured. + * + * @param string $localDir Full path to repo + * @param string $branch Branch whose origin tip to reset onto + * @param string $remote Remote name, defaults to origin + */ + public function cleanRelease(string $localDir, string $branch, string $remote = 'origin'): void + { + $fetchCmd = sprintf('%s fetch %s', $this->gitBin, escapeshellarg($remote)); + $this->execNetwork( + $fetchCmd, + $localDir, + $this->remoteIsGitHubHttps($localDir, $remote) + ); + + $this->shell->exec( + sprintf( + '%s reset --hard %s', + $this->gitBin, + escapeshellarg($remote . '/' . $branch) + ), + $localDir + ); + $this->shell->exec( + sprintf('%s clean -fdx', $this->gitBin), + $localDir + ); + } + private function execNetwork(string $command, ?string $directory, bool $githubHttps): SystemCallResult { if ($this->authentication === null || $this->output === null || $this->shell->isPretend()) { @@ -798,18 +859,19 @@ public function checkoutIsClean(string $localDir): bool */ public function push(string $localDir, $remote = 'origin', ?string $ref = null, bool $force = false, bool $tags = false): void { - $forceCmd = $force ? '--force' : ''; - $tagsCmd = $tags ? '--tags' : ''; $cmd = sprintf( - 'git push %s %s --set-upstream %s %s --follow-tags', - $forceCmd, - $tagsCmd, - $remote, - $ref ?? $this->getCurrentBranch($localDir) + '%s push %s%s--set-upstream %s %s --follow-tags', + $this->gitBin, + $force ? '--force ' : '', + $tags ? '--tags ' : '', + escapeshellarg((string) $remote), + escapeshellarg($ref ?? $this->getCurrentBranch($localDir)) ); - $this->shell->system( + + $this->execNetwork( $cmd, - $localDir + $localDir, + $this->remoteIsGitHubHttps($localDir, (string) $remote) ); } diff --git a/src/Module/Release.php b/src/Module/Release.php index efdf2b6c..0397bd2f 100644 --- a/src/Module/Release.php +++ b/src/Module/Release.php @@ -105,6 +105,16 @@ public function getOptionGroupOptions(): array . 'for offline hotfix releases where the Packagist round-trips for ' . 'the platform resolver are unwelcome.', ] + ), new Option( + '--clean-release', + [ + 'action' => 'store_true', + 'help' => 'Force the checkout to a pristine state ' + . 'matching the remote: "git fetch origin && git reset --hard ' + . 'origin/ && git clean -fdx". DESTRUCTIVE: permanently ' + . 'removes all untracked and ignored files (vendor/, build output, ' + . 'local configs). Only prints in --pretend mode.', + ] )]; } @@ -196,7 +206,7 @@ public function getHelp($action): string */ public function getContextOptionHelp(): array { - return ['--pretend' => '', '--config' => '', '--releaseserver' => '', '--releasedir' => '', '--next-note' => '', '--next-version' => '', '--version-part' => '', '--next-relstate' => '', '--next-apistate' => '', '--from' => '', '--horde-user' => '', '--horde-pass' => '', '--web-dir' => '', '--dump' => '', '--skip-ci-refresh' => '']; + return ['--pretend' => '', '--config' => '', '--releaseserver' => '', '--releasedir' => '', '--next-note' => '', '--next-version' => '', '--version-part' => '', '--next-relstate' => '', '--next-apistate' => '', '--from' => '', '--horde-user' => '', '--horde-pass' => '', '--web-dir' => '', '--dump' => '', '--skip-ci-refresh' => '', '--clean-release' => '']; } /** diff --git a/src/Release/HordeRelease.php b/src/Release/HordeRelease.php index 824cab0b..99fe38b2 100644 --- a/src/Release/HordeRelease.php +++ b/src/Release/HordeRelease.php @@ -75,6 +75,12 @@ public function run(Component $component, array $options = []) $this->output->warn('[PRETEND MODE] No changes will be made'); } + // Optional: + // Force a clean repo state, potentially destroying any vendor dir or configs + if (!empty($options['clean_release'])) { + $this->runCleanRelease(); + } + // Create context for task execution $context = new Context($component, $options); @@ -171,6 +177,24 @@ public function run(Component $component, array $options = []) } } + /** + * Enforce a pristine state matching the remote tip of the current branch + * + * Resets onto origin/ and removes every untracked and + * ignored file. DESTRUCTIVE: Warns loudly first. --pretend mode only prints what would be done. + */ + private function runCleanRelease(): void + { + $localDir = (string) $this->directory; + $branch = $this->gitHelper->getCurrentBranch($localDir); + + $this->output->warn('[CLEAN RELEASE] Forcing a pristine checkout. This is DESTRUCTIVE:'); + $this->output->warn(" git fetch origin && git reset --hard origin/{$branch} && git clean -fdx"); + $this->output->warn(' All untracked and ignored files (vendor/, build output, local configs) will be removed.'); + + $this->gitHelper->cleanRelease($localDir, $branch); + } + /** * Resolve the current branch's release role and refuse branches that * have no role at all. diff --git a/src/Runner/Release.php b/src/Runner/Release.php index 585a0cda..e19ed7f3 100644 --- a/src/Runner/Release.php +++ b/src/Runner/Release.php @@ -97,9 +97,11 @@ public function run(): void && $this->arguments[0] == 'release' && $this->arguments[1] == 'h6') { $path = new ComponentDirectory($this->component->getComponentDirectory()); - $gitHelper = new GitHelper(); + $pretend = !empty($this->options['pretend']); + $gitHelper = (new GitHelper(options: ['pretend' => $pretend])) + ->withGitHubAuthentication($this->authFactory, $this->output); $composerHelper = new ComposerHelper(); - $shell = new Shell(); + $shell = new Shell($this->output, $pretend); // Get GitHubChecker and GitHubReleaseCreator from dependencies $githubChecker = new GitHubChecker($gitHelper); @@ -123,7 +125,8 @@ public function run(): void $githubReleaseCreator, $this->qcTasks, $shell, - $this->branchRoles + $this->branchRoles, + $pretend ); $release->run($this->component, $this->options); diff --git a/test/Unit/Release/HordeReleaseBranchGateTest.php b/test/Unit/Release/HordeReleaseBranchGateTest.php index 0ed1fd8a..2b2315a8 100644 --- a/test/Unit/Release/HordeReleaseBranchGateTest.php +++ b/test/Unit/Release/HordeReleaseBranchGateTest.php @@ -149,4 +149,31 @@ public function testReleaseFeatureOnStablePasses(): void $this->enforce($release, BranchRoles::ROLE_RELEASE, 'minor', 'stable', false); $this->addToAssertionCount(1); } + + // --- clean-release preflight --------------------------------------- + + public function testCleanReleaseResetsOntoCurrentBranchRemoteTip(): void + { + $git = $this->createMock(GitHelper::class); + $git->method('getCurrentBranch')->willReturn('FRAMEWORK_9_9'); + $git->expects($this->once())->method('cleanRelease') + ->with('/path/to/component', 'FRAMEWORK_9_9'); + + $directory = $this->createStub(ComponentDirectory::class); + $directory->method('__toString')->willReturn('/path/to/component'); + + $release = new HordeRelease( + $this->createStub(ComposerHelper::class), + $git, + $directory, + $this->createStub(Output::class), + $this->createStub(GitHubReleaseCreator::class), + $this->createStub(QcTasks::class), + $this->createStub(ShellHelper::class), + new BranchRoles('FRAMEWORK_9_9'), + true + ); + + (new ReflectionMethod($release, 'runCleanRelease'))->invoke($release); + } } diff --git a/test/unit/Helper/GitAuthenticationTest.php b/test/unit/Helper/GitAuthenticationTest.php index a307348d..634e8ea4 100644 --- a/test/unit/Helper/GitAuthenticationTest.php +++ b/test/unit/Helper/GitAuthenticationTest.php @@ -121,6 +121,98 @@ public function testPretendDoesNotObtainAppToken(): void $this->assertSame(0, $git->fetch('/checkout')->getReturnValue()); } + #[DataProvider('fetchResults')] + public function testHttpsPushUsesAppThenAtMostOnePatRetry(array $exitCodes): void + { + $authentication = $this->createPartialMock(AuthenticationFactory::class, ['hasGitHubAppAuth', 'createConfig']); + $authentication->method('hasGitHubAppAuth')->willReturn(true); + $authentication->expects($this->once())->method('createConfig') + ->willReturn(new GithubApiConfig(accessToken: 'short-lived-app-token')); + $output = $this->createMock(Output::class); + $output->expects(count($exitCodes) === 1 ? $this->never() : $this->once())->method('warn'); + $shell = $this->createMock(Shell::class); + $shell->method('isPretend')->willReturn(false); + // One exec() for the `remote -v` probe used to decide the remote is + // an HTTPS github.com URL. getCurrentBranch is not reached because the + // ref is passed explicitly. + $shell->expects($this->once())->method('exec') + ->with($this->stringContains('remote -v'), '/checkout') + ->willReturn(new SystemCallResult(['origin https://github.com/horde/components.git (push)'], 0)); + $attempt = 0; + $shell->expects($this->exactly(count($exitCodes)))->method('execWithEnvironment') + ->willReturnCallback(function (string $command, array $environment, string $directory) use (&$attempt, $exitCodes) { + $token = $attempt === 0 ? 'short-lived-app-token' : 'environment-pat'; + $this->assertStringContainsString('push', $command); + $this->assertStringContainsString("--set-upstream 'origin' 'FRAMEWORK_6_1'", $command); + $this->assertStringContainsString('--follow-tags', $command); + $this->assertStringNotContainsString($token, $command); + $this->assertSame('/checkout', $directory); + $this->assertSame( + 'Authorization: Basic ' . base64_encode('x-access-token:' . $token), + $environment['HORDE_COMPONENTS_GITHUB_AUTHORIZATION'] + ); + return new SystemCallResult([], $exitCodes[$attempt++]); + }); + $git = (new Git(shell: $shell))->withGitHubAuthentication($authentication, $output); + + if (end($exitCodes) !== 0) { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Git remote operation failed'); + } + $git->push('/checkout', 'origin', 'FRAMEWORK_6_1', false, true); + } + + public function testPretendPushRunsNothing(): void + { + $authentication = $this->createMock(AuthenticationFactory::class); + $authentication->expects($this->never())->method('withEnvironmentPatFallback'); + $shell = $this->createMock(Shell::class); + $shell->method('isPretend')->willReturn(true); + $shell->expects($this->never())->method('execWithEnvironment'); + // In pretend mode remote detection is skipped and execNetwork prints + // the command via exec() without running it. + $shell->expects($this->once())->method('exec') + ->with($this->stringContains('push'), '/checkout') + ->willReturn(new SystemCallResult([], 0)); + $git = (new Git(shell: $shell)) + ->withGitHubAuthentication($authentication, $this->createStub(Output::class)); + + $git->push('/checkout', 'origin', 'FRAMEWORK_6_1', false, true); + } + + public function testCleanReleaseRunsFetchResetAndClean(): void + { + $shell = $this->createMock(Shell::class); + $shell->method('isPretend')->willReturn(false); + $commands = []; + $shell->expects($this->exactly(3))->method('exec') + ->willReturnCallback(function (string $command, ?string $directory) use (&$commands) { + $commands[] = $command; + $this->assertSame('/checkout', $directory); + return new SystemCallResult([], 0); + }); + $git = new Git(shell: $shell); + + $git->cleanRelease('/checkout', 'FRAMEWORK_6_1'); + + // fetch, reset --hard origin/, clean -fdx — in that order. + $this->assertCount(3, $commands); + $this->assertStringContainsString("fetch 'origin'", $commands[0]); + $this->assertStringContainsString("reset --hard 'origin/FRAMEWORK_6_1'", $commands[1]); + $this->assertStringContainsString('clean -fdx', $commands[2]); + } + + public function testCleanReleasePretendRunsNothing(): void + { + $realShell = new Shell(pretend: true); + $git = new Git(shell: $realShell); + + // No exception and no mutation: the pretend Shell prints instead of + // executing, so this is a pure smoke check that the path is wired. + $git->cleanRelease('/nonexistent-checkout', 'FRAMEWORK_6_1'); + $this->assertTrue($realShell->isPretend()); + } + public function testCloneUsesTransientConfigWithoutChangingStoredRemote(): void { $directory = sys_get_temp_dir() . '/components-git-auth-' . bin2hex(random_bytes(6));