Vai al contenuto

Sottomoduli

Git I sottomoduli incorporano un repository in un altro. Nel tree del repository padre, un sottomodulo è rappresentato da una voce gitlink (modalità 160000) che punta a un commit specifico nel repository del sottomodulo. Il URL del sottomodulo e il relativo percorso sono dichiarati nel file .gitmodules.

Concetti

Nel tree del repository padre:

Codice
100644 blob abc123...  README.md
040000 tree def456...  src/
160000 commit 789012... lib/external    <-- gitlink entry (submodule)

La voce gitlink registra quale commit del sottomodulo deve essere estratto. Il repository effettivo del sottomodulo si trova in .git/modules/<name>/.

SubmoduleManager

PHP
use Pitmaster\Submodule\SubmoduleManager;

$manager = new SubmoduleManager(
    $repo->objectDatabase(),
    $repo->workDir(),
    $repo->gitDir(),
);

Elencare i sottomoduli

PHP
$submodules = $manager->list();

foreach ($submodules as $sub) {
    echo "{$sub->name}: {$sub->url} at {$sub->path}\n";
    if ($sub->branch !== null) {
        echo "  tracks branch: {$sub->branch}\n";
    }
}

Oggetto valore del sottomodulo

PHP
use Pitmaster\Submodule\Submodule;

$sub->name;     // Submodule name (from .gitmodules section header)
$sub->path;     // Path in the working tree
$sub->url;      // Remote URL
$sub->branch;   // Tracked branch (nullable)

Analisi di .gitmodules

Il file .gitmodules dichiara la configurazione dei sottomoduli:

Ini
[submodule "lib/external"]
    path = lib/external
    url = https://github.com/vendor/lib.git
    branch = main

[submodule "tools/helper"]
    path = tools/helper
    url = https://github.com/vendor/helper.git
PHP
$content = file_get_contents('.gitmodules');
$submodules = SubmoduleManager::parseGitmodules($content);

foreach ($submodules as $sub) {
    echo "{$sub->name} -> {$sub->url}\n";
}

Il parser gestisce:

  • Intestazioni di sezione: [submodule "<name>"]
  • Coppie chiave-valore: path = ..., url = ..., branch = ...
  • Commenti (righe che iniziano con #)
  • Spazi bianchi e rientri

Le voci prive di path o url vengono ignorate. I valori non vengono rimossi dalle virgolette.

Le voci gitlink sono voci dell'albero con modalità 160000. Puntano a un commit (non a un albero o a un blob) nel repository del sottomodulo.

PHP
$tree = $repo->readObject($treeHash);

foreach ($tree->entries as $entry) {
    if ($entry->isGitlink()) {
        echo "Submodule at {$entry->name}: commit {$entry->hash->hex}\n";
    }
}

Rilevamento di TreeEntry

PHP
$entry->isGitlink();  // true if mode is '160000'
$entry->mode;         // '160000'

Inizializzare i sottomoduli

PHP
$manager->init();

Per ogni sottomodulo dichiarato in .gitmodules:

  1. Crea una directory .git/modules/<name>/ vuota
  2. Crea la directory del percorso del sottomodulo, se non esiste
  3. Registra submodule.<name>.active = true e submodule.<name>.url in .git/config

Non recupera né estrae alcun contenuto e non scrive il file .git del sottomodulo.

Aggiornare i sottomoduli

PHP
$manager->update($repo->head()->tree);

Per ogni sottomodulo fissato nell'albero specificato, update() copia la directory git del repository di origine in .git/modules/<name>/, sostituisce i file di lavoro del sottomodulo con quelli dell'origine, scrive il file .git che punta alla directory del modulo, imposta core.worktree e scollega HEAD sul commit fissato.

Il URL del sottomodulo deve essere un percorso locale: assoluto o relativo alla directory di lavoro del genitore (git risolve invece gli URL relativi rispetto al URL remoto del genitore). Un URL con uno schema (https://...) genera RuntimeException('Submodule update currently supports only local paths: ...').

Dopo un aggiornamento, potete aprire ogni sottomodulo come repository separato:

PHP
$subRepo = Pitmaster::open($repo->workDir() . '/lib/external');

Verificare i commit fissati

PHP
$headCommit = $repo->head();
$pinnedId = $manager->pinnedCommit('lib/external', $headCommit->tree);

if ($pinnedId !== null) {
    echo "lib/external is pinned to commit {$pinnedId->hex}\n";
}

Il metodo pinnedCommit() percorre la gerarchia degli alberi per trovare la voce gitlink nel percorso indicato e restituisce l'hash del commit di destinazione.

Stato dei sottomoduli

PHP
$headCommit = $repo->head();
$statuses = $manager->status($headCommit->tree);

foreach ($statuses as $status) {
    $expected = $status['expected'] ?? 'not pinned';
    $actual = $status['actual'] ?? 'not initialized';
    $dirty = $status['dirty'] ? ' (dirty)' : '';

    echo "{$status['name']}: expected={$expected}, actual={$actual}{$dirty}\n";
}

Campi dello stato:

  • name: nome del sottomodulo
  • path: percorso nella directory di lavoro
  • expected: hash del commit fissato nell'albero padre (null se assente)
  • actual: HEAD corrente del sottomodulo (null se non inizializzato)
  • dirty: true quando entrambi i commit sono noti e differiscono. Le modifiche nella directory di lavoro del sottomodulo non vengono controllate.

Struttura delle directory

Codice
project/
  .git/
    modules/
      lib/
        external/          # Submodule's actual git directory (.git/modules/<name>)
        HEAD
        objects/
        refs/
        ...
  .gitmodules              # Submodule declarations
  lib/
    external/
      .git                 # File: "gitdir: ../../.git/modules/lib/external"
      src/
      README.md
  src/
  README.md

Flusso di lavoro dei sottomoduli

PHP
// 1. Open the parent repo
$repo = Pitmaster::open('/path/to/project');

// 2. List submodules
$manager = new SubmoduleManager(
    $repo->objectDatabase(),
    $repo->workDir(),
    $repo->gitDir(),
);

$submodules = $manager->list();

// 3. Populate the submodules pinned at HEAD (local source paths only)
$manager->update($repo->head()->tree);

// 4. Check status
$statuses = $manager->status($repo->head()->tree);

// 5. Open a submodule as its own repo
$subRepo = Pitmaster::open($repo->workDir() . '/lib/external');
$subHead = $subRepo->head();
echo "Submodule HEAD: {$subHead->id->hex}\n";