rob-revisited/ide/tests/VcsTest.php

351 lines
19 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Async\Processes;
use JumPHP\Ide\Git\Git;
use JumPHP\Ide\Svn\Svn;
use JumPHP\Ide\Vcs\Choice;
use JumPHP\Ide\Vcs\RepoHosts;
use JumPHP\Ide\Vcs\SourceControl;
use JumPHP\Ide\Vcs\VcsCommands;
use PHPUnit\Framework\TestCase;
/** Which version control a project uses, where its repository lives, and the "Source control" step of a New Project. */
final class VcsTest extends TestCase
{
private string $dir;
private Processes $processes;
private Git $git;
private Svn $svn;
/** @var array<string, callable> */
private array $commands = [];
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/jumphp-ide-vcs-' . bin2hex(random_bytes(4));
mkdir($this->dir);
$this->processes = new Processes();
$this->git = new Git($this->processes, $this->dir);
$this->git->setFallbackAuthor(['name' => 'Agent', 'email' => 'agent@localhost']);
$this->svn = new Svn($this->processes, $this->dir);
VcsCommands::register(function (string $name, callable $handler): void {
$this->commands[$name] = $handler;
}, $this->git, $this->svn, $this->dir);
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->dir));
}
// hosts -------------------------------------------------------------------------------------------------
public function testTheHostOfAnUrlIsRecognised(): void
{
self::assertSame('github', RepoHosts::detect('https://github.com/ada/game.git'));
self::assertSame('github', RepoHosts::detect('[email protected]:ada/game.git'));
self::assertSame('forgejo', RepoHosts::detect('https://git.jumphp.net/ada/game.git'));
self::assertSame('gitlab', RepoHosts::detect('https://gitlab.com/ada/game.git'));
self::assertSame('gitlab', RepoHosts::detect('ssh://[email protected]/ada/game.git'));
self::assertSame('bitbucket', RepoHosts::detect('https://bitbucket.org/ada/game.git'));
self::assertSame('url', RepoHosts::detect('https://code.example.org/ada/game.git'));
self::assertSame('code.example.org', RepoHosts::hostOf('ssh://[email protected]:2222/ada/game.git'));
}
public function testTheUrlOfAHostIsBuiltFromTheOwnerAndTheName(): void
{
self::assertSame('https://github.com/ada/game.git', RepoHosts::remoteUrl('github', 'ada', 'game'));
self::assertSame('https://git.jumphp.net/ada/game.git', RepoHosts::remoteUrl('forgejo', 'ada', 'game.git'));
self::assertSame('https://git.example.org/team/sub/game.git', RepoHosts::remoteUrl('gitlab', 'team/sub', 'game', 'https://git.example.org'));
self::assertSame('https://gitlab.com/ada/game.git', RepoHosts::remoteUrl('gitlab', 'ada', 'game'));
$this->expectException(\InvalidArgumentException::class);
RepoHosts::remoteUrl('github', 'ada; rm', 'game');
}
/** @dataProvider badUrls */
public function testAnUrlThatCouldBeAnOptionOrHoldASecretIsRefused(string $url): void
{
$this->expectException(\InvalidArgumentException::class);
RepoHosts::checkUrl($url);
}
/** @return iterable<string, array{string}> */
public static function badUrls(): iterable
{
yield 'option' => ['--upload-pack=touch /tmp/x'];
yield 'dash' => ['-oProxyCommand=x'];
yield 'space' => ['https://a.b/c d.git'];
yield 'newline' => ["https://a.b/c.git\nx"];
yield 'password' => ['https://ada:[email protected]/ada/game.git'];
yield 'nothing' => [''];
yield 'not a repository' => ['hello'];
yield 'the framework' => ['https://git.jumphp.net/jumphp/jumPhp.git'];
yield 'the framework over ssh' => ['[email protected]:jumphp/jumPhp.git'];
}
public function testTheUrlsOfGitAndSubversionAreAccepted(): void
{
foreach (['https://github.com/a/b.git', '[email protected]:a/b.git', 'ssh://git@h:22/a/b.git', 'git://h/a/b.git', 'file:///srv/x.git', '/srv/x.git', 'https://[email protected]/a/b.git'] as $url) {
self::assertSame($url, RepoHosts::checkUrl($url));
}
self::assertSame('svn://h/repo/trunk', RepoHosts::checkUrl('svn://h/repo/trunk', 'svn'));
$this->expectException(\InvalidArgumentException::class);
RepoHosts::checkUrl('[email protected]:a/b.git', 'svn');
}
public function testEachHostGetsItsOwnCreationRequest(): void
{
$github = RepoHosts::createRequest(['id' => 'github'], 'game', 'A game', true, 'tok');
self::assertSame('https://api.github.com/user/repos', $github['url']);
self::assertSame('Bearer tok', $github['headers']['Authorization']);
self::assertTrue($github['body']['private']);
$forge = RepoHosts::createRequest(['id' => 'forgejo'], 'game', '', true, 'tok');
self::assertSame('https://git.jumphp.net/api/v1/user/repos', $forge['url']);
self::assertSame('token tok', $forge['headers']['Authorization']);
self::assertTrue($forge['body']['private']);
self::assertSame('main', $forge['body']['default_branch']);
$gitlab = RepoHosts::createRequest(['id' => 'gitlab', 'host' => 'git.example.org'], 'game', '', true, 'tok');
self::assertSame('https://git.example.org/api/v4/projects', $gitlab['url']);
self::assertSame('tok', $gitlab['headers']['PRIVATE-TOKEN']);
self::assertArrayNotHasKey('Authorization', $gitlab['headers']);
self::assertSame('private', $gitlab['body']['visibility']);
self::assertSame('public', RepoHosts::createRequest(['id' => 'gitlab'], 'g', '', false, 't')['body']['visibility']);
self::assertSame('https://gitlab.com/api/v4/projects', RepoHosts::createRequest(['id' => 'gitlab'], 'g', '', true, 't')['url']);
$this->expectException(\InvalidArgumentException::class);
RepoHosts::createRequest(['id' => 'bitbucket'], 'game', '', true, 'tok');
}
public function testWhatAHostAnswersIsTold(): void
{
self::assertSame(['state' => 'created', 'cloneUrl' => 'https://gitlab.com/a/b.git', 'webUrl' => 'https://gitlab.com/a/b'],
RepoHosts::readCreated('gitlab', 201, ['http_url_to_repo' => 'https://gitlab.com/a/b.git', 'web_url' => 'https://gitlab.com/a/b']));
self::assertSame('created', RepoHosts::readCreated('github', 201, ['clone_url' => 'https://github.com/a/b.git', 'html_url' => 'x'])['state']);
self::assertSame('taken', RepoHosts::readCreated('gitlab', 400, ['message' => ['name' => ['has already been taken']]])['state'], 'GitLab says 400 for a taken name');
self::assertSame('taken', RepoHosts::readCreated('github', 422, ['message' => 'Repository creation failed.'])['state']);
self::assertSame('taken', RepoHosts::readCreated('forgejo', 409, ['message' => 'exists'])['state']);
self::assertSame('token', RepoHosts::readCreated('github', 401, [])['state']);
self::assertSame('error', RepoHosts::readCreated('gitlab', 400, ['message' => 'bad'])['state']);
}
// the step of a New Project ----------------------------------------------------------------------------
public function testTheDefaultStepIsALocalPrivateGitRepository(): void
{
$plan = SourceControl::normalize(null);
self::assertSame('git', $plan['mode']);
self::assertTrue($plan['private']);
self::assertSame([], SourceControl::commands($plan));
self::assertTrue(SourceControl::keepsGit($plan));
self::assertNull(SourceControl::tokenHost($plan));
}
public function testNoVersionControlKeepsNoGit(): void
{
$plan = SourceControl::normalize(['mode' => 'none']);
self::assertFalse(SourceControl::keepsGit($plan));
self::assertSame([], SourceControl::commands($plan));
}
public function testTheRepositoryIsCreatedOnTheChosenHostAndPushed(): void
{
foreach (['forgejo' => 'git.jumphp.net', 'github' => 'github.com'] as $host => $name) {
$plan = SourceControl::normalize(['mode' => 'remote', 'host' => $host]);
self::assertSame($name, SourceControl::tokenHost($plan), $host);
self::assertTrue($plan['private'], "$host: private by default");
self::assertSame([['git', 'remote', 'add', 'origin', "https://$name/ada/game.git"], ['git', 'push', '-u', 'origin', 'HEAD']],
SourceControl::commands($plan, "https://$name/ada/game.git"));
}
$gitlab = SourceControl::normalize(['mode' => 'remote', 'host' => 'gitlab', 'gitlabHost' => 'https://git.example.org/', 'private' => true]);
self::assertSame('git.example.org', $gitlab['hostName']);
self::assertSame('git.example.org', SourceControl::tokenHost($gitlab));
self::assertSame('gitlab.com', SourceControl::normalize(['mode' => 'remote', 'host' => 'gitlab'])['hostName']);
self::assertSame([], SourceControl::commands($gitlab), 'nothing to run before the host answered');
self::assertFalse(SourceControl::normalize(['mode' => 'remote', 'host' => 'github', 'private' => false])['private']);
}
public function testAnExistingRemoteIsAddedAndNothingIsPushed(): void
{
$plan = SourceControl::normalize(['mode' => 'remote', 'host' => 'existing', 'url' => '[email protected]:ada/game.git']);
self::assertSame([['git', 'remote', 'add', 'origin', '[email protected]:ada/game.git']], SourceControl::commands($plan));
self::assertNull(SourceControl::tokenHost($plan));
}
public function testSubversionChecksTheRepositoryOutIntoTheProjectWithoutCommitting(): void
{
$plan = SourceControl::normalize(['mode' => 'svn', 'url' => 'https://svn.example.org/repo/trunk']);
self::assertFalse(SourceControl::keepsGit($plan));
self::assertSame([['svn', 'checkout', '--force', '--non-interactive', '--', 'https://svn.example.org/repo/trunk', '.']], SourceControl::commands($plan));
}
public function testABadStepIsRefusedBeforeAnythingIsMade(): void
{
foreach ([['mode' => 'cvs'], ['mode' => 'svn', 'url' => 'https://github.com/a/b.git ; x'], ['mode' => 'remote', 'host' => 'bitbucket'], ['mode' => 'remote', 'host' => 'existing', 'url' => '-x']] as $spec) {
try {
SourceControl::normalize($spec);
self::fail('accepted: ' . json_encode($spec));
} catch (\InvalidArgumentException) {
self::assertTrue(true);
}
}
}
// what the IDE uses -------------------------------------------------------------------------------------
public function testTheChoiceDecidesWhichVersionControlTheIdeUses(): void
{
self::assertSame('git', Choice::effective(null, true, true), 'automatic: Git first');
self::assertSame('svn', Choice::effective(null, false, true));
self::assertNull(Choice::effective(null, false, false));
self::assertNull(Choice::effective('none', true, true), 'detached: no integration');
self::assertSame('svn', Choice::effective('svn', true, true));
self::assertNull(Choice::effective('git', false, true), 'chosen but not there');
}
public function testTheChoiceIsKeptOutOfGit(): void
{
$this->wait($this->commands['vcs.init']([]));
Choice::write($this->dir, 'svn');
self::assertSame('svn', Choice::read($this->dir));
self::assertStringContainsString('/.jumphp/', (string)file_get_contents($this->dir . '/.git/info/exclude'));
Choice::write($this->dir, null);
self::assertNull(Choice::read($this->dir));
}
public function testGitIsInitialisedHereOnce(): void
{
self::assertSame(['kind' => 'git'], $this->wait($this->commands['vcs.init']([])));
self::assertTrue(is_dir($this->dir . '/.git'));
$this->expectException(\RuntimeException::class);
$this->commands['vcs.init']([]);
}
public function testDetachingStopsTheIntegrationAndKeepsTheHistory(): void
{
$this->wait($this->commands['vcs.init']([]));
file_put_contents($this->dir . '/a.txt', 'one');
$this->wait($this->git->commit('First', ['a.txt']));
mkdir($this->dir . '/.svn');
self::assertSame(['kind' => 'none', 'deleted' => []], $this->wait($this->commands['vcs.detach']([])));
self::assertTrue(is_dir($this->dir . '/.git'), '.git is still there');
self::assertTrue(is_dir($this->dir . '/.svn'), '.svn is still there');
self::assertSame('none', Choice::read($this->dir));
self::assertStringContainsString('First', $this->wait($this->git->run(['log', '--oneline'])), 'the history is intact');
$state = $this->wait($this->commands['vcs.state']([]));
self::assertNull($state['kind']);
self::assertTrue($state['hasGit']);
// and Git can be taken back
self::assertSame(['kind' => 'git'], $this->commands['vcs.use'](['kind' => 'git']));
self::assertSame('git', $this->wait($this->commands['vcs.state']([]))['kind']);
}
public function testDeletingTheRepositoryNeedsTheSecondConfirmation(): void
{
$this->wait($this->commands['vcs.init']([]));
foreach ([[], ['confirm' => 'yes'], ['confirm' => 'delete']] as $extra) {
try {
$this->commands['vcs.detach'](['delete' => true] + $extra);
self::fail('deleted without the word DELETE');
} catch (\RuntimeException) {
self::assertTrue(is_dir($this->dir . '/.git'));
}
}
// ticking "delete" without the word is not enough, the word without "delete" deletes nothing
$this->commands['vcs.detach'](['confirm' => 'DELETE']);
self::assertTrue(is_dir($this->dir . '/.git'));
mkdir($this->dir . '/.svn');
file_put_contents($this->dir . '/.svn/entries', '12');
file_put_contents($this->dir . '/keep.txt', 'mine');
$r = $this->commands['vcs.detach'](['delete' => true, 'confirm' => 'DELETE']);
self::assertEqualsCanonicalizing(['.git', '.svn'], $r['deleted']);
self::assertFalse(file_exists($this->dir . '/.git'));
self::assertFalse(file_exists($this->dir . '/.svn'));
self::assertSame('mine', file_get_contents($this->dir . '/keep.txt'), 'the project\'s files are never touched');
self::assertNull(Choice::read($this->dir), 'nothing is left to detach');
}
public function testADeletionStaysInTheProjectFolder(): void
{
$outside = $this->dir . '-outside';
mkdir($outside . '/.git', 0777, true);
$link = $this->dir . '/.git';
if (!@symlink($outside . '/.git', $link)) {
self::markTestSkipped('no symbolic links here');
}
$this->commands['vcs.detach'](['delete' => true, 'confirm' => 'DELETE']);
self::assertTrue(is_dir($outside . '/.git'), 'the target of a link is not followed');
exec('rm -rf ' . escapeshellarg($outside));
}
public function testUsingGitOrSubversionNeedsTheRepositoryToBeThere(): void
{
foreach (['git', 'svn'] as $kind) {
try {
$this->commands['vcs.use'](['kind' => $kind]);
self::fail("$kind accepted without a repository");
} catch (\RuntimeException) {
self::assertNull(Choice::read($this->dir));
}
}
mkdir($this->dir . '/.svn');
self::assertSame(['kind' => 'svn'], $this->commands['vcs.use'](['kind' => 'svn']));
self::assertSame('svn', $this->wait($this->commands['vcs.state']([]))['kind']);
}
// remotes -----------------------------------------------------------------------------------------------
public function testARemoteIsAddedChangedAndRemoved(): void
{
$this->wait($this->commands['vcs.init']([]));
$this->wait($this->commands['vcs.remoteSet'](['name' => 'origin', 'url' => 'https://github.com/ada/game.git']));
$state = $this->wait($this->commands['vcs.state']([]));
self::assertSame([['name' => 'origin', 'url' => 'https://github.com/ada/game.git', 'host' => 'github', 'hostName' => 'github.com']], $state['remotes']);
self::assertSame(['name' => 'origin', 'changed' => true], $this->wait($this->commands['vcs.remoteSet'](['name' => 'origin', 'url' => 'https://gitlab.com/ada/game.git'])));
self::assertSame('gitlab', $this->wait($this->commands['vcs.state']([]))['remotes'][0]['host']);
$this->wait($this->commands['vcs.remoteRemove'](['name' => 'origin']));
self::assertSame([], $this->wait($this->commands['vcs.state']([]))['remotes']);
}
public function testARemoteWithABadUrlOrNameIsRefused(): void
{
$this->wait($this->commands['vcs.init']([]));
foreach ([['origin', '--upload-pack=x'], ['origin', 'https://u:[email protected]/a/b.git'], ['-bad', 'https://github.com/a/b.git']] as [$name, $url]) {
try {
$this->wait($this->commands['vcs.remoteSet'](['name' => $name, 'url' => $url]));
self::fail("accepted $name $url");
} catch (\Throwable) {
self::assertSame([], $this->wait($this->commands['vcs.state']([]))['remotes']);
}
}
}
public function testTheConnectionToARepositoryIsTested(): void
{
$bare = $this->dir . '-bare.git';
exec('git init -q --bare -b main ' . escapeshellarg($bare));
$seed = $this->dir . '-seed';
exec('git init -q -b main ' . escapeshellarg($seed) . ' && cd ' . escapeshellarg($seed) . ' && git -c user.name=a -c user.email=a@b commit -q --allow-empty -m x && git push -q ' . escapeshellarg($bare) . ' main 2>&1');
$this->wait($this->commands['vcs.init']([]));
$ok = $this->wait($this->commands['vcs.testRemote'](['url' => 'file://' . $bare]));
self::assertTrue($ok['ok'], $ok['message']);
self::assertSame(['main'], $ok['branches']);
$missing = $this->wait($this->commands['vcs.testRemote'](['url' => 'file://' . $this->dir . '-nothing.git']));
self::assertFalse($missing['ok']);
self::assertNotSame('', $missing['message']);
$option = $this->wait($this->commands['vcs.testRemote'](['url' => '--upload-pack=touch ' . $this->dir . '/pwned']));
self::assertFalse($option['ok']);
self::assertFileDoesNotExist($this->dir . '/pwned');
$svn = $this->wait($this->commands['vcs.testRemote'](['url' => 'https://github.com/a/b.git', 'vcs' => 'svn']));
self::assertFalse($svn['ok'], 'a Git URL is not a Subversion one');
exec('rm -rf ' . escapeshellarg($bare) . ' ' . escapeshellarg($seed));
}
private function wait(mixed $value): mixed
{
return $value instanceof Deferred ? $this->processes->wait($value) : $value;
}
}