
# 读取仓库

Pitmaster 通过直接解析磁盘上的格式来读取 git 仓库：松散对象（位于 `.git/objects/` 中的 zlib 压缩文件）、pack 文件（`.git/objects/pack/`）、引用（`.git/refs/` 和 `packed-refs` 中的文件）以及索引（`.git/index`）。

## 打开仓库

```php
use Pitmaster\Pitmaster;

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

Pitmaster 支持三种仓库布局：

1. **常规仓库**：`.git` 是项目根目录中的一个目录。
2. **链接工作树**：`.git` 是一个包含 `gitdir: <path>` 的文件，指向 `.git/worktrees/<name>/`。
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 个十六进制字符）；使用 `Pitmaster::init($path, 'sha256')` 创建的仓库则使用 SHA-256（64 个十六进制字符）。对象有四种类型：blob、tree、commit 和 tag。

以下基于哈希的方法需要完整的十六进制哈希；不接受缩写哈希。

### 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),
};
```

对象会先在松散存储中搜索，然后在 pack 文件中搜索。pack 文件查找使用 `.idx` 扇出表进行 O(log n) 二分搜索。

### 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...', ...]
```

返回所有对象（松散对象和已打包对象）的十六进制哈希。

## 使用 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

树是目录列表。每个条目都包含模式、名称和哈希值。

```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)
    }
}
```

## 操作提交

提交会将树快照与其父项和元数据关联起来。

```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
}
```

## 操作标签

带注释的标签是包含目标、类型、名称、标记者和消息的对象。

```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
```

## 读取引用

### 当前 HEAD

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

解析 HEAD（跟随 `HEAD -> refs/heads/main -> commit hash` 等符号引用），并返回提交对象。

### 当前分支

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

### 列出分支和标签

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

### 所有引用

```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";
}
```

### 从特定提交查看日志

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

### 按文件路径筛选日志

```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'),
);
```
