Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41dc18673c | ||
|
|
0c7eecb97d | ||
|
|
9c80f13748 | ||
|
|
5a28e37998 | ||
|
|
16e5dd2200 | ||
|
|
66544caea6 | ||
|
|
9e020f0ea6 | ||
|
|
a37d4f89de | ||
|
|
c82e095b75 | ||
|
|
8168865f3a | ||
|
|
4b80b885e0 | ||
|
|
e2b9fc0392 | ||
|
|
a60e1eebb7 | ||
|
|
4014551aae |
+20
-3
@@ -123,10 +123,14 @@ se bloquea y pide =--force=, =--backup= o =--keep-local=.
|
|||||||
#+BEGIN_SRC sh
|
#+BEGIN_SRC sh
|
||||||
duckbrain update core # sólo el núcleo
|
duckbrain update core # sólo el núcleo
|
||||||
duckbrain update http # un paquete
|
duckbrain update http # un paquete
|
||||||
duckbrain update # todo: catálogo -> core -> componentes
|
duckbrain update # componentes instalados
|
||||||
duckbrain update --dry-run # muestra el plan sin escribir
|
duckbrain update --dry-run # muestra el plan sin escribir
|
||||||
#+END_SRC
|
#+END_SRC
|
||||||
|
|
||||||
|
=update core= repara el ledger del core si viene de una versión antigua y
|
||||||
|
reporta el resultado por archivo (=written=, =overwritten=, =backed_up=,
|
||||||
|
=skipped=, =removed=, =aborted=) más un resumen.
|
||||||
|
|
||||||
** =duckbrain list= / =duckbrain doctor= / =duckbrain catalog= / =duckbrain adopt=
|
** =duckbrain list= / =duckbrain doctor= / =duckbrain catalog= / =duckbrain adopt=
|
||||||
|
|
||||||
- =list=: core y componentes instalados con versión y modo.
|
- =list=: core y componentes instalados con versión y modo.
|
||||||
@@ -174,8 +178,21 @@ Así =crypto/src/Libs/Crypto.php= → =src/Libs/Crypto.php= y
|
|||||||
- =.duckbrain/lock.json=: lo que *tienes* (core y componentes, con versión,
|
- =.duckbrain/lock.json=: lo que *tienes* (core y componentes, con versión,
|
||||||
commit del toolbox y hash por archivo).
|
commit del toolbox y hash por archivo).
|
||||||
|
|
||||||
|
El hash de cada archivo del core es siempre el *canónico* de la versión
|
||||||
|
registrada, nunca el del archivo en disco. Así el drift se deriva de una fuente
|
||||||
|
fiable: =sha256(disco) != lock=. El bloque =core= lleva un =schema= (2 para este
|
||||||
|
formato) que permite reconocer ledgers heredados.
|
||||||
|
|
||||||
|
Los locks creados antes de v0.2.9 guardaron en algunos casos el hash local en
|
||||||
|
lugar del canónico. La primera operación de core sobre ese proyecto recomputa
|
||||||
|
los hashes desde el =commit= registrado y migra el ledger sin tocar archivos. Si
|
||||||
|
la versión vieja del core no está disponible, la operación se detiene en lugar
|
||||||
|
de arriesgar una escritura destructiva.
|
||||||
|
|
||||||
Los hashes permiten detectar ediciones locales. La actualización respeta lo que
|
Los hashes permiten detectar ediciones locales. La actualización respeta lo que
|
||||||
editaste y te pregunta antes de pisarlo.
|
editaste y te pregunta antes de pisarlo. =--keep-local= es durable: el archivo
|
||||||
|
saltado queda registrado con el canónico de la versión destino y se vuelve a
|
||||||
|
proteger en las actualizaciones siguientes, no sólo en la primera.
|
||||||
|
|
||||||
* Migrar un proyecto existente
|
* Migrar un proyecto existente
|
||||||
|
|
||||||
@@ -209,7 +226,7 @@ Cómo trata =adopt= cada archivo:
|
|||||||
|------------------------------+--------------------------------------+-------------|
|
|------------------------------+--------------------------------------+-------------|
|
||||||
| Coincide con el catálogo | Lo registra como =adopted= | No |
|
| Coincide con el catálogo | Lo registra como =adopted= | No |
|
||||||
| Existe pero difiere | Lo registra con =origin: local= | No |
|
| Existe pero difiere | Lo registra con =origin: local= | No |
|
||||||
| Del core (existe en el core) | Registra el hash actual en =lock.core= | No |
|
| Del core (existe en el core) | Registra el hash canónico en =lock.core= | No |
|
||||||
| Ajeno al core/addons | No lo toca | No |
|
| Ajeno al core/addons | No lo toca | No |
|
||||||
|
|
||||||
Las copias divergentes quedan marcadas como *edición local*: un =update=
|
Las copias divergentes quedan marcadas como *edición local*: un =update=
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "commands",
|
"name": "commands",
|
||||||
"version": "0.2.5",
|
"version": "0.2.10",
|
||||||
"description": "CLI y migraciones para Duckbrain",
|
"description": "CLI y migraciones para Duckbrain",
|
||||||
"components": {
|
"components": {
|
||||||
"cli": {
|
"cli": {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ class Toolbox implements CommandInterface
|
|||||||
public static function aliases(): array
|
public static function aliases(): array
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'add', 'remove', 'update', 'list', 'doctor', 'catalog', 'adopt',
|
'add', 'remove', 'update', 'list', 'doctor', 'catalog', 'adopt', 'commands',
|
||||||
'help', '--help', '-h', '--version', '-V',
|
'help', '--help', '-h', '--version', '-V',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ namespace Toolbox;
|
|||||||
use Toolbox\Commands\AddCommand;
|
use Toolbox\Commands\AddCommand;
|
||||||
use Toolbox\Commands\AdoptCommand;
|
use Toolbox\Commands\AdoptCommand;
|
||||||
use Toolbox\Commands\CatalogCommand;
|
use Toolbox\Commands\CatalogCommand;
|
||||||
|
use Toolbox\Commands\CommandsCommand;
|
||||||
use Toolbox\Commands\DoctorCommand;
|
use Toolbox\Commands\DoctorCommand;
|
||||||
use Toolbox\Commands\InstallCommand;
|
use Toolbox\Commands\InstallCommand;
|
||||||
use Toolbox\Commands\ListCommand;
|
use Toolbox\Commands\ListCommand;
|
||||||
@@ -24,6 +25,7 @@ final class Cli
|
|||||||
'doctor' => DoctorCommand::class,
|
'doctor' => DoctorCommand::class,
|
||||||
'catalog' => CatalogCommand::class,
|
'catalog' => CatalogCommand::class,
|
||||||
'adopt' => AdoptCommand::class,
|
'adopt' => AdoptCommand::class,
|
||||||
|
'commands' => CommandsCommand::class,
|
||||||
'self-update' => SelfUpdateCommand::class,
|
'self-update' => SelfUpdateCommand::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ final class AdoptCommand extends Command
|
|||||||
'toolbox_commit' => null,
|
'toolbox_commit' => null,
|
||||||
'mode' => 'copy',
|
'mode' => 'copy',
|
||||||
'origin' => $hasLocal ? 'local' : 'adopted',
|
'origin' => $hasLocal ? 'local' : 'adopted',
|
||||||
|
'description' => $package->descriptionOf($component->name),
|
||||||
'files' => $files,
|
'files' => $files,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -88,7 +89,7 @@ final class AdoptCommand extends Command
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$coreAdopted = $this->adoptCore($parsed['options'], $root, $lock, $dryRun);
|
[$coreAdopted, $coreHasLocal] = $this->adoptCore($parsed['options'], $root, $lock, $dryRun);
|
||||||
|
|
||||||
if (!$dryRun) {
|
if (!$dryRun) {
|
||||||
$lock->save($root);
|
$lock->save($root);
|
||||||
@@ -99,7 +100,8 @@ final class AdoptCommand extends Command
|
|||||||
$this->console->ok('adoptado ' . $id . $mark);
|
$this->console->ok('adoptado ' . $id . $mark);
|
||||||
}
|
}
|
||||||
if ($coreAdopted > 0) {
|
if ($coreAdopted > 0) {
|
||||||
$this->console->ok("adoptado el core ({$coreAdopted} archivos)");
|
$mark = $coreHasLocal ? ' (con ediciones locales)' : '';
|
||||||
|
$this->console->ok("adoptado el core ({$coreAdopted} archivos){$mark}");
|
||||||
}
|
}
|
||||||
if ($adopted === [] && $coreAdopted === 0) {
|
if ($adopted === [] && $coreAdopted === 0) {
|
||||||
$this->console->out('No se encontró nada que adoptar.');
|
$this->console->out('No se encontró nada que adoptar.');
|
||||||
@@ -110,43 +112,54 @@ final class AdoptCommand extends Command
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Registra el core existente: sólo los archivos que también existen en el
|
* Registra el core existente: sólo los archivos que también existen en el
|
||||||
* core de referencia, con su hash actual. No toca archivos.
|
* core de referencia, con su hash CANÓNICO. Si la copia local difiere,
|
||||||
|
* el archivo queda marcado como edición local y `update core` preguntará
|
||||||
|
* antes de pisarla (mismo contrato que `adoptComponent`).
|
||||||
*
|
*
|
||||||
* @param array<string, string|bool> $options
|
* @param array<string, string|bool> $options
|
||||||
|
* @return array{0:int,1:bool}
|
||||||
*/
|
*/
|
||||||
private function adoptCore(array $options, string $root, $lock, bool $dryRun): int
|
private function adoptCore(array $options, string $root, $lock, bool $dryRun): array
|
||||||
{
|
{
|
||||||
if ($lock->core() !== null) {
|
if ($lock->core() !== null) {
|
||||||
return 0;
|
return [0, false];
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$provider = $this->coreProvider($options);
|
$provider = $this->coreProvider($options);
|
||||||
} catch (ToolboxException $e) {
|
} catch (ToolboxException $e) {
|
||||||
$this->console->warn('no se pudo resolver el core para adoptar: ' . $e->getMessage());
|
$this->console->warn('no se pudo resolver el core para adoptar: ' . $e->getMessage());
|
||||||
return 0;
|
return [0, false];
|
||||||
}
|
}
|
||||||
|
|
||||||
$files = [];
|
$files = [];
|
||||||
|
$hasLocal = false;
|
||||||
foreach ($provider->files() as $relative) {
|
foreach ($provider->files() as $relative) {
|
||||||
$absolute = $root . '/' . $relative;
|
$absolute = $root . '/' . $relative;
|
||||||
if (is_file($absolute)) {
|
if (!is_file($absolute)) {
|
||||||
$files[$relative] = Drift::hash($absolute);
|
continue;
|
||||||
|
}
|
||||||
|
$canonical = $provider->read($relative);
|
||||||
|
$files[$relative] = 'sha256:' . hash('sha256', $canonical);
|
||||||
|
if (file_get_contents($absolute) !== $canonical) {
|
||||||
|
$hasLocal = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($files === []) {
|
if ($files === []) {
|
||||||
return 0;
|
return [0, false];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$dryRun) {
|
if (!$dryRun) {
|
||||||
$lock->setCore([
|
$lock->setCore([
|
||||||
|
'schema' => 2,
|
||||||
'version' => $provider->version(),
|
'version' => $provider->version(),
|
||||||
'commit' => $provider->commit(),
|
'commit' => $provider->commit(),
|
||||||
'files' => $files,
|
'files' => $files,
|
||||||
|
'origin' => $hasLocal ? 'local' : 'adopted',
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return count($files);
|
return [count($files), $hasLocal];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Toolbox\Commands;
|
||||||
|
|
||||||
|
use Toolbox\Lock;
|
||||||
|
use Toolbox\Ownership;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Superficie ejecutable del proyecto: comandos en src/Commands con sus
|
||||||
|
* aliases, descripciones y origen. A diferencia del despachador del bin,
|
||||||
|
* las colisiones de alias aquí se REPORTAN (marcadas con !) y no abortan.
|
||||||
|
*/
|
||||||
|
final class CommandsCommand extends Command
|
||||||
|
{
|
||||||
|
public static function describe(): string
|
||||||
|
{
|
||||||
|
return 'Lista los comandos disponibles del proyecto';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run(array $args): int
|
||||||
|
{
|
||||||
|
$parsed = $this->parse($args);
|
||||||
|
$root = $this->root($parsed['options']);
|
||||||
|
|
||||||
|
$autoload = $root . '/autoload.php';
|
||||||
|
if (!defined('ROOT_CORE') && is_file($autoload)) {
|
||||||
|
$previous = getcwd();
|
||||||
|
chdir($root);
|
||||||
|
try {
|
||||||
|
include_once $autoload;
|
||||||
|
} catch (\Throwable) {
|
||||||
|
// el proyecto no arranca: se lista sin clases cargables
|
||||||
|
}
|
||||||
|
if ($previous !== false) {
|
||||||
|
chdir($previous);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$coreDir = defined('ROOT_CORE') ? rtrim(ROOT_CORE, '/') : $root . '/src';
|
||||||
|
$dir = $coreDir . '/Commands';
|
||||||
|
|
||||||
|
if (!is_dir($dir)) {
|
||||||
|
$this->console->out('El proyecto no tiene comandos en src/Commands.');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lock = Lock::load($root);
|
||||||
|
$ownership = Ownership::fromLock($lock);
|
||||||
|
|
||||||
|
$info = [];
|
||||||
|
$aliasOwners = [];
|
||||||
|
|
||||||
|
foreach (glob($dir . '/*.php') as $file) {
|
||||||
|
$base = basename($file, '.php');
|
||||||
|
$class = 'Commands\\' . $base;
|
||||||
|
|
||||||
|
if (!class_exists($class, true) || !is_a($class, 'Interfaces\\CommandInterface', true)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$aliases = method_exists($class, 'aliases') ? $class::aliases() : [];
|
||||||
|
foreach ($aliases as $alias) {
|
||||||
|
$aliasOwners[strtolower((string) $alias)][] = $class;
|
||||||
|
}
|
||||||
|
|
||||||
|
$owner = $ownership->ownerOf('src/Commands/' . $base . '.php');
|
||||||
|
$origin = 'proyecto';
|
||||||
|
if ($owner === 'core') {
|
||||||
|
$origin = 'core';
|
||||||
|
} elseif ($owner !== null) {
|
||||||
|
$origin = $owner . '@' . ($lock->component($owner)['version'] ?? '?');
|
||||||
|
}
|
||||||
|
|
||||||
|
$info[$base] = [
|
||||||
|
'class' => $class,
|
||||||
|
'describe' => $class::describe(),
|
||||||
|
'aliases' => $aliases,
|
||||||
|
'origin' => $origin,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$collisions = [];
|
||||||
|
foreach ($aliasOwners as $alias => $owners) {
|
||||||
|
$uniq = array_unique($owners);
|
||||||
|
if (count($uniq) > 1) {
|
||||||
|
$collisions[$alias] = $uniq;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($info as $base => $row) {
|
||||||
|
foreach ($row['aliases'] as $alias) {
|
||||||
|
$aKey = strtolower((string) $alias);
|
||||||
|
foreach (array_keys($info) as $other) {
|
||||||
|
if (strtolower($other) !== $aKey || $other === $base) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$owners = array_values(array_unique([...($collisions[$aKey] ?? []), $row['class'], $info[$other]['class']]));
|
||||||
|
$collisions[$aKey] = $owners;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows = [['COMANDO', 'ALIASES', 'DESCRIPCIÓN', 'ORIGEN']];
|
||||||
|
foreach ($info as $base => $row) {
|
||||||
|
$marks = [];
|
||||||
|
foreach ($row['aliases'] as $alias) {
|
||||||
|
$marks[] = (isset($collisions[strtolower((string) $alias)]) ? $alias . '!' : (string) $alias);
|
||||||
|
}
|
||||||
|
$marked = $marks === [] ? '—' : implode(', ', $marks);
|
||||||
|
if ($marked !== '—' && isset($collisions[strtolower($base)])) {
|
||||||
|
$marked .= ' !';
|
||||||
|
}
|
||||||
|
|
||||||
|
$rows[] = [strtolower($base), $marked, $row['describe'], $row['origin']];
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->console->table($rows);
|
||||||
|
|
||||||
|
foreach ($collisions as $alias => $owners) {
|
||||||
|
$this->console->warn("alias '{$alias}' declarado o robado por: " . implode(', ', $owners));
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,15 +19,21 @@ final class ListCommand extends Command
|
|||||||
$toolbox = $this->toolboxDir($parsed['options']);
|
$toolbox = $this->toolboxDir($parsed['options']);
|
||||||
$installer = new Installer($root, $toolbox, $this->console, $this->rootCore($parsed['options'], $root));
|
$installer = new Installer($root, $toolbox, $this->console, $this->rootCore($parsed['options'], $root));
|
||||||
|
|
||||||
$rows = [['TIPO', 'ID', 'VERSIÓN', 'MODO']];
|
$rows = [['TIPO', 'ID', 'VERSIÓN', 'MODO', 'DESCRIPCIÓN']];
|
||||||
|
|
||||||
$core = $installer->lock()->core();
|
$core = $installer->lock()->core();
|
||||||
if ($core !== null) {
|
if ($core !== null) {
|
||||||
$rows[] = ['core', 'core', (string) ($core['version'] ?? '?'), 'copy'];
|
$rows[] = ['core', 'core', (string) ($core['version'] ?? '?'), 'copy', ''];
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($installer->lock()->components() as $id => $entry) {
|
foreach ($installer->lock()->components() as $id => $entry) {
|
||||||
$rows[] = [$entry['package'], $id, $entry['version'], $entry['mode']];
|
$rows[] = [
|
||||||
|
$entry['package'],
|
||||||
|
$id,
|
||||||
|
$entry['version'],
|
||||||
|
$entry['mode'],
|
||||||
|
$entry['description'] ?? '—',
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (count($rows) === 1) {
|
if (count($rows) === 1) {
|
||||||
|
|||||||
@@ -24,6 +24,20 @@ final class UpdateCommand extends Command
|
|||||||
if (($parsed['args'][0] ?? null) === 'core') {
|
if (($parsed['args'][0] ?? null) === 'core') {
|
||||||
$provider = $this->coreProvider($parsed['options']);
|
$provider = $this->coreProvider($parsed['options']);
|
||||||
$result = $installer->updateCore($provider, $options);
|
$result = $installer->updateCore($provider, $options);
|
||||||
|
|
||||||
|
$counts = [];
|
||||||
|
foreach ($result['actions'] as $file => $action) {
|
||||||
|
$this->console->out(' ' . $action . ' ' . $file);
|
||||||
|
$counts[$action] = ($counts[$action] ?? 0) + 1;
|
||||||
|
}
|
||||||
|
if ($counts !== []) {
|
||||||
|
$summary = [];
|
||||||
|
foreach ($counts as $action => $count) {
|
||||||
|
$summary[] = $action . '=' . $count;
|
||||||
|
}
|
||||||
|
$this->console->out(' resumen: ' . implode(' ', $summary));
|
||||||
|
}
|
||||||
|
|
||||||
$this->console->ok('core ' . ($result['version'] ?? '?'));
|
$this->console->ok('core ' . ($result['version'] ?? '?'));
|
||||||
foreach ($result['aborted'] as $aborted) {
|
foreach ($result['aborted'] as $aborted) {
|
||||||
$this->console->error('abortado: ' . $aborted);
|
$this->console->error('abortado: ' . $aborted);
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ namespace Toolbox;
|
|||||||
*/
|
*/
|
||||||
final class Config
|
final class Config
|
||||||
{
|
{
|
||||||
public const VERSION = '0.2.5';
|
public const VERSION = '0.2.10';
|
||||||
|
|
||||||
public static function toolboxUrl(): string
|
public static function toolboxUrl(): string
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -189,4 +189,75 @@ final class CoreProvider
|
|||||||
|
|
||||||
return (string) file_get_contents($path);
|
return (string) file_get_contents($path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hashes canónicos de un conjunto de rutas en un ref histórico del core.
|
||||||
|
* Se usa para reparar ledgers heredados que guardaron hashes locales.
|
||||||
|
*
|
||||||
|
* Prefiere el commit (identidad inmutable) y cae al tag `v<versión>`.
|
||||||
|
* Devuelve null si el ref o alguna de las rutas no se pueden resolver.
|
||||||
|
*
|
||||||
|
* @param list<string> $paths
|
||||||
|
* @return array<string, string>|null
|
||||||
|
*/
|
||||||
|
public function canonicalAt(?string $commit, ?string $version, array $paths): ?array
|
||||||
|
{
|
||||||
|
if (!$this->isGit() || $paths === []) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$refs = [];
|
||||||
|
if ($commit !== null && $commit !== '') {
|
||||||
|
$refs[] = $commit;
|
||||||
|
}
|
||||||
|
if ($version !== null && $version !== '') {
|
||||||
|
$refs[] = 'v' . ltrim($version, 'vV');
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (array_unique($refs) as $ref) {
|
||||||
|
exec(
|
||||||
|
'git -C ' . escapeshellarg($this->dir) . ' rev-parse --verify --quiet ' .
|
||||||
|
escapeshellarg($ref . '^{commit}') . ' 2>/dev/null',
|
||||||
|
$ignored,
|
||||||
|
$code
|
||||||
|
);
|
||||||
|
if ($code !== 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = [];
|
||||||
|
$ok = true;
|
||||||
|
foreach ($paths as $relative) {
|
||||||
|
$tmp = tempnam(sys_get_temp_dir(), 'dbcore');
|
||||||
|
if ($tmp === false) {
|
||||||
|
$ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
exec(
|
||||||
|
'git -C ' . escapeshellarg($this->dir) . ' show ' .
|
||||||
|
escapeshellarg($ref . ':' . $relative) .
|
||||||
|
' > ' . escapeshellarg($tmp) . ' 2>/dev/null',
|
||||||
|
$ignored,
|
||||||
|
$exists
|
||||||
|
);
|
||||||
|
if ($exists !== 0) {
|
||||||
|
@unlink($tmp);
|
||||||
|
$ok = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$content = (string) file_get_contents($tmp);
|
||||||
|
@unlink($tmp);
|
||||||
|
|
||||||
|
$files[$relative] = 'sha256:' . hash('sha256', $content);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($ok) {
|
||||||
|
return $files;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,14 +15,12 @@ final class FileSync
|
|||||||
public const ABORTED = 'aborted';
|
public const ABORTED = 'aborted';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Decide qué haría `write()` sin tocar el disco.
|
||||||
|
*
|
||||||
* @param array{force?:bool, backup?:bool, keepLocal?:bool} $options
|
* @param array{force?:bool, backup?:bool, keepLocal?:bool} $options
|
||||||
*/
|
*/
|
||||||
public function write(string $path, string $contents, ?string $expected, array $options = []): string
|
public function plan(string $path, string $contents, ?string $expected, array $options = []): string
|
||||||
{
|
{
|
||||||
if (!is_dir(dirname($path))) {
|
|
||||||
mkdir(dirname($path), 0777, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
$existed = is_file($path);
|
$existed = is_file($path);
|
||||||
$drifted = $existed && Drift::isDrifted($path, $expected);
|
$drifted = $existed && Drift::isDrifted($path, $expected);
|
||||||
|
|
||||||
@@ -31,27 +29,17 @@ final class FileSync
|
|||||||
// heredado) un archivo existente también puede respaldarse.
|
// heredado) un archivo existente también puede respaldarse.
|
||||||
$changed = $existed && (string) file_get_contents($path) !== $contents;
|
$changed = $existed && (string) file_get_contents($path) !== $contents;
|
||||||
if ($changed && ($options['backup'] ?? false)) {
|
if ($changed && ($options['backup'] ?? false)) {
|
||||||
copy($path, $path . '.bak');
|
|
||||||
file_put_contents($path, $contents);
|
|
||||||
|
|
||||||
return self::BACKED_UP;
|
return self::BACKED_UP;
|
||||||
}
|
}
|
||||||
|
|
||||||
file_put_contents($path, $contents);
|
|
||||||
|
|
||||||
return $existed ? self::OVERWRITTEN : self::WRITTEN;
|
return $existed ? self::OVERWRITTEN : self::WRITTEN;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($options['force'] ?? false) {
|
if ($options['force'] ?? false) {
|
||||||
file_put_contents($path, $contents);
|
|
||||||
|
|
||||||
return self::OVERWRITTEN;
|
return self::OVERWRITTEN;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($options['backup'] ?? false) {
|
if ($options['backup'] ?? false) {
|
||||||
copy($path, $path . '.bak');
|
|
||||||
file_put_contents($path, $contents);
|
|
||||||
|
|
||||||
return self::BACKED_UP;
|
return self::BACKED_UP;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +53,34 @@ final class FileSync
|
|||||||
/**
|
/**
|
||||||
* @param array{force?:bool, backup?:bool, keepLocal?:bool} $options
|
* @param array{force?:bool, backup?:bool, keepLocal?:bool} $options
|
||||||
*/
|
*/
|
||||||
public function remove(string $path, ?string $expected, array $options = []): string
|
public function write(string $path, string $contents, ?string $expected, array $options = []): string
|
||||||
|
{
|
||||||
|
if (!is_dir(dirname($path))) {
|
||||||
|
mkdir(dirname($path), 0777, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
$action = $this->plan($path, $contents, $expected, $options);
|
||||||
|
|
||||||
|
if ($action === self::WRITTEN || $action === self::OVERWRITTEN) {
|
||||||
|
file_put_contents($path, $contents);
|
||||||
|
|
||||||
|
return $action;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($action === self::BACKED_UP) {
|
||||||
|
copy($path, $path . '.bak');
|
||||||
|
file_put_contents($path, $contents);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $action;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decide qué haría `remove()` sin tocar el disco.
|
||||||
|
*
|
||||||
|
* @param array{force?:bool, backup?:bool, keepLocal?:bool} $options
|
||||||
|
*/
|
||||||
|
public function planRemove(string $path, ?string $expected, array $options = []): string
|
||||||
{
|
{
|
||||||
if (!is_file($path)) {
|
if (!is_file($path)) {
|
||||||
return self::SKIPPED;
|
return self::SKIPPED;
|
||||||
@@ -79,10 +94,28 @@ final class FileSync
|
|||||||
}
|
}
|
||||||
|
|
||||||
if ($options['backup'] ?? false) {
|
if ($options['backup'] ?? false) {
|
||||||
copy($path, $path . '.bak');
|
return self::BACKED_UP;
|
||||||
} else {
|
}
|
||||||
|
|
||||||
return self::ABORTED;
|
return self::ABORTED;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return self::OVERWRITTEN;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array{force?:bool, backup?:bool, keepLocal?:bool} $options
|
||||||
|
*/
|
||||||
|
public function remove(string $path, ?string $expected, array $options = []): string
|
||||||
|
{
|
||||||
|
$action = $this->planRemove($path, $expected, $options);
|
||||||
|
|
||||||
|
if ($action === self::SKIPPED || $action === self::ABORTED) {
|
||||||
|
return $action;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($action === self::BACKED_UP) {
|
||||||
|
copy($path, $path . '.bak');
|
||||||
}
|
}
|
||||||
|
|
||||||
unlink($path);
|
unlink($path);
|
||||||
|
|||||||
@@ -157,6 +157,7 @@ final class Installer
|
|||||||
'version' => $version,
|
'version' => $version,
|
||||||
'toolbox_commit' => $commit,
|
'toolbox_commit' => $commit,
|
||||||
'mode' => $mode,
|
'mode' => $mode,
|
||||||
|
'description' => $manifest->descriptionOf($componentName),
|
||||||
'files' => $result['files'],
|
'files' => $result['files'],
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -270,7 +271,26 @@ final class Installer
|
|||||||
private function writeCore(CoreProvider $provider, array $options, bool $removeStale): array
|
private function writeCore(CoreProvider $provider, array $options, bool $removeStale): array
|
||||||
{
|
{
|
||||||
$protected = $this->componentOwnedPaths();
|
$protected = $this->componentOwnedPaths();
|
||||||
$expected = $this->lock->core()['files'] ?? [];
|
$core = $this->lock->core();
|
||||||
|
$expected = $core['files'] ?? [];
|
||||||
|
$origin = $core['origin'] ?? null;
|
||||||
|
|
||||||
|
if ($expected !== [] && $this->lock->coreSchema() < 2) {
|
||||||
|
$canonical = $provider->canonicalAt(
|
||||||
|
$core['commit'] ?? null,
|
||||||
|
$core['version'] ?? null,
|
||||||
|
array_keys($expected)
|
||||||
|
);
|
||||||
|
if ($canonical === null) {
|
||||||
|
$ref = $core['commit'] ?? $core['version'] ?? '?';
|
||||||
|
throw new ToolboxException(
|
||||||
|
'No se pudo reparar el lock del core: la versión registrada (' . $ref . ') no está disponible. ' .
|
||||||
|
'Actualiza la caché del core o apunta --core-dir a esa versión.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
$expected = $canonical;
|
||||||
|
}
|
||||||
|
|
||||||
$files = $provider->files();
|
$files = $provider->files();
|
||||||
|
|
||||||
$installed = [];
|
$installed = [];
|
||||||
@@ -282,8 +302,18 @@ final class Installer
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$contents = $provider->read($relative);
|
||||||
$absolute = $this->root . '/' . $relative;
|
$absolute = $this->root . '/' . $relative;
|
||||||
$action = $this->sync->write($absolute, $provider->read($relative), $expected[$relative] ?? null, $options);
|
$hash = 'sha256:' . hash('sha256', $contents);
|
||||||
|
|
||||||
|
if ($options['dryRun'] ?? false) {
|
||||||
|
$planned = $this->sync->plan($absolute, $contents, $expected[$relative] ?? null, $options);
|
||||||
|
$actions[$relative] = 'planned-' . $planned;
|
||||||
|
$installed[$relative] = $hash;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$action = $this->sync->write($absolute, $contents, $expected[$relative] ?? null, $options);
|
||||||
$actions[$relative] = $action;
|
$actions[$relative] = $action;
|
||||||
|
|
||||||
if ($action === FileSync::ABORTED) {
|
if ($action === FileSync::ABORTED) {
|
||||||
@@ -291,7 +321,9 @@ final class Installer
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
$installed[$relative] = Drift::hash($absolute);
|
// Ledger canónico: también para archivos saltados con --keep-local,
|
||||||
|
// de modo que sigan detectándose como drift en el próximo update.
|
||||||
|
$installed[$relative] = $hash;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($removeStale) {
|
if ($removeStale) {
|
||||||
@@ -299,19 +331,44 @@ final class Installer
|
|||||||
if (isset($installed[$relative]) || isset($protected[$relative]) || in_array($relative, $files, true)) {
|
if (isset($installed[$relative]) || isset($protected[$relative]) || in_array($relative, $files, true)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
$action = $this->sync->remove($this->root . '/' . $relative, $hash, $options);
|
if ($options['dryRun'] ?? false) {
|
||||||
|
$planned = $this->sync->planRemove($this->root . '/' . $relative, $hash, $options);
|
||||||
|
$actions[$relative] = $planned === FileSync::OVERWRITTEN
|
||||||
|
? 'planned-removed'
|
||||||
|
: 'planned-' . $planned;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$absolute = $this->root . '/' . $relative;
|
||||||
|
$action = $this->sync->remove($absolute, $hash, $options);
|
||||||
if ($action === FileSync::ABORTED) {
|
if ($action === FileSync::ABORTED) {
|
||||||
$aborted[] = $relative;
|
$aborted[] = $relative;
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
if ($action === FileSync::SKIPPED) {
|
||||||
|
if (is_file($absolute)) {
|
||||||
|
$actions[$relative] = 'skipped';
|
||||||
|
$this->console->warn('obsoleto conservado localmente: ' . $relative . ' (ya no gestionado)');
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$actions[$relative] = 'removed';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($aborted === [] && !($options['dryRun'] ?? false)) {
|
if ($aborted === [] && !($options['dryRun'] ?? false)) {
|
||||||
$this->lock->setCore([
|
$newCore = [
|
||||||
|
'schema' => 2,
|
||||||
'version' => $provider->version() ?? $this->coreVersion(),
|
'version' => $provider->version() ?? $this->coreVersion(),
|
||||||
'commit' => $provider->commit() ?? ($this->lock->core()['commit'] ?? null),
|
'commit' => $provider->commit() ?? ($core['commit'] ?? null),
|
||||||
'files' => $installed,
|
'files' => $installed,
|
||||||
]);
|
];
|
||||||
|
if ($origin !== null) {
|
||||||
|
$newCore['origin'] = $origin;
|
||||||
|
} elseif (!$removeStale) {
|
||||||
|
$newCore['origin'] = 'toolbox';
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->lock->setCore($newCore);
|
||||||
$this->lock->save($this->root);
|
$this->lock->save($this->root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ final class Lock
|
|||||||
'toolbox_commit' => $entry['toolbox_commit'] ?? null,
|
'toolbox_commit' => $entry['toolbox_commit'] ?? null,
|
||||||
'mode' => (string) ($entry['mode'] ?? 'copy'),
|
'mode' => (string) ($entry['mode'] ?? 'copy'),
|
||||||
'origin' => (string) ($entry['origin'] ?? 'toolbox'),
|
'origin' => (string) ($entry['origin'] ?? 'toolbox'),
|
||||||
|
'description' => $entry['description'] ?? null,
|
||||||
'files' => is_array($entry['files'] ?? null) ? $entry['files'] : [],
|
'files' => is_array($entry['files'] ?? null) ? $entry['files'] : [],
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -57,12 +58,21 @@ final class Lock
|
|||||||
return new self($data['core'] ?? null, $components);
|
return new self($data['core'] ?? null, $components);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @return array{version?:string, commit?:string, files?:array<string,string>}|null */
|
/** @return array{schema?:int, version?:string, commit?:string, origin?:string, files?:array<string,string>}|null */
|
||||||
public function core(): ?array
|
public function core(): ?array
|
||||||
{
|
{
|
||||||
return $this->core;
|
return $this->core;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Esquema del ledger del core: 1 = heredado (hash del disco), 2 = hashes
|
||||||
|
* canónicos. La ausencia de marca se interpreta como heredado.
|
||||||
|
*/
|
||||||
|
public function coreSchema(): int
|
||||||
|
{
|
||||||
|
return (int) ($this->core['schema'] ?? 1);
|
||||||
|
}
|
||||||
|
|
||||||
/** @return array<string, array{package:string, version:string, toolbox_commit:?string, mode:string, files:array<string,string>}> */
|
/** @return array<string, array{package:string, version:string, toolbox_commit:?string, mode:string, files:array<string,string>}> */
|
||||||
public function components(): array
|
public function components(): array
|
||||||
{
|
{
|
||||||
@@ -79,7 +89,7 @@ final class Lock
|
|||||||
return $this->components[$id] ?? null;
|
return $this->components[$id] ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @param array{version?:string, commit?:string, files?:array<string,string>} $core */
|
/** @param array{schema?:int, version?:string, commit?:string, origin?:string, files?:array<string,string>} $core */
|
||||||
public function setCore(array $core): void
|
public function setCore(array $core): void
|
||||||
{
|
{
|
||||||
$this->core = $core;
|
$this->core = $core;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "crypto",
|
"name": "crypto",
|
||||||
"version": "0.1.1",
|
"version": "0.1.2",
|
||||||
"description": "Criptograf\u00eda y segundo factor (Crypto, Nonce, TwoFactorAuthenticator)",
|
"description": "Criptograf\u00eda y segundo factor (Crypto, Nonce, TwoFactorAuthenticator)",
|
||||||
"core": {
|
"core": {
|
||||||
"requires": ">=0.1",
|
"requires": ">=0.1",
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ class Crypto
|
|||||||
*/
|
*/
|
||||||
public static function decryptHex(string $data, string $password = PRIVATE_KEY): string
|
public static function decryptHex(string $data, string $password = PRIVATE_KEY): string
|
||||||
{
|
{
|
||||||
|
if ($data === '' || !ctype_xdigit($data) || strlen($data) % 2 !== 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
return static::decrypt(hex2bin($data), $password);
|
return static::decrypt(hex2bin($data), $password);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,10 @@ class Nonce
|
|||||||
*/
|
*/
|
||||||
public static function check(string $nonce, string $passphrase = ''): bool
|
public static function check(string $nonce, string $passphrase = ''): bool
|
||||||
{
|
{
|
||||||
|
if ($nonce === '' || !ctype_xdigit($nonce) || strlen($nonce) % 2 !== 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
$decripted = openssl_decrypt(
|
$decripted = openssl_decrypt(
|
||||||
hex2bin($nonce),
|
hex2bin($nonce),
|
||||||
'aes-128-ecb',
|
'aes-128-ecb',
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "htmx",
|
"name": "htmx",
|
||||||
"version": "0.1.1",
|
"version": "0.2.0",
|
||||||
"description": "Motor de vistas basado en componentes y HTMX",
|
"description": "Motor de vistas basado en componentes y HTMX",
|
||||||
"core": {
|
"core": {
|
||||||
"requires": ">=0.1",
|
"requires": ">=0.1",
|
||||||
|
|||||||
@@ -13,29 +13,6 @@ namespace Libs;
|
|||||||
*/
|
*/
|
||||||
class HTMX extends HTMLComponent
|
class HTMX extends HTMLComponent
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* Valid HTMX swap styles.
|
|
||||||
*/
|
|
||||||
public const SWAP_STYLES = [
|
|
||||||
'innerHTML', 'outerHTML', 'outerSync',
|
|
||||||
'beforebegin', 'before',
|
|
||||||
'afterbegin', 'prepend',
|
|
||||||
'beforeend', 'append',
|
|
||||||
'afterend', 'after',
|
|
||||||
'delete', 'none',
|
|
||||||
'innerMorph', 'outerMorph',
|
|
||||||
'textContent',
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Valid HTMX swap option keys (used as key:value after the style).
|
|
||||||
*/
|
|
||||||
public const SWAP_OPTIONS = [
|
|
||||||
'swap', 'settle', 'transition', 'ignoreTitle', 'strip',
|
|
||||||
'focusScroll', 'swapEmpty', 'scroll', 'show', 'showTarget',
|
|
||||||
'scrollTarget', 'target',
|
|
||||||
];
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders a component
|
* Renders a component
|
||||||
*
|
*
|
||||||
@@ -266,8 +243,6 @@ class HTMX extends HTMLComponent
|
|||||||
* @param bool $excludeBoosted Exclude if the request is boosted (default: false)
|
* @param bool $excludeBoosted Exclude if the request is boosted (default: false)
|
||||||
*
|
*
|
||||||
* @return string
|
* @return string
|
||||||
*
|
|
||||||
* @throws \InvalidArgumentException On an unknown style or option.
|
|
||||||
*/
|
*/
|
||||||
public static function swapOob(string $value = 'true', bool $excludeBoosted = false): string
|
public static function swapOob(string $value = 'true', bool $excludeBoosted = false): string
|
||||||
{
|
{
|
||||||
@@ -275,10 +250,6 @@ class HTMX extends HTMLComponent
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($value !== 'true') {
|
|
||||||
$value = static::validateSwap($value);
|
|
||||||
}
|
|
||||||
|
|
||||||
return static::isHtmx() ? 'hx-swap-oob="' . $value . '"' : '';
|
return static::isHtmx() ? 'hx-swap-oob="' . $value . '"' : '';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,8 +289,6 @@ class HTMX extends HTMLComponent
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
$swap = static::validateSwap($swap);
|
|
||||||
|
|
||||||
return '<hx-partial hx-target="' . htmlspecialchars($target)
|
return '<hx-partial hx-target="' . htmlspecialchars($target)
|
||||||
. '" hx-swap="' . htmlspecialchars($swap) . '">'
|
. '" hx-swap="' . htmlspecialchars($swap) . '">'
|
||||||
. $content
|
. $content
|
||||||
@@ -381,52 +350,10 @@ class HTMX extends HTMLComponent
|
|||||||
* @param string $rule
|
* @param string $rule
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*
|
|
||||||
* @throws \InvalidArgumentException On an unknown style or option.
|
|
||||||
*/
|
*/
|
||||||
public static function reswap(string $rule = 'innerHTML'): void
|
public static function reswap(string $rule = 'innerHTML'): void
|
||||||
{
|
{
|
||||||
header('HX-Reswap: ' . static::validateSwap($rule));
|
header('HX-Reswap: ' . $rule);
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates a HTMX swap value ("style [key:value]...").
|
|
||||||
*
|
|
||||||
* @param string $value
|
|
||||||
*
|
|
||||||
* @return string The normalized value.
|
|
||||||
*
|
|
||||||
* @throws \InvalidArgumentException On an unknown style or option.
|
|
||||||
*/
|
|
||||||
public static function validateSwap(string $value): string
|
|
||||||
{
|
|
||||||
$parts = preg_split(
|
|
||||||
'/\s+/',
|
|
||||||
trim($value),
|
|
||||||
-1,
|
|
||||||
PREG_SPLIT_NO_EMPTY
|
|
||||||
);
|
|
||||||
|
|
||||||
if (empty($parts)) {
|
|
||||||
throw new \InvalidArgumentException('Empty swap value.');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!in_array($parts[0], static::SWAP_STYLES, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'Invalid swap style: ' . $parts[0]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (array_slice($parts, 1) as $option) {
|
|
||||||
$key = explode(':', $option)[0];
|
|
||||||
if (!in_array($key, static::SWAP_OPTIONS, true)) {
|
|
||||||
throw new \InvalidArgumentException(
|
|
||||||
'Invalid swap option: ' . $option
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return implode(' ', $parts);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -46,6 +46,30 @@ Harness::it('lock guarda core y componentes con schema esperado', function () {
|
|||||||
rrmdir($dir);
|
rrmdir($dir);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Harness::it('guardar componentes no asciende el esquema del core', function () {
|
||||||
|
$dir = tmpdir();
|
||||||
|
$lock = Lock::empty();
|
||||||
|
$lock->setCore(['schema' => 1, 'version' => '1.0.0', 'commit' => 'abc', 'files' => ['a' => 'sha256:x']]);
|
||||||
|
$lock->setComponent('p:c', [
|
||||||
|
'package' => 'p',
|
||||||
|
'version' => '1.0.0',
|
||||||
|
'toolbox_commit' => null,
|
||||||
|
'mode' => 'copy',
|
||||||
|
'files' => [],
|
||||||
|
]);
|
||||||
|
$lock->save($dir);
|
||||||
|
|
||||||
|
eq(1, Lock::load($dir)->coreSchema(), 'un guardado de componentes preserva el esquema legacy');
|
||||||
|
$raw = json_decode((string) file_get_contents(Lock::path($dir)), true);
|
||||||
|
eq(1, $raw['core']['schema'], 'el JSON conserva schema 1');
|
||||||
|
|
||||||
|
unset($raw['core']['schema']);
|
||||||
|
file_put_contents(Lock::path($dir), json_encode($raw));
|
||||||
|
eq(1, Lock::load($dir)->coreSchema(), 'sin marca se interpreta como esquema 1');
|
||||||
|
|
||||||
|
rrmdir($dir);
|
||||||
|
});
|
||||||
|
|
||||||
Harness::it('ownership detecta colisión de rutas', function () {
|
Harness::it('ownership detecta colisión de rutas', function () {
|
||||||
$lock = Lock::empty();
|
$lock = Lock::empty();
|
||||||
$lock->setCore(['files' => ['src/Libs/X.php' => 'sha256:a']]);
|
$lock->setCore(['files' => ['src/Libs/X.php' => 'sha256:a']]);
|
||||||
@@ -100,3 +124,52 @@ Harness::it('destino explícito sobreescribe la regla', function () {
|
|||||||
$dest = Destination::relative('src/Libs/Crypto.php', '/proj', '/proj/src', ['src/Libs/Crypto.php' => 'elsewhere/Crypto.php']);
|
$dest = Destination::relative('src/Libs/Crypto.php', '/proj', '/proj/src', ['src/Libs/Crypto.php' => 'elsewhere/Crypto.php']);
|
||||||
eq('elsewhere/Crypto.php', $dest);
|
eq('elsewhere/Crypto.php', $dest);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Harness::it('el lock persiste la descripción y tolera locks sin el campo', function () {
|
||||||
|
$dir = tmpdir();
|
||||||
|
$lock = Lock::empty();
|
||||||
|
$lock->setComponent('db:sql', [
|
||||||
|
'package' => 'db',
|
||||||
|
'version' => '1.0.0',
|
||||||
|
'mode' => 'copy',
|
||||||
|
'description' => 'SQL',
|
||||||
|
'files' => [],
|
||||||
|
]);
|
||||||
|
$lock->save($dir);
|
||||||
|
|
||||||
|
eq('SQL', Lock::load($dir)->component('db:sql')['description'], 'roundtrip de description');
|
||||||
|
|
||||||
|
$raw = json_decode((string) file_get_contents($dir . '/.duckbrain/lock.json'), true);
|
||||||
|
unset($raw['components']['db:sql']['description']);
|
||||||
|
file_put_contents($dir . '/.duckbrain/lock.json', json_encode($raw));
|
||||||
|
|
||||||
|
eq(null, Lock::load($dir)->component('db:sql')['description'], 'lock antiguo sin campo se lee tolerante');
|
||||||
|
|
||||||
|
rrmdir($dir);
|
||||||
|
});
|
||||||
|
|
||||||
|
Harness::it('add captura la descripción efectiva del catálogo en el lock', function () {
|
||||||
|
$root = tmpdir('proj');
|
||||||
|
$tool = tmpdir('tool');
|
||||||
|
write_file($tool . '/packages/mix/duckbrain.json', json_encode([
|
||||||
|
'name' => 'mix',
|
||||||
|
'version' => '1.0.0',
|
||||||
|
'description' => 'Descripción del paquete',
|
||||||
|
'components' => [
|
||||||
|
'own' => ['files' => ['src/Libs/Own.php'], 'description' => 'Descripción propia'],
|
||||||
|
'inh' => ['files' => ['src/Libs/Inh.php']],
|
||||||
|
],
|
||||||
|
'default' => ['own', 'inh'],
|
||||||
|
]));
|
||||||
|
write_file($tool . '/packages/mix/src/Libs/Own.php', "<?php\n");
|
||||||
|
write_file($tool . '/packages/mix/src/Libs/Inh.php', "<?php\n");
|
||||||
|
|
||||||
|
(new Toolbox\Installer($root, $tool, new Toolbox\Console()))->add(['mix'], ['yes' => true]);
|
||||||
|
|
||||||
|
$lock = Lock::load($root);
|
||||||
|
eq('Descripción propia', $lock->component('mix:own')['description'], 'propia gana en el lock');
|
||||||
|
eq('Descripción del paquete', $lock->component('mix:inh')['description'], 'sin propia, hereda del paquete');
|
||||||
|
|
||||||
|
rrmdir($root);
|
||||||
|
rrmdir($tool);
|
||||||
|
});
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ use Toolbox\Commands\ListCommand;
|
|||||||
use Toolbox\Commands\RemoveCommand;
|
use Toolbox\Commands\RemoveCommand;
|
||||||
use Toolbox\Commands\UpdateCommand;
|
use Toolbox\Commands\UpdateCommand;
|
||||||
use Toolbox\Console;
|
use Toolbox\Console;
|
||||||
|
use Toolbox\CoreProvider;
|
||||||
|
use Toolbox\Drift;
|
||||||
use Toolbox\Lock;
|
use Toolbox\Lock;
|
||||||
|
|
||||||
Harness::suite('group7');
|
Harness::suite('group7');
|
||||||
@@ -71,6 +73,82 @@ function g7_console(&$stream): Console
|
|||||||
return new Console($stream, $stream);
|
return new Console($stream, $stream);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repo del core con dos versiones y una ruta que desaparece en v0.1.1.
|
||||||
|
* Queda con el working tree en el último tag.
|
||||||
|
*/
|
||||||
|
function g7_core_history(): string
|
||||||
|
{
|
||||||
|
$dir = tmpdir('corehist');
|
||||||
|
write_file($dir . '/autoload.php', <<<'PHP'
|
||||||
|
<?php
|
||||||
|
define('ROOT_DIR', __DIR__);
|
||||||
|
define('ROOT_CORE', ROOT_DIR . '/src');
|
||||||
|
spl_autoload_register(function (string $class): void {
|
||||||
|
$fp = str_replace('\\', '/', $class);
|
||||||
|
$file = ROOT_CORE . '/' . dirname($fp) . '/' . basename($fp) . '.php';
|
||||||
|
if (file_exists($file)) {
|
||||||
|
require_once $file;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
PHP);
|
||||||
|
write_file($dir . '/config.php', "<?php\n");
|
||||||
|
write_file($dir . '/src/Libs/Router.php', "<?php\n// router-v1\n");
|
||||||
|
write_file($dir . '/src/Libs/Legacy.php', "<?php\n// legacy\n");
|
||||||
|
write_file($dir . '/src/Empty/.gitkeep', '');
|
||||||
|
git_init($dir);
|
||||||
|
git_commit($dir, 'core v1');
|
||||||
|
git_tag($dir, 'v0.1.0');
|
||||||
|
|
||||||
|
write_file($dir . '/src/Libs/Router.php', "<?php\n// router-v2\n");
|
||||||
|
exec('git -C ' . escapeshellarg($dir) . ' rm -q src/Libs/Legacy.php');
|
||||||
|
git_commit($dir, 'core v2');
|
||||||
|
git_tag($dir, 'v0.1.1');
|
||||||
|
|
||||||
|
return $dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
function g7_core_tag(string $dir, string $version, string $router): void
|
||||||
|
{
|
||||||
|
write_file($dir . '/src/Libs/Router.php', "<?php\n// " . $router . "\n");
|
||||||
|
git_commit($dir, 'core ' . $version);
|
||||||
|
git_tag($dir, 'v' . $version);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param list<string> $paths */
|
||||||
|
function g7_materialize(string $repo, string $ref, string $root, array $paths): void
|
||||||
|
{
|
||||||
|
foreach ($paths as $path) {
|
||||||
|
$contents = shell_exec(
|
||||||
|
'git -C ' . escapeshellarg($repo) . ' show ' . escapeshellarg($ref . ':' . $path) . ' 2>/dev/null'
|
||||||
|
);
|
||||||
|
write_file($root . '/' . $path, (string) $contents);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, string> */
|
||||||
|
function g7_legacy_lock(string $proj, string $repo): array
|
||||||
|
{
|
||||||
|
$oldCommit = trim((string) shell_exec('git -C ' . escapeshellarg($repo) . ' rev-parse v0.1.0'));
|
||||||
|
$routerHash = 'sha256:' . hash('sha256', (string) shell_exec(
|
||||||
|
'git -C ' . escapeshellarg($repo) . ' show v0.1.0:src/Libs/Router.php'
|
||||||
|
));
|
||||||
|
|
||||||
|
$files = [
|
||||||
|
'autoload.php' => Drift::hash($proj . '/autoload.php'),
|
||||||
|
'config.php' => Drift::hash($proj . '/config.php'),
|
||||||
|
'src/Libs/Router.php' => $routerHash,
|
||||||
|
'src/Libs/Legacy.php' => Drift::hash($proj . '/src/Libs/Legacy.php'),
|
||||||
|
];
|
||||||
|
|
||||||
|
write_file($proj . '/.duckbrain/lock.json', json_encode([
|
||||||
|
'core' => ['version' => '0.1.0', 'commit' => $oldCommit, 'files' => $files],
|
||||||
|
'components' => [],
|
||||||
|
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n");
|
||||||
|
|
||||||
|
return $files;
|
||||||
|
}
|
||||||
|
|
||||||
Harness::it('install descarga el core en un directorio vacío', function () {
|
Harness::it('install descarga el core en un directorio vacío', function () {
|
||||||
$proj = tmpdir('proj');
|
$proj = tmpdir('proj');
|
||||||
$core = g7_core('0.1.0');
|
$core = g7_core('0.1.0');
|
||||||
@@ -194,6 +272,48 @@ Harness::it('--dry-run no escribe archivos ni lock', function () {
|
|||||||
rrmdir($tool);
|
rrmdir($tool);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Harness::it('update core --dry-run no escribe archivos', function () {
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
$tool = g7_toolbox();
|
||||||
|
$core = g7_core('1.0.0', 'router-v1');
|
||||||
|
$core2 = g7_core('2.0.0', 'router-v2');
|
||||||
|
|
||||||
|
(new InstallCommand(new Console()))->run([$proj, '--toolbox=' . $tool, '--core-dir=' . $core, '--yes']);
|
||||||
|
|
||||||
|
$routerBefore = (string) file_get_contents($proj . '/src/Libs/Router.php');
|
||||||
|
(new UpdateCommand(new Console()))->run(['core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $core2, '--yes', '--dry-run']);
|
||||||
|
|
||||||
|
ok(str_contains($routerBefore, 'router-v1'), 'estado inicial correcto');
|
||||||
|
ok(str_contains((string) file_get_contents($proj . '/src/Libs/Router.php'), 'router-v1'), 'dry-run no escribe el fichero');
|
||||||
|
eq('1.0.0', Lock::load($proj)->core()['version'], 'dry-run no actualiza la version en el lock');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($tool);
|
||||||
|
rrmdir($core);
|
||||||
|
rrmdir($core2);
|
||||||
|
});
|
||||||
|
|
||||||
|
Harness::it('update core --dry-run aborta por drift sin escribir', function () {
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
$tool = g7_toolbox();
|
||||||
|
$core = g7_core('1.0.0', 'router-v1');
|
||||||
|
$core2 = g7_core('2.0.0', 'router-v2');
|
||||||
|
|
||||||
|
(new InstallCommand(new Console()))->run([$proj, '--toolbox=' . $tool, '--core-dir=' . $core, '--yes']);
|
||||||
|
write_file($proj . '/config.php', "<?php\n// customizado\n");
|
||||||
|
|
||||||
|
(new UpdateCommand(new Console()))->run(['core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $core2, '--yes', '--dry-run']);
|
||||||
|
|
||||||
|
ok(!is_file($proj . '/config.php.bak'), 'dry-run no crea backups');
|
||||||
|
ok(str_contains((string) file_get_contents($proj . '/config.php'), 'customizado'), 'dry-run conserva la edicion local');
|
||||||
|
ok(str_contains((string) file_get_contents($proj . '/src/Libs/Router.php'), 'router-v1'), 'dry-run no toca ficheros sin drift');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($tool);
|
||||||
|
rrmdir($core);
|
||||||
|
rrmdir($core2);
|
||||||
|
});
|
||||||
|
|
||||||
Harness::it('core sin tags: versión desconocida y commit pineado', function () {
|
Harness::it('core sin tags: versión desconocida y commit pineado', function () {
|
||||||
$proj = tmpdir('proj');
|
$proj = tmpdir('proj');
|
||||||
$tool = g7_toolbox();
|
$tool = g7_toolbox();
|
||||||
@@ -278,3 +398,146 @@ Harness::it('un comando del proyecto sin describe() no carga (interfaz estricta)
|
|||||||
|
|
||||||
rrmdir($proj);
|
rrmdir($proj);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Harness::it('canonicalAt lee un ref viejo y falla cerrado con refs o rutas ausentes', function () {
|
||||||
|
$repo = g7_core_history();
|
||||||
|
$old = trim((string) shell_exec('git -C ' . escapeshellarg($repo) . ' rev-parse v0.1.0'));
|
||||||
|
$provider = CoreProvider::fromDirectory($repo);
|
||||||
|
|
||||||
|
$hashes = $provider->canonicalAt($old, null, ['src/Libs/Router.php', 'src/Libs/Legacy.php', 'src/Empty/.gitkeep']);
|
||||||
|
ok(is_array($hashes), 'resuelve el ref viejo');
|
||||||
|
$canonicalRouter = 'sha256:' . hash('sha256', (string) shell_exec(
|
||||||
|
'git -C ' . escapeshellarg($repo) . ' show v0.1.0:src/Libs/Router.php'
|
||||||
|
));
|
||||||
|
eq($canonicalRouter, $hashes['src/Libs/Router.php'], 'hash canónico histórico');
|
||||||
|
eq('sha256:' . hash('sha256', ''), $hashes['src/Empty/.gitkeep'], 'archivo vacío resuelto');
|
||||||
|
|
||||||
|
eq(null, $provider->canonicalAt('deadbeef', '9.9.9', ['src/Libs/Router.php']), 'ref inexistente');
|
||||||
|
eq(null, $provider->canonicalAt($old, null, ['src/Libs/Nope.php']), 'ruta inexistente');
|
||||||
|
|
||||||
|
rrmdir($repo);
|
||||||
|
});
|
||||||
|
|
||||||
|
Harness::it('update core repara un lock heredado y protege keep-local de forma durable', function () {
|
||||||
|
$repo = g7_core_history();
|
||||||
|
$tool = g7_toolbox();
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
$paths = ['autoload.php', 'config.php', 'src/Libs/Router.php', 'src/Libs/Legacy.php'];
|
||||||
|
|
||||||
|
g7_materialize($repo, 'v0.1.0', $proj, $paths);
|
||||||
|
$config = "<?php\n// config local del proyecto\n";
|
||||||
|
$legacy = "<?php\n// legacy custom\n";
|
||||||
|
write_file($proj . '/config.php', $config);
|
||||||
|
write_file($proj . '/src/Libs/Legacy.php', $legacy);
|
||||||
|
g7_legacy_lock($proj, $repo);
|
||||||
|
|
||||||
|
$stream = null;
|
||||||
|
$console = g7_console($stream);
|
||||||
|
$code = (new UpdateCommand($console))->run([
|
||||||
|
'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', '--keep-local',
|
||||||
|
]);
|
||||||
|
rewind($stream);
|
||||||
|
$out = (string) stream_get_contents($stream);
|
||||||
|
|
||||||
|
eq(0, $code, 'el update termina sin abortos');
|
||||||
|
eq($config, (string) file_get_contents($proj . '/config.php'), 'config local intacto');
|
||||||
|
eq($legacy, (string) file_get_contents($proj . '/src/Libs/Legacy.php'), 'obsoleto local intacto');
|
||||||
|
ok(str_contains((string) file_get_contents($proj . '/src/Libs/Router.php'), 'router-v2'), 'Router actualizado');
|
||||||
|
ok(str_contains($out, 'skipped config.php'), 'reporta el archivo saltado');
|
||||||
|
ok(str_contains($out, 'resumen:'), 'reporta un resumen por archivo');
|
||||||
|
ok(str_contains($out, 'obsoleto conservado localmente: src/Libs/Legacy.php'), 'avisa del obsoleto conservado');
|
||||||
|
|
||||||
|
$lock = Lock::load($proj);
|
||||||
|
eq(2, $lock->coreSchema(), 'el lock migra a esquema 2');
|
||||||
|
eq('0.1.1', $lock->core()['version']);
|
||||||
|
ok(!isset($lock->core()['files']['src/Libs/Legacy.php']), 'el obsoleto sale del ledger');
|
||||||
|
$canonicalConfig = 'sha256:' . hash('sha256', (string) shell_exec(
|
||||||
|
'git -C ' . escapeshellarg($repo) . ' show v0.1.1:config.php'
|
||||||
|
));
|
||||||
|
eq($canonicalConfig, $lock->core()['files']['config.php'], 'el ledger guarda el canónico destino, no el hash local');
|
||||||
|
|
||||||
|
g7_core_tag($repo, '0.1.2', 'router-v3');
|
||||||
|
(new UpdateCommand(g7_console($quiet)))->run([
|
||||||
|
'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', '--keep-local',
|
||||||
|
]);
|
||||||
|
eq($config, (string) file_get_contents($proj . '/config.php'), 'keep-local durable: config sigue intacto');
|
||||||
|
ok(str_contains((string) file_get_contents($proj . '/src/Libs/Router.php'), 'router-v3'), 'Router sigue actualizándose');
|
||||||
|
eq('0.1.2', Lock::load($proj)->core()['version']);
|
||||||
|
|
||||||
|
g7_core_tag($repo, '0.1.3', 'router-v4');
|
||||||
|
$rc = (new UpdateCommand(g7_console($quiet2)))->run([
|
||||||
|
'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes',
|
||||||
|
]);
|
||||||
|
eq(1, $rc, 'sin --keep-local el drift aborta');
|
||||||
|
eq($config, (string) file_get_contents($proj . '/config.php'), 'el aborto no pisa config');
|
||||||
|
eq('0.1.2', Lock::load($proj)->core()['version'], 'el lock no avanza con abortos');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($tool);
|
||||||
|
rrmdir($repo);
|
||||||
|
});
|
||||||
|
|
||||||
|
Harness::it('update core falla cerrado si no puede reparar el lock heredado', function () {
|
||||||
|
$repo = g7_core_history();
|
||||||
|
$fresh = g7_core('9.9.9', 'router-fresh');
|
||||||
|
$tool = g7_toolbox();
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
$paths = ['autoload.php', 'config.php', 'src/Libs/Router.php', 'src/Libs/Legacy.php'];
|
||||||
|
|
||||||
|
g7_materialize($repo, 'v0.1.0', $proj, $paths);
|
||||||
|
write_file($proj . '/config.php', "<?php\n// custom\n");
|
||||||
|
g7_legacy_lock($proj, $repo);
|
||||||
|
|
||||||
|
$lockBefore = (string) file_get_contents(Lock::path($proj));
|
||||||
|
$routerBefore = (string) file_get_contents($proj . '/src/Libs/Router.php');
|
||||||
|
|
||||||
|
$stream = null;
|
||||||
|
$console = g7_console($stream);
|
||||||
|
$code = (new UpdateCommand($console))->run([
|
||||||
|
'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $fresh, '--yes', '--keep-local',
|
||||||
|
]);
|
||||||
|
rewind($stream);
|
||||||
|
$out = (string) stream_get_contents($stream);
|
||||||
|
|
||||||
|
eq(1, $code, 'falla cerrado');
|
||||||
|
eq($lockBefore, (string) file_get_contents(Lock::path($proj)), 'el lock no se reescribe');
|
||||||
|
eq($routerBefore, (string) file_get_contents($proj . '/src/Libs/Router.php'), 'no se escribe el core');
|
||||||
|
ok(str_contains($out, 'No se pudo reparar el lock del core'), 'explica el bloqueo');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($tool);
|
||||||
|
rrmdir($repo);
|
||||||
|
rrmdir($fresh);
|
||||||
|
});
|
||||||
|
|
||||||
|
Harness::it('update core --dry-run planifica el drift sin escribir', function () {
|
||||||
|
$repo = g7_core_history();
|
||||||
|
$tool = g7_toolbox();
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
$paths = ['autoload.php', 'config.php', 'src/Libs/Router.php', 'src/Libs/Legacy.php'];
|
||||||
|
|
||||||
|
g7_materialize($repo, 'v0.1.0', $proj, $paths);
|
||||||
|
write_file($proj . '/config.php', "<?php\n// custom\n");
|
||||||
|
g7_legacy_lock($proj, $repo);
|
||||||
|
|
||||||
|
$lockBefore = (string) file_get_contents(Lock::path($proj));
|
||||||
|
$routerBefore = (string) file_get_contents($proj . '/src/Libs/Router.php');
|
||||||
|
|
||||||
|
$stream = null;
|
||||||
|
$console = g7_console($stream);
|
||||||
|
$code = (new UpdateCommand($console))->run([
|
||||||
|
'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', '--keep-local', '--dry-run',
|
||||||
|
]);
|
||||||
|
rewind($stream);
|
||||||
|
$out = (string) stream_get_contents($stream);
|
||||||
|
|
||||||
|
eq(0, $code, 'dry-run termina bien');
|
||||||
|
ok(str_contains($out, 'planned-skipped config.php'), 'planifica el archivo protegido');
|
||||||
|
ok(str_contains($out, 'planned-overwritten src/Libs/Router.php'), 'planifica el archivo a actualizar');
|
||||||
|
eq($lockBefore, (string) file_get_contents(Lock::path($proj)), 'dry-run no toca el lock');
|
||||||
|
eq($routerBefore, (string) file_get_contents($proj . '/src/Libs/Router.php'), 'dry-run no escribe archivos');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($tool);
|
||||||
|
rrmdir($repo);
|
||||||
|
});
|
||||||
|
|||||||
@@ -130,3 +130,80 @@ Harness::it('bin nuevo sin el motor: los aliases del motor son comando desconoci
|
|||||||
rrmdir($proj);
|
rrmdir($proj);
|
||||||
rrmdir($core);
|
rrmdir($core);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Harness::it('list muestra la descripción del lock por componente, con — si falta', function () {
|
||||||
|
$root = tmpdir('proj');
|
||||||
|
$tool = tmpdir('tool');
|
||||||
|
write_file($tool . '/packages/mix/duckbrain.json', json_encode([
|
||||||
|
'name' => 'mix',
|
||||||
|
'version' => '1.0.0',
|
||||||
|
'description' => 'Descripción del paquete',
|
||||||
|
'components' => [
|
||||||
|
'own' => ['files' => ['src/Libs/Own.php'], 'description' => 'Descripción propia'],
|
||||||
|
'inh' => ['files' => ['src/Libs/Inh.php']],
|
||||||
|
'old' => ['files' => ['src/Libs/Old.php']],
|
||||||
|
],
|
||||||
|
'default' => ['own', 'inh', 'old'],
|
||||||
|
]));
|
||||||
|
foreach (['Own', 'Inh', 'Old'] as $c) {
|
||||||
|
write_file($tool . "/packages/mix/src/Libs/{$c}.php", "<?php\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
(new Toolbox\Installer($root, $tool, new Console()))->add(['mix'], ['yes' => true]);
|
||||||
|
|
||||||
|
// simular lock viejo: quitar la descripción de `old`
|
||||||
|
$raw = json_decode((string) file_get_contents($root . '/.duckbrain/lock.json'), true);
|
||||||
|
unset($raw['components']['mix:old']['description']);
|
||||||
|
file_put_contents($root . '/.duckbrain/lock.json', json_encode($raw));
|
||||||
|
|
||||||
|
$out = fopen('php://memory', 'rw');
|
||||||
|
$code = (new Toolbox\Commands\ListCommand(new Console($out)))->run(['--root=' . $root, '--toolbox=' . $tool]);
|
||||||
|
rewind($out);
|
||||||
|
$text = (string) stream_get_contents($out);
|
||||||
|
|
||||||
|
eq(0, $code);
|
||||||
|
ok((bool) preg_match('/mix:own.*Descripción propia/', $text), 'fila propia con su descripción');
|
||||||
|
ok((bool) preg_match('/mix:inh.*Descripción del paquete/', $text), 'fila heredada con la del paquete');
|
||||||
|
ok((bool) preg_match('/mix:old.*—/', $text), 'lock viejo sin campo muestra —');
|
||||||
|
|
||||||
|
rrmdir($root);
|
||||||
|
rrmdir($tool);
|
||||||
|
});
|
||||||
|
|
||||||
|
Harness::it('commands lista la superficie con origen y reporta colisiones', function () {
|
||||||
|
$repo = $GLOBALS['g8_repo'];
|
||||||
|
$core = g7_core('0.1.0');
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
|
||||||
|
(new InstallCommand(new Console()))->run([$proj, '--toolbox=' . $repo, '--core-dir=' . $core, '--yes']);
|
||||||
|
(new AddCommand(new Console()))->run(['commands', 'commands:toolbox', '--root=' . $proj, '--toolbox=' . $repo, '--yes']);
|
||||||
|
|
||||||
|
$eco = "<?php\n\nnamespace Commands;\n\nclass Eco implements \\Interfaces\\CommandInterface\n{\n public static function describe(): string { return 'eco local'; }\n public static function aliases(): array { return ['hola']; }\n public function run(): void {}\n}\n";
|
||||||
|
write_file($proj . '/src/Commands/Eco.php', $eco);
|
||||||
|
|
||||||
|
// sin colisión: funciona desde el bin del proyecto
|
||||||
|
$o = []; exec('cd ' . escapeshellarg($proj) . ' && php duckbrain commands 2>&1', $o, $code);
|
||||||
|
eq(0, $code, 'bin del proyecto sirve commands');
|
||||||
|
$text = implode("\n", $o);
|
||||||
|
ok(str_contains($text, 'eco') && str_contains($text, 'hola'), 'comando propio con su alias');
|
||||||
|
ok(str_contains($text, 'proyecto'), 'origen proyecto');
|
||||||
|
ok(str_contains($text, 'commands:migration@'), 'origen componente@versión desde el lock');
|
||||||
|
|
||||||
|
// con colisión (roba el nombre de clase migration): el motor REPORTA, el bin aborta
|
||||||
|
write_file($proj . '/src/Commands/Eco.php', str_replace("['hola']", "['migration']", $eco));
|
||||||
|
|
||||||
|
$out = fopen('php://memory', 'rw');
|
||||||
|
$code = (new Toolbox\Commands\CommandsCommand(new Console($out, $out)))->run(['--root=' . $proj]);
|
||||||
|
rewind($out);
|
||||||
|
$text = (string) stream_get_contents($out);
|
||||||
|
|
||||||
|
eq(0, $code, 'la vista no aborta ante colisiones');
|
||||||
|
ok(str_contains($text, 'migration!'), 'fila marcada con !');
|
||||||
|
ok(str_contains($text, "WARN: alias 'migration'"), 'warn con los dueños');
|
||||||
|
|
||||||
|
$o = []; exec('cd ' . escapeshellarg($proj) . ' && php duckbrain list 2>&1', $o, $c2);
|
||||||
|
eq(1, $c2, 'el despachador sí aborta ante colisión (guard del bin)');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($core);
|
||||||
|
});
|
||||||
|
|||||||
@@ -121,3 +121,32 @@ Harness::it('adopt registra el core existente con sus hashes', function () {
|
|||||||
rrmdir($proj);
|
rrmdir($proj);
|
||||||
rrmdir($core);
|
rrmdir($core);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Harness::it('adopt del core registra hash canónico y marca ediciones locales', function () {
|
||||||
|
$repo = $GLOBALS['g9_repo'];
|
||||||
|
$core = g7_core('0.1.0');
|
||||||
|
$proj = tmpdir('proj');
|
||||||
|
|
||||||
|
// Copia idéntica de Router.php + config.php customizado (proyecto heredado).
|
||||||
|
write_file($proj . '/src/Libs/Router.php', (string) file_get_contents($core . '/src/Libs/Router.php'));
|
||||||
|
write_file($proj . '/config.php', "<?php\n// credenciales del proyecto\n");
|
||||||
|
|
||||||
|
(new AdoptCommand(new Console()))->run(['--root=' . $proj, '--toolbox=' . $repo, '--core-dir=' . $core]);
|
||||||
|
|
||||||
|
$lock = Lock::load($proj);
|
||||||
|
$coreHashRouter = $lock->core()['files']['src/Libs/Router.php'];
|
||||||
|
$coreHashConfig = $lock->core()['files']['config.php'];
|
||||||
|
|
||||||
|
$canonicalRouter = (string) file_get_contents($core . '/src/Libs/Router.php');
|
||||||
|
$canonicalConfig = (string) file_get_contents($core . '/config.php');
|
||||||
|
|
||||||
|
eq('sha256:' . hash('sha256', $canonicalRouter), $coreHashRouter, 'hash de Router.php = canónico');
|
||||||
|
eq('sha256:' . hash('sha256', $canonicalConfig), $coreHashConfig, 'hash de config.php = canónico (aunque el local difiera)');
|
||||||
|
eq('local', $lock->core()['origin'] ?? null, 'origin = local porque hay ediciones locales');
|
||||||
|
eq(2, $lock->coreSchema(), 'adopt graba el esquema canónico');
|
||||||
|
|
||||||
|
ok(file_get_contents($proj . '/config.php') !== $canonicalConfig, 'la copia local customizada no se tocó');
|
||||||
|
|
||||||
|
rrmdir($proj);
|
||||||
|
rrmdir($core);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user