Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 87 additions & 25 deletions src/Helper/Git.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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/<branch>
* - 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()) {
Expand Down Expand Up @@ -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)
);
}

Expand Down
12 changes: 11 additions & 1 deletion src/Module/Release.php
Original file line number Diff line number Diff line change
Expand Up @@ -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/<current-branch> && git clean -fdx". DESTRUCTIVE: permanently '
. 'removes all untracked and ignored files (vendor/, build output, '
. 'local configs). Only prints in --pretend mode.',
]
)];
}

Expand Down Expand Up @@ -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' => ''];
}

/**
Expand Down
24 changes: 24 additions & 0 deletions src/Release/HordeRelease.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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/<current branch> 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.
Expand Down
9 changes: 6 additions & 3 deletions src/Runner/Release.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -123,7 +125,8 @@ public function run(): void
$githubReleaseCreator,
$this->qcTasks,
$shell,
$this->branchRoles
$this->branchRoles,
$pretend
);

$release->run($this->component, $this->options);
Expand Down
27 changes: 27 additions & 0 deletions test/Unit/Release/HordeReleaseBranchGateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
92 changes: 92 additions & 0 deletions test/unit/Helper/GitAuthenticationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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/<branch>, 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));
Expand Down
Loading