354 lines
19 KiB
PHP
354 lines
19 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\Async\Processes;
|
|
use JumPHP\Ide\Scripts\Castor;
|
|
use JumPHP\Ide\Scripts\ScriptCommands;
|
|
use JumPHP\Ide\Scripts\ScriptShell;
|
|
use JumPHP\Ide\Scripts\ScriptStore;
|
|
use JumPHP\Ide\Scripts\ScriptTrust;
|
|
use JumPHP\Ide\Scripts\TaskDetector;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/** The Scripts window: runners' tasks found, variables quoted, the trust rule, scripts.json, real runs of make and castor. */
|
|
final class ScriptsTest extends TestCase
|
|
{
|
|
private string $dir;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->dir = sys_get_temp_dir() . '/jumphp-scripts-' . bin2hex(random_bytes(4));
|
|
mkdir($this->dir . '/project', 0777, true);
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
exec('rm -rf ' . escapeshellarg($this->dir));
|
|
}
|
|
|
|
private function write(string $path, string $content): void
|
|
{
|
|
@mkdir(dirname("$this->dir/project/$path"), 0777, true);
|
|
file_put_contents("$this->dir/project/$path", $content);
|
|
}
|
|
|
|
public function testMakefileTargetsAndTheirHelpAreFound(): void
|
|
{
|
|
$tasks = TaskDetector::makefile(<<<'MK'
|
|
.PHONY: build test
|
|
PHP := php
|
|
A = b:c
|
|
## Builds everything
|
|
build: deps
|
|
$(PHP) build.php
|
|
test: ## Runs the tests
|
|
phpunit
|
|
lint fix: ## Two at once
|
|
%.o: %.c
|
|
ifeq ($(A),x:y)
|
|
endif
|
|
define TEMPLATE
|
|
inside: nothing
|
|
endef
|
|
$(OUT): x
|
|
deploy:: ## Double colon
|
|
MK);
|
|
self::assertSame(['build', 'test', 'lint', 'fix', 'deploy'], array_column($tasks, 'name'));
|
|
self::assertSame(['Builds everything', 'Runs the tests', 'Two at once', 'Two at once', 'Double colon'], array_column($tasks, 'help'));
|
|
}
|
|
|
|
public function testCastorTasksAreReadFromTheFileWithoutRunningIt(): void
|
|
{
|
|
$tasks = TaskDetector::castorStatic([<<<'PHP'
|
|
<?php
|
|
use Castor\Attribute\AsTask;
|
|
use function Castor\run;
|
|
|
|
#[AsTask(description: 'Says hello')]
|
|
function helloWorld(): void { run('echo hi'); }
|
|
|
|
#[AsTask('db-reset', 'db', 'Resets the database', aliases: ['reset'])]
|
|
function anything(): void {}
|
|
|
|
function notATask(): void {}
|
|
|
|
#[\Castor\Attribute\AsTask(namespace: '')]
|
|
function cache_clear(): void {}
|
|
PHP, <<<'PHP'
|
|
<?php
|
|
namespace Qa\CodingStandards;
|
|
|
|
use Castor\Attribute as Castor;
|
|
|
|
#[Castor\AsTask(description: 'PHP CS')]
|
|
function phpCs(): void {}
|
|
PHP, '<?php this is not php {']);
|
|
self::assertSame(['cache-clear', 'db:db-reset', 'hello-world', 'qa:coding-standards:php-cs'], array_column($tasks, 'name'));
|
|
$byName = array_column($tasks, null, 'name');
|
|
self::assertSame('Says hello', $byName['hello-world']['help']);
|
|
self::assertSame(['reset'], $byName['db:db-reset']['aliases']);
|
|
self::assertSame('PHP CS', $byName['qa:coding-standards:php-cs']['help']);
|
|
}
|
|
|
|
public function testCastorListJsonLeavesOutCastorsOwnCommands(): void
|
|
{
|
|
$json = "warning before\n" . json_encode(['commands' => [
|
|
['name' => 'help', 'description' => 'Display help'], ['name' => 'list'], ['name' => 'castor:repack'],
|
|
['name' => 'hello', 'description' => 'Says hello', 'aliases' => ['hi']], ['name' => 'secret', 'hidden' => true],
|
|
]]);
|
|
self::assertSame([['name' => 'hello', 'help' => 'Says hello', 'aliases' => ['hi']]], TaskDetector::castorJson($json));
|
|
self::assertNull(TaskDetector::castorJson('Fatal error'));
|
|
}
|
|
|
|
public function testComposerAndPackageScriptsAndOtherRunners(): void
|
|
{
|
|
$this->write('composer.json', json_encode(['scripts' => ['test' => 'phpunit', 'cs' => ['php-cs-fixer fix', 'phpstan'], 'post-install-cmd' => 'echo done'],
|
|
'scripts-descriptions' => ['test' => 'Runs PHPUnit']]));
|
|
$this->write('package.json', json_encode(['scripts' => ['dev' => 'vite', 'build' => 'vite build']]));
|
|
$this->write('pnpm-lock.yaml', '');
|
|
$this->write('justfile', "# Serves the site\nserve port='8000':\n php -S localhost:{{port}}\n\n_hidden:\n true\n[private]\nsecret:\n true\nset shell := [\"bash\", \"-c\"]\n");
|
|
$this->write('Taskfile.yml', "version: '3'\ntasks:\n build:\n desc: Builds it\n cmds: [make]\n inner:\n internal: true\n");
|
|
$groups = TaskDetector::detect("$this->dir/project", fn (string $p) => $p === 'composer');
|
|
$by = array_column($groups, null, 'id');
|
|
self::assertSame(['composer', 'npm', 'just', 'task'], array_column($groups, 'id'));
|
|
self::assertSame(['test', 'cs', 'post-install-cmd'], array_column($by['composer']['tasks'], 'name'));
|
|
self::assertSame('Runs PHPUnit', $by['composer']['tasks'][0]['help']);
|
|
self::assertSame('php-cs-fixer fix && phpstan', $by['composer']['tasks'][1]['help']);
|
|
self::assertSame('composer run-script test', $by['composer']['tasks'][0]['command']);
|
|
self::assertSame('composer:test', $by['composer']['tasks'][0]['ref']);
|
|
self::assertSame('pnpm', $by['npm']['label']);
|
|
// pnpm is not installed here: in Docker, through corepack
|
|
self::assertStringContainsString('node:22-alpine corepack pnpm run dev', $by['npm']['tasks'][0]['command']);
|
|
self::assertSame([['name' => 'serve', 'help' => 'Serves the site']], array_map(fn ($t) => ['name' => $t['name'], 'help' => $t['help']], $by['just']['tasks']));
|
|
self::assertSame(['build'], array_column($by['task']['tasks'], 'name'));
|
|
self::assertSame('Builds it', $by['task']['tasks'][0]['help']);
|
|
}
|
|
|
|
public function testVariablesAreQuotedForWhereTheyStand(): void
|
|
{
|
|
self::assertSame('cat "${JUMPHP_FILE}"', ScriptShell::expand('cat ${file}'));
|
|
self::assertSame('echo "in ${JUMPHP_DIR} now"', ScriptShell::expand('echo "in ${dir} now"'));
|
|
self::assertSame("echo 'line '\"\${JUMPHP_LINE}\"' of'", ScriptShell::expand("echo 'line \${line} of'"));
|
|
self::assertSame('echo ${HOME} \${file}', ScriptShell::expand('echo ${HOME} \${file}'));
|
|
self::assertSame('git commit -m "${JUMPHP_INPUT_1}"', ScriptShell::expand('git commit -m "${input:Message}"', ['Message']));
|
|
self::assertSame(['Message', 'Branch'], ScriptShell::inputs('${input:Message} ${input:Branch} ${input:Message}'));
|
|
self::assertSame("'a b'", ScriptShell::quote('a b'));
|
|
self::assertSame("'it'\\''s'", ScriptShell::quote("it's"));
|
|
}
|
|
|
|
public function testAValueIsNeverRunAsCode(): void
|
|
{
|
|
$root = "$this->dir/project";
|
|
$body = "printf '%s|' \${selection} \"\${selection}\" '\${selection}' \${input:Name}\nprintf '%s' \"\${relativeFile}:\${line}\"";
|
|
$evil = "\$(touch $this->dir/pwned) \"; touch $this->dir/pwned2; '";
|
|
$env = ScriptShell::environment($body, $root, ['file' => 'src/a b.php', 'line' => 7, 'selection' => $evil], ['Name' => '`id`']);
|
|
file_put_contents("$this->dir/run.sh", ScriptShell::file('t', $body, $root, $env, ['MY_VAR' => 'x y']));
|
|
$out = shell_exec('sh ' . escapeshellarg("$this->dir/run.sh"));
|
|
self::assertSame("$evil|$evil|$evil|`id`|src/a b.php:7", $out);
|
|
self::assertFileDoesNotExist("$this->dir/pwned");
|
|
self::assertFileDoesNotExist("$this->dir/pwned2");
|
|
}
|
|
|
|
public function testMissingValuesAreSaid(): void
|
|
{
|
|
try {
|
|
ScriptShell::environment('cat ${file}', '/p', [], []);
|
|
self::fail('no file');
|
|
} catch (\InvalidArgumentException $e) {
|
|
self::assertStringContainsString('${file}', $e->getMessage());
|
|
}
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
ScriptShell::environment('echo ${input:Who}', '/p', [], []);
|
|
}
|
|
|
|
public function testPathsAreThoseOfTheContainerInDocker(): void
|
|
{
|
|
$env = ScriptShell::environment('echo ${file} ${dir} ${project}', '/home/me/site', ['file' => 'src/Kernel.php'], [], '/app');
|
|
self::assertSame(['JUMPHP_FILE' => '/app/src/Kernel.php', 'JUMPHP_DIR' => '/app/src', 'JUMPHP_PROJECT' => '/app'], $env);
|
|
}
|
|
|
|
public function testScriptsAreSavedSharedOrLocal(): void
|
|
{
|
|
$root = "$this->dir/project";
|
|
$store = new ScriptStore($root);
|
|
$a = $store->save(['name' => 'Build assets', 'command' => "npm run build\r\necho ok", 'icon' => '🚀', 'runIn' => 'terminal', 'env' => ['NODE_ENV' => 'production', 'bad name' => 'x'],
|
|
'events' => ['save' => '*.scss', 'before' => ['pong:run', '']]]);
|
|
$b = $store->save(['name' => 'Build assets', 'command' => 'make', 'local' => true, 'runIn' => 'nowhere']);
|
|
self::assertSame('build-assets', $a['id']);
|
|
self::assertSame('build-assets-2', $b['id']);
|
|
self::assertSame('run', $b['runIn']);
|
|
$shared = json_decode((string)file_get_contents("$root/.jumphp/scripts.json"), true);
|
|
self::assertSame(1, $shared['version']);
|
|
self::assertSame("npm run build\necho ok", $shared['scripts'][0]['command']);
|
|
self::assertSame(['NODE_ENV' => 'production'], $shared['scripts'][0]['env']);
|
|
self::assertSame(['pong:run'], $shared['scripts'][0]['events']['before']);
|
|
self::assertFileExists("$root/.jumphp/scripts.local.json");
|
|
self::assertStringContainsString('/scripts.local.json', (string)file_get_contents("$root/.jumphp/.gitignore"));
|
|
// made local: it leaves the shared file
|
|
$store->save(['local' => true] + $a);
|
|
self::assertSame([], json_decode((string)file_get_contents("$root/.jumphp/scripts.json"), true)['scripts']);
|
|
self::assertSame([true, true], array_column($store->all()['scripts'], 'local'));
|
|
$store->bind('make:build', ['pin' => true, 'key' => 'Ctrl+Alt+B']);
|
|
self::assertTrue($store->all()['bindings']['make:build']['pin']);
|
|
self::assertTrue($store->hasEvents());
|
|
$store->remove('build-assets');
|
|
$store->remove('build-assets-2');
|
|
$store->bind('make:build', []);
|
|
self::assertFileDoesNotExist("$root/.jumphp/scripts.local.json");
|
|
self::assertFalse($store->hasEvents());
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
$store->save(['name' => 'x', 'cwd' => '../outside']);
|
|
}
|
|
|
|
public function testGlobsOfTheSaveEvent(): void
|
|
{
|
|
self::assertTrue(ScriptStore::globMatches('*.scss', 'assets/css/app.scss'));
|
|
self::assertTrue(ScriptStore::globMatches('src/**/*.php', 'src/A/B/C.php'));
|
|
self::assertTrue(ScriptStore::globMatches('src/**/*.php', 'src/C.php'));
|
|
self::assertFalse(ScriptStore::globMatches('src/*.php', 'src/A/C.php'));
|
|
self::assertTrue(ScriptStore::globMatches('*.js, *.ts', 'ui/x.ts'));
|
|
self::assertFalse(ScriptStore::globMatches('', 'x.php'));
|
|
}
|
|
|
|
public function testAClonedProjectsScriptsDoNotRunByThemselvesUntilItIsTrusted(): void
|
|
{
|
|
$root = "$this->dir/project";
|
|
$this->write('.jumphp/scripts.json', json_encode(['scripts' => [['id' => 'evil', 'name' => 'Evil', 'command' => 'touch ' . $this->dir . '/ran', 'events' => ['open' => true]]]]));
|
|
$trust = new ScriptTrust("$this->dir/home/trusted.json");
|
|
self::assertFalse($trust->isTrusted($root));
|
|
self::assertTrue($trust->allows($root, null), 'a click always runs');
|
|
self::assertFalse($trust->allows($root, 'open'));
|
|
$handlers = $this->handlers($trust);
|
|
$list = $this->settle($handlers['scripts.list']([]));
|
|
self::assertTrue($list['needsTrust']);
|
|
self::assertFalse($list['trusted']);
|
|
try {
|
|
$handlers['scripts.prepare'](['ref' => 'script:evil', 'event' => 'open']);
|
|
self::fail('an untrusted project ran a script on open');
|
|
} catch (\RuntimeException $e) {
|
|
self::assertStringContainsString('not trusted', $e->getMessage());
|
|
}
|
|
self::assertFileDoesNotExist("$this->dir/ran");
|
|
$this->settle($handlers['scripts.trust'](['on' => true]));
|
|
self::assertTrue($trust->allows($root, 'open'));
|
|
self::assertFalse((new ScriptTrust("$this->dir/home/trusted.json"))->allows("$this->dir/other", 'save'), 'per project folder');
|
|
$prepared = $this->settle($handlers['scripts.prepare'](['ref' => 'script:evil', 'event' => 'open']));
|
|
self::assertFileExists("$root/.jumphp/run/script-evil.sh");
|
|
self::assertStringContainsString('/run/', (string)file_get_contents("$root/.jumphp/.gitignore"));
|
|
self::assertSame('Evil', $prepared['label']);
|
|
}
|
|
|
|
public function testATinyMakefileRunsInTheBackground(): void
|
|
{
|
|
if (trim((string)shell_exec('command -v make')) === '') {
|
|
self::markTestSkipped('make is not installed here');
|
|
}
|
|
$this->write('Makefile', "hello: ## Says hello\n\t@echo \"hello from make in $\$(basename $\$PWD)\"\n");
|
|
$handlers = $this->handlers(new ScriptTrust("$this->dir/home/trusted.json"));
|
|
$list = $this->settle($handlers['scripts.list']([]));
|
|
self::assertSame('make hello', $list['groups'][0]['tasks'][0]['command']);
|
|
$r = $this->settle($handlers['scripts.background'](['ref' => 'make:hello']));
|
|
self::assertSame(0, $r['code'], $r['output']);
|
|
self::assertSame('hello from make in project', $r['output']);
|
|
}
|
|
|
|
public function testAHomeMadeScriptRunsWithItsVariablesAndFolder(): void
|
|
{
|
|
$this->write('sub/x.txt', 'x');
|
|
(new ScriptStore("$this->dir/project"))->save(['name' => 'Where', 'cwd' => 'sub', 'env' => ['GREETING' => 'hi there'],
|
|
'command' => 'echo "$GREETING $(basename "$PWD") ${fileName}:${line} ${input:Who}"']);
|
|
$handlers = $this->handlers(new ScriptTrust("$this->dir/home/trusted.json"));
|
|
$r = $this->settle($handlers['scripts.background'](['ref' => 'script:where', 'context' => ['file' => 'sub/x.txt', 'line' => 3], 'inputs' => ['Who' => "O'Brien"]]));
|
|
self::assertSame("hi there sub x.txt:3 O'Brien", $r['output']);
|
|
}
|
|
|
|
public function testACastorTaskIsWrittenIntoCastorPhp(): void
|
|
{
|
|
$made = Castor::addTask(null, 'db:reset-all', 'Resets the database', "run('bin/console doctrine:database:drop --force');");
|
|
self::assertStringContainsString("use Castor\\Attribute\\AsTask;", $made);
|
|
self::assertStringContainsString("use function Castor\\run;", $made);
|
|
self::assertStringContainsString("#[AsTask(namespace: 'db', description: 'Resets the database')]\nfunction resetAll(): void\n{\n run('bin/console", $made);
|
|
self::assertSame(['db:reset-all'], array_column(TaskDetector::castorStatic([$made]), 'name'));
|
|
// an existing file in a PHP namespace, with grouped use lines
|
|
$existing = "<?php\n\nnamespace app;\n\nuse Castor\\Attribute\\{AsTask, AsOption};\n\n#[AsTask]\nfunction build(): void {}\n";
|
|
$more = Castor::addTask($existing, 'hello', '', '');
|
|
self::assertSame(1, substr_count($more, 'AsTask;') + substr_count($more, 'AsTask,'));
|
|
self::assertStringContainsString('use function Castor\\run;', $more);
|
|
self::assertSame(['app:build', 'hello'], array_column(TaskDetector::castorStatic([$more]), 'name'));
|
|
self::assertNotFalse(@token_get_all($more));
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
Castor::addTask($more, 'hello', '', '');
|
|
}
|
|
|
|
public function testTheCastorReleaseIsCheckedBeforeItIsInstalled(): void
|
|
{
|
|
self::assertSame('castor.linux-amd64', Castor::asset('Linux', 'x86_64'));
|
|
self::assertSame('castor.darwin-arm64', Castor::asset('Darwin', 'arm64'));
|
|
self::assertSame('castor.windows-amd64.exe', Castor::asset('Windows', 'AMD64'));
|
|
self::assertNull(Castor::asset('Linux', 'riscv64'));
|
|
file_put_contents("$this->dir/castor.linux-amd64", 'binary');
|
|
$sums = hash('sha256', 'binary') . " castor.linux-amd64\n" . str_repeat('a', 64) . " castor.darwin-arm64\n";
|
|
self::assertSame(hash('sha256', 'binary'), Castor::checksum($sums, 'castor.linux-amd64'));
|
|
Castor::verifyAndInstall("$this->dir/castor.linux-amd64", $sums, 'castor.linux-amd64', "$this->dir/home/.jumphp/bin/castor");
|
|
self::assertFileExists("$this->dir/home/.jumphp/bin/castor");
|
|
self::assertTrue(is_executable("$this->dir/home/.jumphp/bin/castor"));
|
|
file_put_contents("$this->dir/tampered", 'other');
|
|
try {
|
|
Castor::verifyAndInstall("$this->dir/tampered", str_replace('castor.linux-amd64', 'tampered', $sums), 'tampered', "$this->dir/home/x");
|
|
self::fail('a tampered download was installed');
|
|
} catch (\RuntimeException) {
|
|
self::assertFileDoesNotExist("$this->dir/home/x");
|
|
self::assertFileDoesNotExist("$this->dir/tampered");
|
|
}
|
|
}
|
|
|
|
/** castor itself, when its phar can be fetched (php of this image runs it): its list, then a task run */
|
|
public function testARealCastorListsAndRunsATask(): void
|
|
{
|
|
$phar = sys_get_temp_dir() . '/jumphp-castor-test.phar';
|
|
if (!is_file($phar) || filesize($phar) < 100000) {
|
|
$data = @file_get_contents('https://github.com/jolicode/castor/releases/latest/download/castor.linux-amd64.phar', false,
|
|
stream_context_create(['http' => ['timeout' => 20, 'user_agent' => 'JumPHP-IDE']]));
|
|
if (!is_string($data) || strlen($data) < 100000) {
|
|
self::markTestSkipped('the castor phar could not be fetched');
|
|
}
|
|
file_put_contents($phar, $data);
|
|
}
|
|
$this->write('castor.php', Castor::addTask(null, 'greet', 'Greets', "io()->writeln('hello from castor');"));
|
|
copy($phar, "$this->dir/project/castor.phar");
|
|
$trust = new ScriptTrust("$this->dir/home/trusted.json");
|
|
$trust->trust("$this->dir/project");
|
|
$handlers = $this->handlers($trust);
|
|
$list = $this->settle($handlers['scripts.list'](['refresh' => true]));
|
|
$castor = array_column($list['groups'], null, 'id')['castor'] ?? null;
|
|
self::assertNotNull($castor);
|
|
if (!($castor['listed'] ?? false)) {
|
|
self::markTestSkipped('castor list did not answer here: ' . $list['castor']['error']);
|
|
}
|
|
self::assertSame(['greet'], array_column($castor['tasks'], 'name'));
|
|
self::assertSame('Greets', $castor['tasks'][0]['help']);
|
|
$r = $this->settle($handlers['scripts.background'](['ref' => 'castor:greet']));
|
|
self::assertSame(0, $r['code'], $r['output']);
|
|
self::assertStringContainsString('hello from castor', $r['output']);
|
|
}
|
|
|
|
/** @return array<string, callable> */
|
|
private function handlers(ScriptTrust $trust): array
|
|
{
|
|
$handlers = [];
|
|
$this->processes = new Processes();
|
|
ScriptCommands::register(function (string $name, callable $h) use (&$handlers): void {
|
|
$handlers[$name] = $h;
|
|
}, $this->processes, "$this->dir/project", fn () => false, $trust, "$this->dir/home");
|
|
return $handlers;
|
|
}
|
|
|
|
private Processes $processes;
|
|
|
|
private function settle(mixed $value): mixed
|
|
{
|
|
return $value instanceof Deferred ? $this->processes->wait($value, 120) : $value;
|
|
}
|
|
}
|