gitrepo

package
v0.3.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gitrepo 通过调用 git 命令行读取仓库状态、diff 与历史。

用 CLI 而不是 go-git 这类库是刻意的:用户在命令行里真实生效的 git 行为 (配置、.gitattributes、.gitignore 规则、全局 gitignore、hooks)能原样复现, 不会出现「GUI 里看到的和命令行不一致」。代价是每次调用要起进程, 所以内容读取走长驻的 cat-file --batch(见 contents.go)。

Index

Constants

View Source
const (
	ScopeSystem = "system"
	ScopeGlobal = "global"
	ScopeLocal  = "local"
)

Git 的配置分三层,名字照抄 git 自己的叫法 —— 命令行里怎么写,这里就怎么叫:

  • system:机器上所有用户(/etc/gitconfig 之类)
  • global:当前用户的每一个仓库(~/.gitconfig)
  • local:只此一个仓库(.git/config)

三层同名时后面的覆盖前面的(local > global > system),这也是界面把它们 摆在一起的理由:单看一层说不清「这条到底生效没有」。

Variables

View Source
var (
	// ErrGhNotFound 表示系统未安装 gh 命令行工具。装上它的方式按平台说 ——
	// 一句「brew install gh」在 Windows 上等于没说,而那正是多数用户会
	// 撞上它的地方。
	ErrGhNotFound = errors.New(ghInstallHint())

	// ErrGhNotAuth 表示 gh 尚未完成 GitHub 登录认证或 Token 已失效。
	ErrGhNotAuth = errors.New("gh 未登录或认证已失效,请在终端运行 gh auth login")
)
View Source
var ErrBranchNotMerged = errors.New("branch not fully merged")

ErrBranchNotMerged 表示分支上有尚未合并进当前分支的提交。 由 DeleteBranch 在未指定 force 时返回,界面层据此弹出二次确认框。

View Source
var ErrHunkGone = errors.New("这个改动已经变了")

ErrHunkGone 表示点的那段改动在重新读出来的 patch 里已经不存在了 —— 用户点下去和 git 真正执行之间文件被改过(或前一次暂存让行号挪了位), 是正常竞态,不是 bug。界面翻译成一句人话 + 自动刷新。

View Source
var ErrNoBranch = errors.New("not on a branch")

ErrNoBranch 表示要推的那条分支在本地不存在。

界面在分离 HEAD 上把推送按钮画成灰的,但它还有菜单和命令栏两条路进来, 而这时候 branch 是**短哈希**(见 branchInfo)—— 直接拿它去推,git 报的是 "src refspec a1b2c3d does not match any",翻成人话是「这条引用已经不在了」, 和真正的原因(没有分支在手上)差着十万八千里。

View Source
var ErrNoChangesToStash = errors.New("no local changes to save")

ErrNoChangesToStash 表示没有可储藏的未提交改动。

View Source
var ErrNoRemote = errors.New("no remote to push to")

ErrNoRemote 表示这个仓库没有可以推的远程。

单独一个错误而不是让 git 去报:`git push` 在没有上游时给的是 "The current branch x has no upstream branch",那句话指向的是「设上游」, 而这里真正的问题是「一条远程都没有」—— 两件事的出路完全不同。

View Source
var ErrNotConflicted = errors.New("这个文件已经没有冲突了")

ErrNotConflicted 表示点的文件已经没有未解决的冲突了 —— 用户点下去和 git 真正执行之间,冲突在别处解决掉了(或者本来就不是冲突文件)。是正常竞态, 界面翻译成一句人话 + 自动刷新。

这个前置检查是必须的,不是保险:对没有冲突条目的路径,`git checkout --ours` 会退化成普通 checkout 静默执行(把 index 里的版本盖回工作区), `git rm -f` 会真的把文件删掉 —— 一个按旧状态点下来的按钮不该有这种后果。

View Source
var ErrNotRepo = errors.New("不是 git 仓库")

ErrNotRepo 表示这个目录(以及它的各级父目录)不是 git 仓库。

它和「仓库在读的时候出错了」不是一回事:那个重试有意义,这个只说明 文件夹选错了 —— 重试多少次结果都一样,该做的是换一个。界面上要分开 对待,所以这里得是个能认出来的错,而不是一句话。

Functions

func GetPRDiff

func GetPRDiff(ctx context.Context, repoDir string, prNumber int) ([]diff.FileDiff, error)

GetPRDiff 获取指定 PR 的 diff 并解析为 []diff.FileDiff。

func OldLines

func OldLines(f diff.FileDiff, newLines []string) []string

OldLines 由新侧内容和 hunk 反推出旧侧内容。

删除的行在界面上也要高亮,而高亮必须整份文件一起切(多行字符串、 块注释单看一行是判断不出来的)。旧文件的内容本来要再跑一次 `git show` 才能拿到,但这里能直接从 diff 里还原:hunk 里每个删除行的 原文都在,没被 hunk 覆盖的位置两侧内容相同 —— 拼回去就是旧文件。

newLines 是文件在新侧的内容(newLines[0] 是第 1 行)。 对不齐时返回 nil,调用方按「没有旧侧内容」处理即可。

func PostPRComment

func PostPRComment(ctx context.Context, repoDir string, prNumber int, body string) error

PostPRComment 为指定的 GitHub PR 发表评论。

func SplitLines

func SplitLines(s string) []string

SplitLines 把文件内容切成行,去掉末尾换行造成的那个空串。

func UnsetConfig added in v0.3.5

func UnsetConfig(ctx context.Context, dir, scope, key string) error

UnsetConfig 删掉一条配置(同名的多条一起删)。

键本来就不在不算错:界面上的「删除」记的是「这一行别留下」,而那条记录 可能已经被别处删掉了 —— 幂等才拦得住这种竞态。

func WriteConfig added in v0.3.5

func WriteConfig(ctx context.Context, dir, scope, key, value string) error

WriteConfig 写入一条配置:同名的被替换成这一个值,本来没有就新增。

用 --replace-all 而不是默认的「只改头一条」:界面上一个键只有一行,存回去 也该只剩一条 —— 否则改完再看,行数凭空变多(url.*.insteadof 这类天然多值 的键就会这样)。

键值前面钉一个 `--`:git 的选项解析在它之后收手,值是以「-」开头的 (`core.pager = -R` 这种)也不会被当成选项吃掉。

Types

type Change

type Change struct {
	Path     string
	OldPath  string // 重命名/复制时的原路径
	Status   Status
	Staged   bool
	Unstaged bool

	StagedStatus   Status // index vs HEAD 那一侧
	UnstagedStatus Status // 工作区 vs index 那一侧
}

Change 是 git status 报告的一个变更文件。

Staged / Unstaged 分别对应 index 相对 HEAD 的变更(XY 里的 X) 和工作区相对 index 的变更(Y)。两个都为真表示「暂存了一部分, 之后又改了一些」,这在做暂存/提交功能时是必须区分的状态。 StagedStatus / UnstagedStatus 是两侧各自的变更类型(空串 = 这一侧没变), Status 是合成出来的显示用类型。

type Commit

type Commit struct {
	Hash    string    // 完整哈希
	Short   string    // 短哈希,界面上显示这个
	Author  string    // 作者名
	Email   string    // 作者邮箱
	When    time.Time // 作者时间
	Subject string    // 提交信息的第一行
	Body    string    // 提交信息第一行之后的那些段;没有就是空串
	Refs    string    // 指向它的分支/标签,如 "HEAD -> main, origin/main"
	Parents []string  // 完整哈希的父提交;合并提交有两个以上,根提交没有
}

Commit 是历史里的一个提交。

type ConfigEntry added in v0.3.5

type ConfigEntry struct {
	Key   string
	Value string
	// Scope 是这一条所在的层级。除了上面三个,git 还会报 unknown ——
	// macOS 上 /Applications/Xcode.app/…/gitconfig 这类厂商塞进来的文件
	// 就走这一档。不认识的层级原样留着,由界面决定归到哪一栏。
	Scope string
	// File 是这条配置来自哪个文件(已经去掉 file: 前缀的绝对路径)。
	// 很老的 git 不报来源,可能是空的。
	File string
}

ConfigEntry 是一条配置。

func ReadConfig added in v0.3.5

func ReadConfig(ctx context.Context, dir string) ([]ConfigEntry, error)

ReadConfig 用一次 git 进程读回三层的全部配置。

不分三次问:这些条目在界面上是一张表,而分三次读就有三个时间点 —— 读的时候别人正在改配置,表里就会出现互相矛盾的条目。

需要 git ≥ 2.26(--show-scope)。缺了它这里的错误会原样浮到界面上, 不静默降级:一份读不全的配置比一句「你的 git 太老」危险得多。

type ConflictSides

type ConflictSides uint8

ConflictSides 说一个冲突文件在 index 里还剩哪几方的版本。

零值(两边都没有)理论上不出现 —— 两边都删的东西不会成为冲突;真撞上 (DD 那种纠缠在重命名里的形态)时哪边都 checkout 不出来,界面按「接受 删除」处理。

const (
	SideOurs   ConflictSides = 1 << iota // stage 2:我们这边有内容
	SideTheirs                           // stage 3:对方那边有内容
)

func (ConflictSides) Ours

func (s ConflictSides) Ours() bool

Ours / Theirs 说这一边在 index 里有没有内容。false = 这一边删了文件。

func (ConflictSides) Theirs

func (s ConflictSides) Theirs() bool

type Failure

type Failure struct {
	Title  string
	Hint   string
	Detail string
}

Failure 是一次 git 写操作失败整理成界面能用的说法。

和 internal/llm/failure.go 同一个形状:Title 说「出了什么事」,Hint 说 「能怎么办」,Detail 是 git 自己的原话 —— 前两句是我们替它翻译的, 翻译可能不准,原话留着,遇到怪问题才有得对。Title 为空 = 没有失败。

func Describe

func Describe(op Op, err error) Failure

Describe 把 git 的错误整理成人话。

git 的错误信息生来不是给 GUI 用户看的:一句 "error: pathspec 'x' did not match any file(s) known to git" 对命令行用户是清楚的,对点了下按钮 的人就是一坨英文。模式表翻常见的那些,认不出的也绝不把原文当标题 —— 原话永远留在 Detail 里可查。

func (Failure) Empty

func (f Failure) Empty() bool

Empty 表示这不是一次失败。

type File

type File struct {
	diff.FileDiff

	// Status 是这一段里该文件的变更类型(已暂存段用 index 侧的类型,
	// 未暂存段用工作区侧的类型)。
	Status Status

	// Section 说明这个 File 属于哪一段。两段各自的 diff 来自各自的基线,
	// 同一个路径可以同时出现在两段里(暂存之后又改了)。
	Section Section

	// Staged / Unstaged 是「这一段」的归属标志:SectionStaged 的条目
	// Staged=true、Unstaged=false,反之亦然。两个独立布尔是为了历史
	// 调用方读起来顺,不表示一个 File 能同时属于两段。
	Staged   bool
	Unstaged bool

	// Fingerprint 是文件内容的指纹,用于「已 review」标记:
	// 内容一变指纹就变,已读状态自动失效。
	Fingerprint string

	// TooLarge 表示文件超过读取上限,没有渲染内容。
	TooLarge bool

	// Stages 说(冲突文件)在 index 里还剩哪几方的版本:缺 stage 2 是我们
	// 这边删了它,缺 stage 3 是对方删了它。只在 Status == StatusConflict
	// 时有意义;别的文件是零值。
	//
	// 界面拿它把「哪边删了文件」提前说清 —— 删除-修改冲突里,一颗写着
	// 「用对方那边的」的按钮按下去是**把文件删掉**,不说清就是挖坑。
	Stages ConflictSides
}

File 是一个可以直接渲染的文件变更:解析好的 hunk + git status 的三态信息。

func FilesFromDiff

func FilesFromDiff(parsed []diff.FileDiff) []File

FilesFromDiff 把解析好的 patch 包成可渲染的 File 列表。

git status 那一路(Load)能拿到「未跟踪」「冲突」这类 patch 里没有的信息, 而按提交看 diff 时没有这些,状态只能从 patch 头推。

type Model

type Model struct {
	Repo     *Repo
	Branch   string
	Detached bool // HEAD 不在任何分支上(检出过标签/提交,或变基到一半)
	// Remotes 是远程名。RemoteURLs 是同一个远程配的 URL(提交详情卡拿它
	// 拼「在网页上看这个提交」的地址)—— 两条一起读,见 RemoteURLs。
	Remotes    []string
	RemoteURLs map[string]string
	Files      []File
	TotalAdd   int
	TotalDel   int

	// Pending 是仓库正卡在哪一步写操作中间(合并/变基/拣选/回退/am 撞了
	// 冲突停着)。零值 = 没卡住。
	Pending Pending

	// HasHead 表示仓库是否已有提交(HEAD 存在,可用于修改上次提交)。
	HasHead bool

	// Ahead 和 Behind 是当前分支相对配置上游的超前和落后提交数。
	Ahead  int
	Behind int

	// Upstream 是当前分支跟踪的远程分支名(如 origin/main)。若无上游则为空。
	Upstream string

	// Worktree 是工作区里的全部文件(已跟踪 + 未跟踪但未被忽略),
	// 供「编辑器」视图的文件栏列举整个仓库。读不到时为空 ——
	// 它只影响那一栏的完整性,不该把整次加载判失败。
	Worktree []WorktreeFile
}

Model 是仓库当前状态的完整快照,界面每次刷新重建一份。

type Op

type Op uint8

Op 是发起这次写操作的动作,用来挑「认不出具体错误时」的兜底说法。 零值是 OpNone(没有操作在进行),界面拿它当「写闸门空着」。

const (
	OpNone Op = iota
	OpStage
	OpUnstage
	OpCommit
	OpCheckout
	OpTag
	OpFetch
	OpPull
	OpPush
	OpMerge
	OpRebase
	OpCherryPick
	OpRevert
	OpReset
	OpBranch
	OpStash
	OpAmend
	OpConflict
	OpForcePush
	OpAm // 用户自己在终端里跑的补丁序列停在半路(git am)
	OpDiscard
	OpWrite     // 内置编辑器把文件写回工作区(不经过 git)
	OpGitConfig // 设置里的「Git 配置」页把改动写回配置文件
)

type PRItem

type PRItem struct {
	Number     int       `json:"number"`
	Title      string    `json:"title"`
	Author     string    `json:"author"`
	HeadBranch string    `json:"headBranch"`
	BaseBranch string    `json:"baseBranch"`
	UpdatedAt  time.Time `json:"updatedAt"`
	URL        string    `json:"url"`
}

PRItem 代表一个 GitHub Pull Request 的基本摘要信息。

func ListPRs

func ListPRs(ctx context.Context, repoDir string) ([]PRItem, error)

ListPRs 通过 gh CLI 查询指定仓库下的打开 PR 列表。

type Pending

type Pending struct {
	Kind PendingKind

	// Other 是「对方」那个提交:MERGE_HEAD / CHERRY_PICK_HEAD / REVERT_HEAD
	// 的哈希。合并里它是被并进来那条分支的尖端。
	Other string

	// Branch 是正在变基的分支(rebase-merge|apply/head-name 去掉 refs/heads/)。
	// 从分离态发起(`git rebase --onto` 那种)时是空的。
	//
	// 这段期间 git 的 HEAD 是分离的 —— 界面拿它来把分支芯片的话说对:
	// 「正在变基 main」而不是「分离 HEAD:a1b2c3d,先新建一条分支」,
	// 后者在变基中间是主动误导。
	Branch string

	// Onto 是变基目标(.../onto 的完整哈希)。UI 层拿它在引用表里找回
	// 人名(origin/main 之类),找不到就显示短哈希。
	Onto string

	// Step / Total 是变基进度(第 n / m 步)。读不到时是 0。
	Step  int
	Total int
}

Pending 是仓库当前卡住的那一步。

零值(Kind == PendingNone)就是没卡住 —— 绝大多数时候。

func (Pending) Active

func (p Pending) Active() bool

Active 表示有一步操作卡着。

type PendingKind

type PendingKind uint8

PendingKind 是卡住的那一步是什么。

const (
	PendingNone PendingKind = iota
	PendingMerge
	PendingRebase
	PendingAm // 用户自己在终端里跑的 git am 停在半路
	PendingCherryPick
	PendingRevert
)

type Ref

type Ref struct {
	Kind RefKind
	// Name 是短名,用来显示、以及和提交列表里 %D 装饰出来的名字对上:
	// main、origin/main、v1.0、stash@{0}。
	Name string
	// Full 是完整引用名(refs/heads/main、refs/tags/v1.0),**喂给 Log 的是它**。
	//
	// 不能拿短名去当 revision:仓库里同时有分支 v1 和标签 v1 时,git 的消歧
	// 顺序是 refs/v1 → refs/tags/v1 → refs/heads/v1,标签赢。用户点的是分支,
	// 看到的是标签的历史,而且不报任何错。
	Full     string
	Remote   string // 远程分支所属的 remote("origin"),别的种类留空
	Upstream string // 本地分支的上游("origin/main"),没有或非本地分支为空
	// Ahead / Behind 是本地分支相对上游的超前/落后提交数,UpstreamGone 是
	// 上游已经在远程上被删掉(%(upstream:track) 给的是 [gone])。
	//
	// 三个数都从同一次 for-each-ref 里带出来,不按分支各跑一次 rev-list:
	// 侧栏一列分支几十条,一次一条进程会把读引用变成几十倍慢。track 为空
	// 表示「同步」或「没有上游」—— 两者都不值得在侧栏占一行字。
	Ahead        int
	Behind       int
	UpstreamGone bool
	Hash         string // 短哈希
	Head         bool   // 当前检出的本地分支
	// Subject 只有储藏用得上:储藏名字("On main: ...")是全部信息,
	// 分支和标签的提交信息在提交列表里看。
	Subject string
	When    time.Time
}

Ref 是侧栏 refs 树里的一项。

func (Ref) Label

func (r Ref) Label() string

Label 是侧栏每行显示的文字:远程分支去掉 remote 前缀,分组那一层已经在 树里了,叶子上再来一遍就是 "origin/origin/main"。

type RefKind

type RefKind int

RefKind 是引用的种类,侧栏按它分组。

const (
	RefLocal  RefKind = iota // refs/heads/*
	RefRemote                // refs/remotes/*,不含 */HEAD
	RefTag                   // refs/tags/*
	RefStash                 // stash@{n}
)

type Repo

type Repo struct {
	Root string // 工作区根目录的绝对路径
	Name string // 目录名,用于显示
	// GitDir 是 .git 目录的绝对路径。判断「正卡在合并/变基中间」要看它
	// 底下的标记文件(pending.go),所以打开时顺手量好。
	//
	// 不能想当然写成 Root/.git:linked worktree 和子模块的 .git 是一个
	// **文件**(里面一行 gitdir: …),GIT_DIR 环境变量也常见 ——
	// `--absolute-git-dir` 正是为这些情况存在的。
	GitDir string
}

Repo 是一个已打开的 git 仓库。

func Open

func Open(ctx context.Context, dir string) (*Repo, error)

Open 在 dir 里定位仓库根并打开。dir 可以指向仓库的任意子目录。

func (*Repo) Abort

func (r *Repo) Abort(ctx context.Context, kind PendingKind) error

func (*Repo) AddIgnore

func (r *Repo) AddIgnore(ctx context.Context, p string) error

AddIgnore 把一条路径写进仓库根的 .gitignore,一行一条(`/<path>`)。

带上前导斜杠:不带的话 `build` 会连子目录里的同名文件一起忽略,用户点 的是「忽略这一个」。同一行已经在了就什么都不做 —— .gitignore 是用户 自己的文件,重复追加是最容易把别人的文件写脏的一种做法。

func (*Repo) BlobHash added in v0.3.16

func (r *Repo) BlobHash(ctx context.Context, rev, path string) (string, error)

BlobHash 返回某个版本里文件的 blob 哈希,不读内容。

二进制文件的指纹靠它(见 model.go 的 binaryFingerprint):没有 hunk 可读,只有对象哈希能说明「内容换没换」。

func (*Repo) Branch

func (r *Repo) Branch(ctx context.Context) (string, error)

Branch 返回当前分支名。处于 detached HEAD 时返回短哈希。

func (*Repo) BranchCommits

func (r *Repo) BranchCommits(ctx context.Context, base, target string, limit int) ([]Commit, error)

BranchCommits 读从 base 到 target 之间的提交列表。

func (*Repo) BranchDiff

func (r *Repo) BranchDiff(ctx context.Context, base, target string, tripleDot bool) ([]File, error)

BranchDiff 读两个分支之间的改动(产物为 []File)。 tripleDot 为 true 时用 base...target(自共同祖先分叉以来的改动,即 PR 模式); 为 false 时用 base..target(两个分支最新指针的直接差异)。

func (*Repo) CheckoutDetach

func (r *Repo) CheckoutDetach(ctx context.Context, hash string) error

CheckoutDetach 检出某个提交,HEAD 分离。

--detach 明写(和 CheckoutTag 一个道理):分离是主动要的,别让 git 先 念一段它自己的建议。工作区有挡道的改动时 git 会拒收(would be overwritten by checkout),原话 failure.go 翻成「有未提交的改动挡着」。

func (*Repo) CheckoutLocal

func (r *Repo) CheckoutLocal(ctx context.Context, name string) error

CheckoutLocal 检出本地分支。

传**短名**,不传 refs/heads/x:checkout 拿全名时会当成一个 commit-ish, HEAD 变成分离的(量过:`git checkout refs/heads/topic` 会打印 "Note: switching to 'refs/heads/topic'." 然后 detached)。只有名字确实是 分支名,git 才把 HEAD 附上去。

同名标签会让 git 打一句 warning 然后按 heads 优先消歧 —— checkout 和 rev-parse 不一样,它站在分支这一边,正是我们要的(Log 那边必须传全名, 见 Ref.Full 的说明)。

func (*Repo) CheckoutRemote

func (r *Repo) CheckoutRemote(ctx context.Context, local, remoteRef string) error

CheckoutRemote 从远程分支建一条本地分支并跟踪它。

remoteRef 要传全名(refs/remotes/origin/x):短名 origin/x 在仓库里同时 有同名分支时会指向别处,而这一步建出来的分支名和上游关系都靠它定。

本地重名不在这里兜:`git checkout -b x --track …` 遇到本地已有 x 会直接 报 "a branch named 'x' already exists",上层先查一遍本地引用,重名时 降级成检出本地那条(见 app 的 checkoutRef)。

func (*Repo) CheckoutTag

func (r *Repo) CheckoutTag(ctx context.Context, name string) error

CheckoutTag 检出标签。

--detach 是明写出来的:`git checkout refs/tags/v1` 本来也会分离 HEAD (全名不是分支名),但那样 git 会先念一段 detached HEAD 的建议 —— 分离是我们主动要的,就自己说清楚,别让它来提醒。

func (*Repo) CherryPick

func (r *Repo) CherryPick(ctx context.Context, hash string) error

CherryPick 把某个提交重放到当前分支上。

撞冲突时 git 会停在半路(CHERRY_PICK_HEAD + 未合并条目),返回 error; 界面重读之后自然会看到状态条和「继续/跳过/中止」—— 这条路和合并共用 同一套收尾。

func (*Repo) Commit

func (r *Repo) Commit(ctx context.Context, message string) error

Commit 把 index 里的内容提交成一次提交,信息从管道喂进去。

用 `-F -` 而不是 `-m`:消息里可以有换行、引号、以 - 开头的行,走参数会 被命令行解析咬;管道是字节原样的(git 不认的编码也不会有机会损坏)。git 会忽略纯空白消息、给末尾补换行,这些都交给它自己。

func (*Repo) CommitAmend

func (r *Repo) CommitAmend(ctx context.Context, message string) error

CommitAmend 修改上一次提交(git commit --amend -F -)。

func (*Repo) CommitDiff

func (r *Repo) CommitDiff(ctx context.Context, hash string) ([]File, error)

CommitDiff 读一个提交相对其父提交的改动,产物和 Load 一样是 []File, 所以 diff 视图、语法高亮、✨ 解释全都能直接复用。

合并提交按第一个父提交比较(--first-parent):跟第二个父比或者干脆 不给 diff 都没什么用,Fork 这类工具也是这么做的。

func (*Repo) ConflictContents

func (r *Repo) ConflictContents(ctx context.Context, path string) (base, ours, theirs, worktree []byte, err error)

ConflictContents returns the three useful texts for a conflicted path: the common ancestor (stage 1), our side (stage 2), and their side (stage 3). A missing stage means that side deleted the file. The worktree is returned as the editable result, including conflict markers when Git wrote them.

func (*Repo) Contents

func (r *Repo) Contents(path string) ([]byte, error)

Contents 读取工作区里某个文件的内容。

func (*Repo) ContentsAt

func (r *Repo) ContentsAt(ctx context.Context, rev, path string) ([]byte, error)

ContentsAt 读取某个版本里该文件的内容。rev 可以是 HEAD、某个 commit 或者 :0(index)。

func (*Repo) Continue

func (r *Repo) Continue(ctx context.Context, kind PendingKind) error

Continue / Abort / Skip 把卡住的那一步往前推、退回去、或者跳过。

指令按 kind 拼 —— 五种状态的操作名和 git 子命令同名,一张表就够。 界面只管点,判断「现在能不能点」是 UI 层的事(还有冲突文件时「继续」 会撞 git 的 "unmerged files",由 failure.go 翻成人话)。

func (*Repo) CreateBranch

func (r *Repo) CreateBranch(ctx context.Context, name, rev string, switchTo bool) error

CreateBranch 从 rev 建一条分支;rev 为空 = 当前 HEAD。

switchTo 为真时用 checkout -b 一步到位:先 branch 再 checkout 是两条 命令,中间那一瞬新分支已经存在但还没切过去 —— 期间用户再点一下别的 (比如检出另一条分支),收尾就没法把话圆回来。一步到位,要么都在要么 都不在。

重名和非法名字 git 的原话分别是 "a branch named 'x' already exists" 和 "not a valid branch name",failure.go 里都有 —— 不在这里预判。

func (*Repo) CreateTag

func (r *Repo) CreateTag(ctx context.Context, name, msg, rev string) error

CreateTag 在 rev 上打一个标签:msg 非空 = 附注标签(带作者、日期和说明 的对象),为空 = 轻量标签(一个指向提交的指针)。

不用 `-a -m ""` 造「空附注标签」:git 会直接拒收(no tag message?), 而 `-a` 不带 `-m` 会去拉编辑器 —— GUI 进程没有终端,那是一次静默的挂起。 rev 为空表示 HEAD。

func (*Repo) DeleteBranch

func (r *Repo) DeleteBranch(ctx context.Context, name string, force bool) error

DeleteBranch 删除本地分支。

force 为 false 时走 git branch -d;若分支上有未合并的提交,git 会返回 "is not fully merged",此时转化为 ErrBranchNotMerged 便于上层做二次确认。 force 为 true 时走 git branch -D 强制删除。 尝试删除当前正检出的分支时,git 会返回 "cannot delete branch" 错误。

func (*Repo) DeleteRemoteBranch

func (r *Repo) DeleteRemoteBranch(ctx context.Context, remote, branch string) error

DeleteRemoteBranch 删除指定远程上的分支(git push <remote> --delete <branch>)。

func (*Repo) Fetch

func (r *Repo) Fetch(ctx context.Context) error

Fetch 抓取所有远程的分支和标签,并清掉远端已经删掉的引用。

--all:一次把所有远程都抓下来,不用挑。 --prune:远端删掉的分支这里跟着消失。不 prune 的话侧栏会一直挂着一条早 就不存在的分支,点它还报「这条引用已经不在了」—— 明明是它的错,却要用户 自己反应过来是远端删了。

没有远程时 `git fetch --all` 静默退 0(什么都不做,也不报错),所以「能不 能抓」要由上层判(Model.Remotes),不能等这条命令失败 —— 那种「点了没反应」 比灰按钮难受得多。

func (*Repo) FileLog

func (r *Repo) FileLog(ctx context.Context, path string, limit int) ([]Commit, error)

FileLog 读某个文件的提交历史(新到旧)。

--follow 让它跟住重命名:文件改过名字之后,改名之前那些提交也在它的历史 里 —— 不然「这个文件的历史」会在改名那一刻凭空断掉,而那正是用户想看的 地方。(--follow 只认单个路径,这也是这里不收变参的原因。)

路径用 `--` 隔开:文件名可以是纯哈希的样子,不隔开会被当成 revision, 报一句和用户做的事毫不相干的错。

func (*Repo) HasHead

func (r *Repo) HasHead(ctx context.Context) bool

HasHead 检查仓库当前是否至少存在一次提交(HEAD 有效)。

func (*Repo) LastCommitMessage

func (r *Repo) LastCommitMessage(ctx context.Context) (string, error)

LastCommitMessage 返回最近一次提交的完整提交信息(修改上次提交时预填)。

func (*Repo) Load

func (r *Repo) Load(ctx context.Context) (*Model, error)

Load 读取工作区相对 HEAD 的全部变更,按「已暂存」「未暂存」分成两段。

两段的 diff 必须来自各自的基线:已暂存 = index vs HEAD (`git diff --cached <base>`),未暂存 = worktree vs index(`git diff`)。 这不只是为了显示 —— hunk 的 ID 是「路径 + 带行号的原文」的哈希,换一条 基线行号就全变;界面上展示的 hunk 和点击暂存时重新跑出来的 hunk 只有 基线相同才对得上号(见 write.go 里 StageHunk 的重新切片)。

Files 里「已暂存」是连续的前缀,之后才是未暂存 —— 界面的分组和段落键 都建立在这条性质上。

func (*Repo) Log

func (r *Repo) Log(ctx context.Context, rev string, limit, skip int) ([]Commit, error)

Log 读最近的提交。skip 用来翻页。

rev 是看哪条历史:分支名、标签名、任意 revision,空串表示当前的 HEAD。 侧栏点了哪条分支就传哪条 —— 不为空时不能退回 HEAD,那样点了分支看着没反应。

func (*Repo) LogAll added in v0.3.9

func (r *Repo) LogAll(ctx context.Context, limit, skip int) ([]Commit, error)

LogAll 读**所有分支**的提交:本地分支、远程跟踪分支、标签一起,按拓扑序排。

侧栏「所有分支」那一行用的就是它 —— 用户想看的是这个仓库总共在干什么, 不是某一条线的历史。储藏不在里面(git log --all 本来就不收 refs/stash), 那是储藏自己的视图。

空仓库直接返回空:--all 一条引用都没有时 git log 也是空输出,但顺带吐一 句 "does not have any commits yet" 到 stderr,按错误处理就错了。

func (*Repo) Merge

func (r *Repo) Merge(ctx context.Context, branch string) error

Merge 把 branch 合并进当前分支(git merge --no-edit <branch>)。

--no-edit 避免合并需要提交信息时去拉编辑器挂起进程。 撞冲突时命令退出码为非 0,产生 MERGE_HEAD,由上层 Pending 探测接管。

func (*Repo) NewLines

func (r *Repo) NewLines(path string, limit int) []string

NewLines 返回文件在「新的一侧」的内容按行切开的结果。

已删除的文件没有新内容,返回 nil。返回的切片不含末尾换行造成的空串, 所以 len() 就是文件的真实行数 —— 界面靠它算 diff 末尾那段 「未改动区间」有多长。

内容超过 limit 字节时返回 nil:与其把几 MB 的文件切行塞进界面, 不如干脆不高亮、也不算末尾区间。

func (*Repo) NewLinesAt

func (r *Repo) NewLinesAt(ctx context.Context, rev, path string, limit int) []string

NewLinesAt 和 NewLines 一样,但读的是指定版本(rev 语义同 ContentsAt, 比如 ":0" 是 index)。

已暂存段必须用它:那一段 diff 的「新侧」是 index 里的样子,不是工作区的 样子。半暂存的文件(暂存之后又改了)两者不一样 —— 读工作区会让展开的 未改动区间行号错位、语法高亮整段对不上,而且错得静默无声。

func (*Repo) Pull

func (r *Repo) Pull(ctx context.Context) error

Pull 把当前分支的上游拉下来合进当前分支。

--no-edit:合并需要一段提交信息时(真合并,不是快进),git 会去拉编辑器; GUI 进程没有终端,那是一次静默的挂起。给了它就自动用默认那句。

不加 --ff-only,也不指定 --rebase:用户配了 pull.rebase / pull.ff 就按他 的来,那是他的仓库和他的习惯。

func (*Repo) Push

func (r *Repo) Push(ctx context.Context, branch string) error

Push 推送 branch 这条分支。

已经有上游就直接推。没有上游时用 origin 建一条(`-u`):第一次把新分支推 上去是最常见的场景,让它失败、逼用户去终端里配一次上游,是把我们该做的判断 推给了用户。

没有 origin 就返回 ErrNoRemote,**不**从别的远程里挑一个:多个远程时哪一个 才是「那个远程」只有用户知道,猜错了就是把代码推到了不该去的地方。

func (*Repo) PushForce

func (r *Repo) PushForce(ctx context.Context, branch string) error

PushForce 强制推送当前分支(--force-with-lease)。

用 --force-with-lease 而不是裸 --force:只在远程分支还是本地上次抓取 时的样子才覆盖,别人新推上去的提交不会被静默吃掉。别人推过时 git 报错 并含 "stale info",failure.go 会翻成「远程上有你还没见过的提交」。

func (*Repo) PushTag

func (r *Repo) PushTag(ctx context.Context, remote, tag string) error

PushTag 把本地标签推送到指定远程。

func (*Repo) Rebase

func (r *Repo) Rebase(ctx context.Context, upstream string) error

Rebase 把当前分支变基到 upstream(git rebase <upstream>)。

变基改写提交历史。GIT_EDITOR=true 与 GIT_SEQUENCE_EDITOR=true 保证 不会挂在编辑器上;撞冲突时停在 rebase-merge/,由 Pending 状态条接管。

func (*Repo) Refs

func (r *Repo) Refs(ctx context.Context) ([]Ref, error)

Refs 读本地分支、远程分支、标签和储藏。

一次 for-each-ref 拿三个命名空间:分三次调用要多起两个进程,而且三次之间 仓库状态可能变,读出来的东西对不上(比如分支刚被删掉)。

func (*Repo) RemoteURLs added in v0.3.11

func (r *Repo) RemoteURLs(ctx context.Context, names []string) map[string]string

RemoteURLs 一次读出这些远程各自配的 URL。

用 `git remote -v` 而不是每个远程一条 get-url:一条命令拿全,且读出来 的 fetch/push 两行取 fetch 那一行(用户写的是哪个就认哪个)。

读不到就返回 nil、不报错 —— 「这个仓库没有远程」不是错误,是「没有网页 可看」,调用方拿空 map 就行,不该为它弹一句错。

func (*Repo) Remotes

func (r *Repo) Remotes(ctx context.Context) ([]string, error)

Remotes 返回配置的远程名。工具栏拿它决定 抓取/拉取/推送 能不能点 —— `git fetch --all` 在没有远程时是静默成功的,等错误等不到。

func (*Repo) RemoveFiles

func (r *Repo) RemoveFiles(ctx context.Context, paths ...string) error

RemoveFiles 把工作区里这些路径上的文件删掉,用来丢弃未跟踪的改动 —— git 还不认识它们,「恢复原状」就是从磁盘上拿走。

文件已经不在(用户刚在别处删了)不算失败:要的结果已经达成了。路径先 夹进仓库根、确认没跑出去(`..` 和绝对路径在这一步挡下 —— 拼接是纯字面 的,`a/../../x` 这种会在 Clean 之后被 Rel 认出来),因为这个函数真的会 删文件,是这一层里唯一不可逆的那把刀。仓库里指向外面的符号链接不受影响: os.Remove 摘的是链接本身,不是它指向的东西。

func (*Repo) RenameBranch

func (r *Repo) RenameBranch(ctx context.Context, old, new string) error

RenameBranch 重命名分支(git branch -m old new)。

无论 old 是否为当前检出的分支,git 均支持并会自动更新当前 HEAD 指向。

func (*Repo) ResetTo

func (r *Repo) ResetTo(ctx context.Context, hash string, mode ResetMode) error

ResetTo 把当前分支挪到某个提交上。

只动当前分支:git reset 本来就是这个语义,界面上的文案也跟着说 「重置 main 到 …」,别让它读成「把那个提交删掉」。

func (*Repo) ResolveManual

func (r *Repo) ResolveManual(ctx context.Context, path string, data []byte) error

ResolveManual writes an edited worktree result and stages it as the final resolution. It rechecks the unmerged index first so a stale editor cannot overwrite a conflict that another actor already resolved.

func (*Repo) ResolveOurs

func (r *Repo) ResolveOurs(ctx context.Context, path string) error

ResolveOurs 用「我们这边」的内容解决一个冲突文件。

「我们」是谁跟着卡住的操作变:合并/拣选/回退里是当前分支,变基里是变基 目标(git 的 --ours,和合并正好相反)。按钮文案那层负责把这件事说清, 这里只管 git 的事实。

func (*Repo) ResolveTheirs

func (r *Repo) ResolveTheirs(ctx context.Context, path string) error

ResolveTheirs 用「对方那边」的内容解决一个冲突文件:被并入的分支、正在 重放的提交、被回退提交的父版本、储藏里的那份……

func (*Repo) RestoreFile

func (r *Repo) RestoreFile(ctx context.Context, paths ...string) error

RestoreFile 丢弃工作区里这些路径上的未暂存改动,把它们恢复成 index 里的 样子(`git checkout -- <paths>`)。

路径是变参、和 StageFile 一个口径:未暂存的重命名要新旧两个路径一起给, 否则只把新路径恢复出来,旧路径仍然是「被删掉」的状态,看着像丢弃没生效。

只对 git 已经认识的文件有效 —— 未跟踪的文件走 RemoveFiles:checkout 对 它是 "pathspec did not match any file(s) known to git",翻译过来是一句 和用户做的事毫不相干的「引用不在了」。

func (*Repo) Revert

func (r *Repo) Revert(ctx context.Context, hash string) error

Revert 生成一条反向提交(把某个提交的改动抵消掉)。

--no-edit 明写:不带它 git 会开编辑器让用户确认那条「Revert "…"」消息, GUI 子进程没有终端(gitEnv 里的 GIT_EDITOR=true 是兜底,这里写出来更 直白)。合并提交不给 -m 会被 git 拒收(is a merge but no -m option was given),那句话 failure.go 已经翻好了。

func (*Repo) ShortHead

func (r *Repo) ShortHead(ctx context.Context) string

ShortHead 返回 HEAD 的短哈希(提交成功后的提示里报一串给用户认)。

func (*Repo) SizeAt added in v0.3.16

func (r *Repo) SizeAt(ctx context.Context, rev, path string) (int64, error)

SizeAt 返回某个版本里文件的字节数,不把内容读出来。

给「先看多大再决定读不读」用(图片预览):一张几十 MB 的图读完再发现 超限,内存已经花掉了。cat-file -s 只查对象头,代价和一次 stat 差不多。

func (*Repo) Skip

func (r *Repo) Skip(ctx context.Context, kind PendingKind) error

func (*Repo) StageAll

func (r *Repo) StageAll(ctx context.Context) error

StageAll 把工作区和 index 的差异全部放进 index(含未跟踪和删除)。

不给 pathspec:`git add -A` 一条命令覆盖全仓库。界面上的「全部暂存」不能 靠遍历文件列表逐条 add —— 那个列表有未跟踪文件的条数上限,会漏。

func (*Repo) StageFile

func (r *Repo) StageFile(ctx context.Context, paths ...string) error

func (*Repo) StageHunk

func (r *Repo) StageHunk(ctx context.Context, path, hunkID string) error

StageHunk 把未暂存段里的某一段改动放进 index。

func (*Repo) StageRange added in v0.3.4

func (r *Repo) StageRange(ctx context.Context, path, oldText, newText string, hr diff.HunkRange) error

StageRange 把未暂存段里 DiffView 划出来的这一段改动放进 index。

oldText 是 index 那份原文、newText 是工作区那份 —— 也就是界面展示「未暂存」 时用的同两份文本,补丁按它们生成,行区间是 DiffView 的 0 基末尾开区间。

func (*Repo) StashApply

func (r *Repo) StashApply(ctx context.Context, name string) error

StashApply 将指定储藏的内容应用到当前工作区,不从储藏列表删除该条目(git stash apply <name>)。

func (*Repo) StashDiff

func (r *Repo) StashDiff(ctx context.Context, name string) ([]File, error)

StashDiff 读一个储藏的内容,产物和 CommitDiff 一样是 []File。

名字传的是 stash@{n},不是哈希 —— 储藏的改动不在它那个提交本身里 (那个提交的第一个父是当时的 HEAD,直接 diff 出来的东西是错的), git stash show 才负责把 WIP 那次提交和它的父正确地摆在一起比。

func (*Repo) StashDrop

func (r *Repo) StashDrop(ctx context.Context, name string) error

StashDrop 从储藏列表中删除指定条目(git stash drop <name>)。

func (*Repo) StashPop

func (r *Repo) StashPop(ctx context.Context, name string) error

StashPop 将指定储藏的内容应用到当前工作区,并在成功后将其从储藏列表丢弃(git stash pop <name>)。

func (*Repo) StashPush

func (r *Repo) StashPush(ctx context.Context, message string, includeUntracked bool) error

StashPush 将当前工作区与暂存区的改动存入储藏(git stash push [-u] [-m <message>])。

func (*Repo) StateFingerprint

func (r *Repo) StateFingerprint(ctx context.Context) string

StateFingerprint 返回一个能代表仓库当前 git 状态的字符串。

三条来源,覆盖界面关心的每一块:

  • statusRaw(--porcelain=v2 --branch -z):工作区 / 已暂存 / 未跟踪 / 当前分支 / 上游超前落后 / 分离 HEAD / 冲突 —— 正是「改动」列表 和 ahead-behind 徽标显示的那份状态;
  • git show-ref --head:所有分支、远端、标签、储藏以及 HEAD —— 侧栏的引用树和「历史」看的就是这一份(仓库里进新提交、建分支、 fetch 出新远端都会让它变);
  • pending 标记文件的存在性:MERGE_HEAD、rebase-merge 这些 —— 「正卡在合并/变基中间」那条状态条要跟得上。

单条命令失败就拼进一条 e:<error> 而不是中断:失败说明仓库状态 短时间内读不出来,界面上保留旧内容不刷新,总比反复弹错强。

func (*Repo) Status

func (r *Repo) Status(ctx context.Context) ([]Change, error)

func (*Repo) UnstageAll

func (r *Repo) UnstageAll(ctx context.Context) error

UnstageAll 把 index 里的全部改动撤出(重置暂存区到 HEAD,不影响工作区)。

func (*Repo) UnstageFile

func (r *Repo) UnstageFile(ctx context.Context, paths ...string) error

UnstageFile 把整个文件撤出 index。

用 `git reset` 而不是新版的 `git restore --staged`:语义一样(包括 「已暂存的新增」撤销后回到未跟踪),但 reset 从 git 1.x 就在,不挑版本。 变参的理由和 StageFile 一样:撤销一个已暂存的重命名,得把新旧两个路径 都从 index 里退回去,只退一个会留下半截删除。

func (*Repo) UnstageHunk

func (r *Repo) UnstageHunk(ctx context.Context, path, hunkID string) error

UnstageHunk 把已暂存段里的某一段改动撤出 index。

调用方必须保证目标不是「已暂存的新增文件」:反转 `@@ -0,0 +1,N @@` 会在 index 里留下一个空文件,而不是把条目删掉(和整文件 reset 不同)。 界面那边由 hunkStageable 挡着,只给整文件操作。

func (*Repo) UnstageRange added in v0.3.4

func (r *Repo) UnstageRange(ctx context.Context, path, oldText, newText string, hr diff.HunkRange) error

UnstageRange 把已暂存段里 DiffView 划出来的这一段改动撤出 index。

方向反过来:oldText 是 HEAD 那份(已暂存段的基线)、newText 是 index 那份; 撤销就是把「HEAD → index」的这段改动反向打到 index 上,index 回到 HEAD 的 样子,工作区一个字节都不动。

和 UnstageHunk 不同,这里不需要调用方替它挡「已暂存的新增文件」:新增在 补丁里是 /dev/null 旧侧,反向 apply 掉的是 index 里那条记录本身,不会留下 一个空文件。

func (*Repo) Upstream

func (r *Repo) Upstream(ctx context.Context, branch string) string

Upstream 返回 branch 的上游引用名,没有上游时返回空串。

func (*Repo) UpstreamCounts

func (r *Repo) UpstreamCounts(ctx context.Context) (ahead, behind int, err error)

UpstreamCounts 查询当前分支相对其配置的上游分支的超前(ahead)与落后(behind)提交数。 若无上游分支、处于分离 HEAD 或无提交,返回 0, 0, nil。

func (*Repo) WorktreeFiles added in v0.3.6

func (r *Repo) WorktreeFiles(ctx context.Context) ([]WorktreeFile, error)

WorktreeFiles 列出工作区里的全部文件:已跟踪的,加上未跟踪但没有被 .gitignore 忽略的。

这是给「编辑器」视图的文件栏用的:它要的是「仓库里有哪些代码」,而不是 「哪些代码改了」—— 后者是 git status 的活。忽略文件不在其中,空的目录 也不会出现(git 不追踪目录),与「未跟踪」在状态里的含义一致。

-z 走 NUL 分隔,core.quotePath=false 关掉引号转义:带空格、带中文的名字 原样出来,不用再解一层转义。

func (*Repo) WorktreeHash added in v0.3.16

func (r *Repo) WorktreeHash(ctx context.Context, path string) (string, error)

WorktreeHash 返回工作区文件的 blob 哈希(git 的哈希算法)。

走 git hash-object 而不是在这里读文件:它按流算,几百 MB 的文件不会 整份进内存;路径里有什么字符也不用担心,-- 之后一律当路径。

func (*Repo) WriteContents

func (r *Repo) WriteContents(path string, data []byte) error

WriteContents replaces a worktree file without touching the index. The embedded resolver stages it separately after the write has succeeded.

已存在的文件保留它原来的权限位:内置编辑器保存一个 0755 的脚本时,不该 顺手把可执行位抹掉 —— 那是一次没人要求的改动,而且 git status 也不会报。 新文件才按 0644 建。

type ResetMode

type ResetMode uint8

ResetMode 是重置的三档 —— 区别只在「改动丢到哪一层」。

const (
	// ResetSoft:只挪分支的指向,改动全留在暂存区。
	ResetSoft ResetMode = iota
	// ResetMixed:挪指向 + 清暂存区,改动留在工作区(git 的默认档)。
	ResetMixed
	// ResetHard:暂存区和工作区一起回到那个提交,没提交的改动**丢掉**。
	ResetHard
)

type Section

type Section uint8

Section 说明一个 File 属于文件列表的哪一段。

历史提交、储藏里的 diff 两段都不是(SectionNone)—— 那边的 key 和语义 保持和分段之前完全一样。

const (
	SectionNone     Section = iota
	SectionStaged           // index vs HEAD:已暂存
	SectionUnstaged         // worktree vs index:未暂存(含未跟踪、冲突)
)

type Status

type Status string

Status 是文件相对 HEAD 的变更类型。

const (
	StatusModified  Status = "modified"
	StatusAdded     Status = "added"
	StatusDeleted   Status = "deleted"
	StatusRenamed   Status = "renamed"
	StatusCopied    Status = "copied"
	StatusUntracked Status = "untracked"
	StatusConflict  Status = "conflict"
)

func (Status) Label

func (s Status) Label() string

Label 返回状态的中文说明,用于 tooltip。

func (Status) Letter

func (s Status) Letter() byte

Letter 返回文件树里显示的单字母状态标记。

type WorktreeFile added in v0.3.6

type WorktreeFile struct {
	Path string
}

WorktreeFile 是工作区里的一个路径。目前只带路径 —— 编辑器那一栏要的是 「这个仓库有哪些代码」,改动与否由调用方拿状态自己合。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL