Compare commits

15 changed files with 281 additions and 49 deletions
+1 -1
View File
@@ -65,7 +65,7 @@ por el componente que pides; los metadatos del paquete no se instalan.
El instalador global arranca un proyecto desde cero y no necesita nada previo: El instalador global arranca un proyecto desde cero y no necesita nada previo:
#+BEGIN_SRC sh #+BEGIN_SRC sh
git clone git@git.kj2.me:kj/duckbrain-toolbox.git git clone https://git.kj2.me/kj/duckbrain-toolbox.git
ln -s "$PWD/duckbrain-toolbox/bin/duckbrain" ~/.local/bin/duckbrain ln -s "$PWD/duckbrain-toolbox/bin/duckbrain" ~/.local/bin/duckbrain
duckbrain install mi-proyecto # descarga el núcleo Duckbrain duckbrain install mi-proyecto # descarga el núcleo Duckbrain
+9 -4
View File
@@ -1,13 +1,15 @@
{ {
"name": "commands", "name": "commands",
"version": "0.2.1", "version": "0.2.4",
"description": "CLI y migraciones para Duckbrain", "description": "CLI y migraciones para Duckbrain",
"components": { "components": {
"cli": { "cli": {
"files": [ "files": [
"duckbrain", "duckbrain",
"src/Interfaces/CommandInterface.php" "src/Interfaces/CommandInterface.php"
] ],
"description": "CLI del proyecto (binario duckbrain)",
"core": "none"
}, },
"migration": { "migration": {
"files": [ "files": [
@@ -20,12 +22,15 @@
"core": { "core": {
"requires": ">=0.1", "requires": ">=0.1",
"tested": "0.1" "tested": "0.1"
} },
"description": "Migraciones de base de datos (mysql/pgsql/sqlite)"
}, },
"toolbox": { "toolbox": {
"files": [ "files": [
"src/Toolbox" "src/Toolbox"
] ],
"description": "Gestor de addons dentro del propio proyecto",
"core": "none"
} }
}, },
"default": [ "default": [
@@ -33,17 +33,19 @@ final class DoctorCommand extends Command
foreach ($lock->components() as $id => $entry) { foreach ($lock->components() as $id => $entry) {
[$package, $component] = array_pad(explode(':', $id, 2), 2, null); [$package, $component] = array_pad(explode(':', $id, 2), 2, null);
$requires = null; $requires = null;
$tested = null; $tested = null;
$independent = false;
if ($component !== null && $package !== null && $catalog->has($package)) { if ($component !== null && $package !== null && $catalog->has($package)) {
$manifest = $catalog->get($package); $manifest = $catalog->get($package);
if ($manifest->hasComponent($component)) { if ($manifest->hasComponent($component)) {
$requires = $manifest->coreRequirement($component); $requires = $manifest->coreRequirement($component);
$tested = $manifest->testedCore($component); $tested = $manifest->testedCore($component);
$independent = $manifest->coreIndependent($component);
} }
} }
$result = Compatibility::evaluateCore($coreVersion, $requires, $tested); $result = Compatibility::evaluateCore($coreVersion, $requires, $tested, $independent);
$rows[] = [ $rows[] = [
$id, $id,
@@ -12,6 +12,7 @@ final class Compatibility
public const UNTESTED = 'untested'; public const UNTESTED = 'untested';
public const INSUFFICIENT = 'insufficient'; public const INSUFFICIENT = 'insufficient';
public const UNKNOWN = 'unknown'; public const UNKNOWN = 'unknown';
public const INDEPENDENT = 'independent';
/** /**
* @return array{status:string, message:string} * @return array{status:string, message:string}
@@ -19,8 +20,13 @@ final class Compatibility
public static function evaluateCore( public static function evaluateCore(
?string $coreVersion, ?string $coreVersion,
?string $requires, ?string $requires,
?string $tested ?string $tested,
bool $independent = false
): array { ): array {
if ($independent) {
return ['status' => self::INDEPENDENT, 'message' => 'independiente del core'];
}
if ($coreVersion === null) { if ($coreVersion === null) {
return ['status' => self::UNKNOWN, 'message' => 'versión del core desconocida (sin tags)']; return ['status' => self::UNKNOWN, 'message' => 'versión del core desconocida (sin tags)'];
} }
@@ -68,10 +74,11 @@ final class Compatibility
public static function label(string $status): string public static function label(string $status): string
{ {
return match ($status) { return match ($status) {
self::OK => 'OK', self::OK => 'OK',
self::UNTESTED => 'NO PROBADO', self::UNTESTED => 'NO PROBADO',
self::INSUFFICIENT => 'INSUFICIENTE', self::INSUFFICIENT => 'INSUFICIENTE',
default => 'SIN DATOS', self::INDEPENDENT => 'INDEPENDIENTE',
default => 'SIN DATOS',
}; };
} }
} }
+42 -2
View File
@@ -18,6 +18,8 @@ final class Component
public readonly ?string $description = null, public readonly ?string $description = null,
public readonly ?array $destinations = null, public readonly ?array $destinations = null,
public readonly bool $override = false, public readonly bool $override = false,
public readonly bool $coreDeclared = false,
public readonly ?bool $coreIndependent = null,
) { ) {
} }
@@ -61,15 +63,53 @@ final class Component
$description = $data['description']; $description = $data['description'];
} }
$coreDeclared = array_key_exists('core', $data);
$coreIndependent = null;
$coreRequires = null;
$coreTested = null;
if ($coreDeclared) {
[$coreRequires, $coreTested, $coreIndependent] = self::parseCore($data['core'], "el componente '{$name}'");
}
return new self( return new self(
name: $name, name: $name,
files: array_values($data['files']), files: array_values($data['files']),
requires: $requires, requires: $requires,
coreRequires: $data['core']['requires'] ?? null, coreRequires: $coreRequires,
coreTested: $data['core']['tested'] ?? null, coreTested: $coreTested,
description: $description, description: $description,
destinations: $destinations, destinations: $destinations,
override: (bool) ($data['override'] ?? false), override: (bool) ($data['override'] ?? false),
coreDeclared: $coreDeclared,
coreIndependent: $coreIndependent,
); );
} }
/**
* Bloque `core`: objeto de rango ({requires?, tested?}) o la cadena
* "none" (independencia afirmativa, excluyente con el rango).
*
* @return array{0: ?string, 1: ?string, 2: ?bool}
*/
public static function parseCore(mixed $core, string $origin): array
{
if ($core === 'none') {
return [null, null, true];
}
if (!is_array($core)) {
throw new ToolboxException("{$origin} tiene un 'core' inválido");
}
$requires = $core['requires'] ?? null;
$tested = $core['tested'] ?? null;
foreach (['requires' => $requires, 'tested' => $tested] as $key => $value) {
if ($value !== null && !is_string($value)) {
throw new ToolboxException("{$origin} tiene un 'core.{$key}' inválido");
}
}
return [$requires, $tested, null];
}
} }
+3 -3
View File
@@ -8,18 +8,18 @@ namespace Toolbox;
*/ */
final class Config final class Config
{ {
public const VERSION = '0.2.1'; public const VERSION = '0.2.4';
public static function toolboxUrl(): string public static function toolboxUrl(): string
{ {
return self::env('DUCKBRAIN_TOOLBOX_URL') return self::env('DUCKBRAIN_TOOLBOX_URL')
?: 'git@git.kj2.me:kj/duckbrain-toolbox.git'; ?: 'https://git.kj2.me/kj/duckbrain-toolbox.git';
} }
public static function coreUrl(): string public static function coreUrl(): string
{ {
return self::env('DUCKBRAIN_CORE_URL') return self::env('DUCKBRAIN_CORE_URL')
?: 'git@git.kj2.me:kj/duckbrain.git'; ?: 'https://git.kj2.me/kj/duckbrain.git';
} }
/** /**
+3 -2
View File
@@ -111,10 +111,11 @@ final class Installer
$compat = Compatibility::evaluateCore( $compat = Compatibility::evaluateCore(
$this->coreVersion(), $this->coreVersion(),
$manifest->coreRequirement($componentName), $manifest->coreRequirement($componentName),
$manifest->testedCore($componentName) $manifest->testedCore($componentName),
$manifest->coreIndependent($componentName)
); );
if ($compat['status'] !== Compatibility::OK) { if (!in_array($compat['status'], [Compatibility::OK, Compatibility::INDEPENDENT], true)) {
$warnings[] = $id . ': ' . $compat['message']; $warnings[] = $id . ': ' . $compat['message'];
$assumeYes = (bool) ($options['yes'] ?? false); $assumeYes = (bool) ($options['yes'] ?? false);
if (!$assumeYes && !$this->console->confirm(" {$id}: {$compat['message']}. ¿Continuar?", false)) { if (!$assumeYes && !$this->console->confirm(" {$id}: {$compat['message']}. ¿Continuar?", false)) {
+32 -9
View File
@@ -18,6 +18,7 @@ final class Manifest
public readonly ?string $coreTested, public readonly ?string $coreTested,
public readonly ?string $php, public readonly ?string $php,
public readonly array $postInstall, public readonly array $postInstall,
public readonly ?bool $coreIndependent = null,
) { ) {
} }
@@ -83,16 +84,23 @@ final class Manifest
$postInstall[] = $command; $postInstall[] = $command;
} }
$coreRequires = $coreTested = null;
$coreIndependent = null;
if (array_key_exists('core', $data)) {
[$coreRequires, $coreTested, $coreIndependent] = Component::parseCore($data['core'], "el manifiesto '{$origin}'");
}
return new self( return new self(
name: $name, name: $name,
version: $version, version: $version,
description: is_string($data['description'] ?? null) ? $data['description'] : '', description: is_string($data['description'] ?? null) ? $data['description'] : '',
components: $components, components: $components,
default: $default, default: $default,
coreRequires: $data['core']['requires'] ?? null, coreRequires: $coreRequires,
coreTested: $data['core']['tested'] ?? null, coreTested: $coreTested,
php: is_string($data['php'] ?? null) ? $data['php'] : null, php: is_string($data['php'] ?? null) ? $data['php'] : null,
postInstall: $postInstall, postInstall: $postInstall,
coreIndependent: $coreIndependent,
); );
} }
@@ -140,22 +148,37 @@ final class Manifest
return $this->default; return $this->default;
} }
public function coreRequirement(?string $component = null): ?string /**
* Bloque de core efectivo: si el componente declara `core` (rango o
* "none") ese bloque gana por completo; si no, hereda el del paquete.
*
* @return array{requires: ?string, tested: ?string, independent: ?bool}
*/
private function coreBlock(?string $component): array
{ {
if ($component !== null) { if ($component !== null) {
return $this->component($component)->coreRequires ?? $this->coreRequires; $c = $this->component($component);
if ($c->coreDeclared) {
return ['requires' => $c->coreRequires, 'tested' => $c->coreTested, 'independent' => $c->coreIndependent];
}
} }
return $this->coreRequires; return ['requires' => $this->coreRequires, 'tested' => $this->coreTested, 'independent' => $this->coreIndependent];
}
public function coreRequirement(?string $component = null): ?string
{
return $this->coreBlock($component)['requires'];
} }
public function testedCore(?string $component = null): ?string public function testedCore(?string $component = null): ?string
{ {
if ($component !== null) { return $this->coreBlock($component)['tested'];
return $this->component($component)->coreTested ?? $this->coreTested; }
}
return $this->coreTested; public function coreIndependent(?string $component = null): bool
{
return $this->coreBlock($component)['independent'] === true;
} }
/** /**
+9 -5
View File
@@ -1,6 +1,6 @@
{ {
"name": "http", "name": "http",
"version": "0.1.1", "version": "0.1.2",
"description": "Utilidades HTTP (CurlRequest, Aria2, Proxy, CompreFace)", "description": "Utilidades HTTP (CurlRequest, Aria2, Proxy, CompreFace)",
"core": { "core": {
"requires": ">=0.1", "requires": ">=0.1",
@@ -11,7 +11,8 @@
"curlRequest": { "curlRequest": {
"files": [ "files": [
"src/Libs/CurlRequest.php" "src/Libs/CurlRequest.php"
] ],
"description": "Cliente HTTP sobre cURL con cabeceras y c\u00f3digo de estado"
}, },
"aria2": { "aria2": {
"files": [ "files": [
@@ -20,7 +21,8 @@
"core": { "core": {
"requires": ">=0.1", "requires": ">=0.1",
"tested": "0.1" "tested": "0.1"
} },
"description": "Cliente JSON-RPC de aria2 (cola de descargas)"
}, },
"proxy": { "proxy": {
"files": [ "files": [
@@ -29,7 +31,8 @@
"core": { "core": {
"requires": ">=0.1", "requires": ">=0.1",
"tested": "0.1" "tested": "0.1"
} },
"description": "Proxy HTML con filtros de respuesta"
}, },
"compreFace": { "compreFace": {
"files": [ "files": [
@@ -41,7 +44,8 @@
"core": { "core": {
"requires": ">=0.1", "requires": ">=0.1",
"tested": "0.1" "tested": "0.1"
} },
"description": "Cliente de la API CompreFace (reconocimiento facial)"
} }
}, },
"default": [ "default": [
+3 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "test", "name": "test",
"version": "0.1.1", "version": "0.1.2",
"description": "Kit de pruebas PHPUnit para Duckbrain", "description": "Kit de pruebas PHPUnit para Duckbrain",
"core": { "core": {
"requires": ">=0.1", "requires": ">=0.1",
@@ -15,7 +15,8 @@
], ],
"require": { "require": {
"commands:migration": ">=0.1" "commands:migration": ">=0.1"
} },
"description": "Kit de pruebas PHPUnit para el proyecto"
} }
}, },
"default": [ "default": [
+28
View File
@@ -162,3 +162,31 @@ Harness::it('build-phar genera un phar ejecutable con su sha256', function () {
rrmdir($dist); rrmdir($dist);
}); });
Harness::it('el phar resuelve su catálogo embebido y su raíz sin --toolbox', function () {
$repo = $GLOBALS['g10_repo'];
$dist = tmpdir('dist');
exec('DUCKBRAIN_DIST=' . escapeshellarg($dist) . ' bash ' . escapeshellarg($repo . '/scripts/build-phar') . ' 2>&1', $out, $code);
eq(0, $code, 'build-phar termina bien');
$phar = $dist . '/duckbrain.phar';
// Ejecutado desde $dist (cwd sin packages/), sin --toolbox: la raíz debe
// resolverse al propio phar y el catálogo debe leerse bajo phar://.
$lines = [];
exec('cd ' . escapeshellarg($dist) . ' && php ' . escapeshellarg($phar) . ' catalog 2>&1', $lines, $ccode);
eq(0, $ccode, 'catalog desde el phar termina bien');
$text = implode("\n", $lines);
ok(str_contains($text, 'commands'), 'descubre paquetes embebidos bajo phar://');
ok(str_contains($text, 'curlRequest'), 'los componentes embebidos aparecen sin flags');
// Alta de un componente desde el catálogo embebido, sin --toolbox.
$proj = $dist . '/proj';
$lines2 = [];
exec('cd ' . escapeshellarg($dist) . ' && php ' . escapeshellarg($phar) . ' add id --root=' . escapeshellarg($proj) . ' --yes 2>&1', $lines2, $acode);
eq(0, $acode, 'add desde el phar sin --toolbox');
ok(is_file($proj . '/src/Libs/Ulid.php'), 'el archivo del componente quedó instalado');
rrmdir($dist);
});
+17 -11
View File
@@ -9,9 +9,9 @@ $GLOBALS['g11_repo'] = dirname(__DIR__);
/** /**
* Contratos: * Contratos:
* - levels.json debe cubrir exactamente los componentes del catalogo. * - levels.json debe cubrir exactamente los componentes del catalogo.
* - si tests/compat/report.json existe, todo 'tested' declarado debe estar * - si tests/compat/report.json existe: todo 'tested' declarado debe estar
* respaldado por un 'ok' del reporte, y los niveles 'none' no deben * respaldado por un 'ok' del reporte, y el nivel 'none' de evidencia debe
* declarar tested. * coincidir con la declaracion 'core: none' del manifiesto (bidireccional).
* Sin reporte (entorno offline sin haber corrido el barrido) solo se exige el * Sin reporte (entorno offline sin haber corrido el barrido) solo se exige el
* primer contrato. * primer contrato.
*/ */
@@ -51,19 +51,25 @@ Harness::it('los stamps tested estan respaldados por el reporte del barrido', fu
$report = json_decode((string) file_get_contents($reportPath), true); $report = json_decode((string) file_get_contents($reportPath), true);
ok(is_array($report) && isset($report['components']), 'report.json valido'); ok(is_array($report) && isset($report['components']), 'report.json valido');
$levels = json_decode((string) file_get_contents($repo . '/tests/compat/levels.json'), true); $levels = json_decode((string) file_get_contents($repo . '/tests/compat/levels.json'), true);
$catalog = Catalog::fromRoot($repo); $catalog = Catalog::fromRoot($repo);
foreach ($catalog->packages() as $manifest) { foreach ($catalog->packages() as $manifest) {
foreach (array_keys($manifest->components()) as $component) { foreach (array_keys($manifest->components()) as $component) {
$id = $manifest->name . ':' . $component; $id = $manifest->name . ':' . $component;
$level = $levels[$manifest->name][$component] ?? null; $level = $levels[$manifest->name][$component] ?? null;
$level = is_array($level) ? $level['level'] : $level; $level = is_array($level) ? $level['level'] : $level;
$status = $report['components'][$id]['status'] ?? 'missing'; $status = $report['components'][$id]['status'] ?? 'missing';
$tested = $manifest->testedCore($component); $tested = $manifest->testedCore($component);
$independ = $manifest->coreIndependent($component);
if ($level === 'none') { if ($level === 'none') {
eq(null, $tested, "$id esta deliberadamente sin datos y no debe declarar tested"); ok($independ, "$id esta sin evidencia de barrido y debe declarar core none");
}
if ($independ) {
eq('none', $level, "$id se declara independiente y su nivel debe ser none");
eq(null, $tested, "$id independiente no puede declarar tested");
continue; continue;
} }
+18
View File
@@ -0,0 +1,18 @@
<?php
use Toolbox\Config;
Harness::suite('group12');
Harness::it('los defaults de lectura son HTTPS anónimos y los env ganan', function () {
putenv('DUCKBRAIN_TOOLBOX_URL');
putenv('DUCKBRAIN_CORE_URL');
ok(str_starts_with(Config::toolboxUrl(), 'https://'), 'toolboxUrl por defecto en https');
ok(str_starts_with(Config::coreUrl(), 'https://'), 'coreUrl por defecto en https');
putenv('DUCKBRAIN_CORE_URL=ssh://git@example.test/kj/duckbrain.git');
eq('ssh://git@example.test/kj/duckbrain.git', Config::coreUrl(), 'el override gana sobre el default');
putenv('DUCKBRAIN_CORE_URL');
});
+33
View File
@@ -146,3 +146,36 @@ Harness::it('la descripcion del componente prevalece y hereda del paquete', func
'components' => ['c' => ['files' => ['c.php'], 'description' => 7]], 'components' => ['c' => ['files' => ['c.php'], 'description' => 7]],
]), 'description no-string es inválida'); ]), 'description no-string es inválida');
}); });
Harness::it('core admite "none" como bloque con herencia completa', function () {
$m = Manifest::fromArray([
'name' => 'pkg',
'version' => '1.0.0',
'core' => 'none',
'components' => [
'a' => ['files' => ['src/A.php']],
'b' => ['files' => ['src/B.php'], 'core' => ['requires' => '>=0.2', 'tested' => '0.2']],
],
]);
ok($m->coreIndependent('a'), 'a hereda la independencia del paquete');
ok(!$m->coreIndependent('b'), 'b sobreescribe el bloque con su rango');
eq('>=0.2', $m->coreRequirement('b'));
eq('0.2', $m->testedCore('b'));
eq(null, $m->coreRequirement('a'), 'independiente no arrastra rangos');
$m2 = Manifest::fromArray([
'name' => 'pkg2',
'version' => '1.0.0',
'core' => ['requires' => '>=0.1'],
'components' => ['c' => ['files' => ['src/C.php'], 'core' => 'none']],
]);
ok($m2->coreIndependent('c'), 'componente declara none sobre rango de paquete');
eq(null, $m2->coreRequirement('c'), 'el rango del paquete no se filtra al bloque declarado none');
eq('>=0.1', $m2->coreRequirement());
throws(fn () => Manifest::fromArray([
'name' => 'bad', 'version' => '1.0.0', 'core' => 'otro',
'components' => ['x' => ['files' => ['x.php']]],
]), 'core string distinto de none es inválido');
});
+64
View File
@@ -66,3 +66,67 @@ Harness::it('doctor no modifica lock ni archivos', function () {
rrmdir($root); rrmdir($root);
rrmdir($tool); rrmdir($tool);
}); });
Harness::it('core independiente: sin aviso en add incluso sin core conocido', function () {
$root = tmpdir('proj');
$tool = tmpdir('tool');
write_file($tool . '/packages/http/duckbrain.json', json_encode([
'name' => 'http', 'version' => '1.0.0', 'description' => 'HTTP',
'core' => 'none',
'components' => ['aria2' => ['files' => ['src/Libs/Aria2.php']]],
]));
write_file($tool . '/packages/http/src/Libs/Aria2.php', "<?php\n");
write_file($root . '/src/Libs/Router.php', "<?php\n");
$lock = Lock::load($root);
$lock->setCore(['version' => null, 'commit' => 'x', 'files' => []]);
$lock->save($root);
$out = fopen('php://memory', 'rw');
$inst = new Toolbox\Installer($root, $tool, new Console($out));
$res = $inst->add(['http:aria2'], []);
rewind($out);
$text = (string) stream_get_contents($out);
eq([], $res['warnings'], 'independiente no produce aviso');
eq([], $res['aborted'], 'nada se aborta');
ok(str_contains(implode(',', $res['installed']), 'http:aria2'), 'instala normal');
ok(!str_contains($text, 'sin datos'), 'sin ruido en consola');
// control: mismo fixture sin declaración sí avisa
write_file($tool . '/packages/http/duckbrain.json', json_encode([
'name' => 'http', 'version' => '1.0.1', 'description' => 'HTTP',
'components' => ['aria2' => ['files' => ['src/Libs/Aria2.php']]],
]));
$out2 = fopen('php://memory', 'rw');
$res2 = (new Toolbox\Installer($root, $tool, new Console($out2)))->add(['http:aria2'], ['yes' => true]);
ok($res2['warnings'] !== [], 'sin declaración sigue avisando');
rrmdir($root);
rrmdir($tool);
});
Harness::it('doctor muestra independiente sin rangos y sin fallo', function () {
$root = tmpdir('proj');
$tool = tmpdir('tool');
write_file($tool . '/packages/db/duckbrain.json', json_encode([
'name' => 'db', 'version' => '1.0.0', 'description' => 'DB',
'components' => ['sql' => ['files' => ['src/Libs/Sql.php'], 'core' => 'none']],
]));
write_file($tool . '/packages/db/src/Libs/Sql.php', "<?php\n");
$lock = Lock::load($root);
$lock->setCore(['version' => '1.5.0', 'commit' => 'c', 'files' => []]);
$lock->setComponent('db:sql', ['package' => 'db', 'version' => '1.0.0', 'mode' => 'copy', 'files' => []]);
$lock->save($root);
$out = fopen('php://memory', 'rw');
$code = (new DoctorCommand(new Console($out)))->run(['--root=' . $root, '--toolbox=' . $tool]);
rewind($out);
$text = (string) stream_get_contents($out);
eq(0, $code);
ok(str_contains($text, 'INDEPENDIENTE'), 'estado independiente visible');
rrmdir($root);
rrmdir($tool);
});