
# リポジトリを読み取る

Pitmasterはディスク上の形式を直接解析してgitリポジトリを読み取ります。対象は、`.git/objects/`内のzlib圧縮されたルーズオブジェクト、パックファイル（`.git/objects/pack/`）、`.git/refs/`および`packed-refs`内のRef、インデックス（`.git/index`）です。

## リポジトリを開く

```php
use Pitmaster\Pitmaster;

$repo = Pitmaster::open('/path/to/project');
```

Pitmasterは3種類のリポジトリレイアウトに対応しています:

1. **通常のリポジトリ**: `.git`はプロジェクトのルートにあるディレクトリです。
2. **リンクされたワークツリー**: `.git`は`.git/worktrees/<name>/`を指す`gitdir: <path>`を含むファイルです。
3. **ベアリポジトリ**: パス自体に`HEAD`、`objects/`などが含まれます。

```php
// Detection helpers
Pitmaster::isRepository('/path');  // true for any of the above
Pitmaster::isWorktree('/path');    // true only for linked worktrees
```

## オブジェクトを読み取る

gitリポジトリ内の各データは、ハッシュで識別されるオブジェクトとして保存されます。既定ではSHA-1（40桁の16進文字列）、`Pitmaster::init($path, 'sha256')`で作成されたリポジトリではSHA-256（64桁の16進文字列）を使用します。オブジェクト型はblob、tree、commit、tagの4種類です。

以下のハッシュベースのメソッドには完全な16進ハッシュが必要です。省略形のハッシュは受け付けられません。

### readObject

```php
use Pitmaster\Object\Blob;
use Pitmaster\Object\Tree;
use Pitmaster\Object\Commit;
use Pitmaster\Object\Tag;

$object = $repo->readObject('a1b2c3d4e5f6...');

match (true) {
    $object instanceof Blob   => handleBlob($object),
    $object instanceof Tree   => handleTree($object),
    $object instanceof Commit => handleCommit($object),
    $object instanceof Tag    => handleTag($object),
};
```

オブジェクトはまずルーズストレージから検索され、次にパックファイルが検索されます。パックファイルの検索では、O(log n)の二分探索に`.idx`のfanoutテーブルを使用します。

### catFile

型を確認せずにコンテンツを簡単に取得するには:

```php
$content = $repo->catFile('a1b2c3d4e5f6...');
echo $content;
```

### objectExists

```php
if ($repo->objectExists('a1b2c3d4e5f6...')) {
    // Object is in the repository
}
```

### listObjects

```php
$hashes = $repo->listObjects();
// ['a1b2c3d4...', 'f6e5d4c3...', ...]
```

すべてのオブジェクト（ルーズおよびパック済み）の16進ハッシュを返します。

## blobを扱う

blobはファイルの生の内容を保持します。

```php
$blob = $repo->readObject($hash);
echo $blob->content;     // Raw file bytes
echo $blob->size();      // Content length
echo $blob->id->hex;     // Object hash
```

## treeを扱う

treeはディレクトリ一覧です。各エントリーにはモード、名前、ハッシュがあります。

```php
$tree = $repo->readObject($hash);

foreach ($tree->entries as $entry) {
    echo "{$entry->mode} {$entry->name} {$entry->hash->hex}\n";
    // 100644 README.md abc123...
    // 40000 src def456...
    // 100755 deploy.sh 789012...

    if ($entry->isTree()) {
        // Recurse into subdirectory (mode 40000)
    } elseif ($entry->isExecutable()) {
        // Executable file (mode 100755)
    } elseif ($entry->isBlob()) {
        // Regular file (any 10xxxx mode, so executables match too)
    } elseif ($entry->isSymlink()) {
        // Symbolic link (mode 120000)
    } elseif ($entry->isGitlink()) {
        // Submodule (mode 160000)
    }
}
```

## commitを扱う

commitはツリーのスナップショットを親とメタデータに結び付けます。

```php
$commit = $repo->head();

echo $commit->id->hex;      // Full object hash
echo $commit->tree->hex;    // Tree object hash
echo $commit->author;       // "Name <email> timestamp tz"
echo $commit->committer;    // "Name <email> timestamp tz"
echo $commit->message;      // Full commit message

// Parent commits
foreach ($commit->parents as $parentId) {
    $parent = $repo->readObject($parentId->hex);
}

// Merge detection
if ($commit->isMerge()) {
    // Two or more parents
}
```

## tagを扱う

注釈付きtagは、対象、型、名前、tagger、メッセージを持つオブジェクトです。

```php
$tag = $repo->readObject($hash);

echo $tag->object->hex;           // Target object hash
echo $tag->objectType->value;     // 'commit', 'tree', 'blob', or 'tag'
echo $tag->name;            // Tag name
echo $tag->tagger;          // "Name <email> timestamp tz"
echo $tag->message;         // Tag message
```

## Refを読み取る

### 現在のHEAD

```php
$commit = $repo->head();
```

HEAD（`HEAD -> refs/heads/main -> commit hash`などのシンボリックRefをたどる）を解決し、commitオブジェクトを返します。

### 現在のブランチ

```php
$branch = $repo->branch();  // 'main' or null if detached
```

### ブランチとtagの一覧

```php
$branches = $repo->branches();  // ['bugfix/typo', 'feature/login', 'main']
$tags = $repo->tags();          // ['v1.0.0', 'v1.1.0']
```

### すべてのRef

```php
$refs = $repo->allRefs();
// [
//     'refs/heads/main' => 'abc123...',
//     'refs/heads/feature' => 'def456...',
//     'refs/tags/v1.0.0' => '789012...',
//     'refs/remotes/origin/main' => 'abc123...',
// ]
```

### リビジョンを解決する

```php
$id = $repo->resolve('HEAD');
$id = $repo->resolve('main');
$id = $repo->resolve('v1.0.0');
$id = $repo->resolve('HEAD~3');
$id = $repo->resolve('main^2');
$id = $repo->resolve('3f2c1e0b9d6a4f8e7c5b2a1d0e9f8c7b6a5d4e3f');
```

リビジョンパーサーは`~N`（祖先）演算子と`^N`（親）演算子に対応しており、任意に連結できます。ハッシュは完全な値を指定する必要があります。

## コミット履歴をたどる

### ログ

コミットはコミッターのタイムスタンプ順に、新しいものから返されます。

```php
// Last 20 commits from HEAD
$commits = $repo->log(20);

foreach ($commits as $commit) {
    $short = substr($commit->id->hex, 0, 7);
    echo "{$short} {$commit->message}\n";
}
```

### 特定のコミットからのlog

```php
$from = $repo->resolve('feature/login');
$commits = $repo->log(10, $from);
```

### ファイルパスで絞り込んだlog

```php
$commits = $repo->logPath('src/Repository.php', 20);
```

指定されたファイルが最初の親と比べて変更された（追加、変更、削除、名前変更）コミットのみを返します。パスには正確なファイルパスを指定する必要があり、ディレクトリは一致しません。最新の`5 * $limit`件のコミットのみを調べるため、それより古い一致は見つからないことがあります（[#7](https://github.com/inline0/pitmaster/issues/7)）。

### 表示

```php
$result = $repo->show('HEAD');
$commit = $result['commit'];
$diffs = $result['diff'];

echo "Author: {$commit->author}\n";
echo "Message: {$commit->message}\n\n";

foreach ($diffs as $diff) {
    echo $diff->format();
}
```

## 既定ブランチの検出

```php
$default = $repo->defaultBranch();
// Checks: remote HEAD symref -> local HEAD -> main/master fallback
```

`remote.origin.url`が設定され、プロセスが有効な場合、最初の確認でリモートにスマートHTTPリクエストを送ります。ネットワークエラーは無視され、その後ローカルの確認が行われます。

## マージの系譜

```php
// Is feature fully merged into main?
$merged = $repo->isBranchMerged('feature/done', 'main');

// Find the merge base of two commits
$base = $repo->mergeBase(
    $repo->resolve('main'),
    $repo->resolve('feature/login'),
);
```
