GUI 程序(-H windowsgui)起 console 子进程时若未设 HideWindow, Windows 会为其分配新控制台。refreshGit 一次连跑 3 个 git 进程 = 3 个闪窗(主因),另有 taskkill 和 go vet 两处。 统一 procAttr() 模式(Windows 返回 HideWindow:true,其他平台 nil): - internal/git: 新建 procattr_windows/other.go,run/runOut 挂上 - internal/task: killTree(taskkill)挂上 - internal/app: 新建 procattr_windows/other.go,go vet 挂上
270 lines
7.2 KiB
Go
270 lines
7.2 KiB
Go
// Package git 用命令行读仓库状态:不引第三方库,也不碰 .git 内部结构。
|
||
package git
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"fmt"
|
||
"os/exec"
|
||
"path/filepath"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// Info 是一个工作区的 git 快照。
|
||
type Info struct {
|
||
// OK 表示这是一个 git 仓库(且装了 git)。
|
||
OK bool
|
||
// Branch 是当前分支名,游离头时是短哈希。
|
||
Branch string
|
||
// Files 是「绝对路径 → 状态码」,状态码是 M/A/D/R/?? /U 之一。
|
||
Files map[string]string
|
||
// Dirty 是改动文件数。
|
||
Dirty int
|
||
}
|
||
|
||
// Available 判断目录里能不能用 git(装了 git 且是仓库)。
|
||
func Available(root string) bool {
|
||
if root == "" {
|
||
return false
|
||
}
|
||
if _, err := exec.LookPath("git"); err != nil {
|
||
return false
|
||
}
|
||
out, err := run(root, "rev-parse", "--is-inside-work-tree")
|
||
return err == nil && strings.TrimSpace(out) == "true"
|
||
}
|
||
|
||
// Load 读一次仓库状态。
|
||
func Load(root string) Info {
|
||
info := Info{Files: map[string]string{}}
|
||
if !Available(root) {
|
||
return info
|
||
}
|
||
info.OK = true
|
||
if out, err := run(root, "rev-parse", "--abbrev-ref", "HEAD"); err == nil {
|
||
info.Branch = strings.TrimSpace(out)
|
||
}
|
||
out, err := run(root, "status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames")
|
||
if err != nil {
|
||
return info
|
||
}
|
||
for _, e := range parsePorcelain(out) {
|
||
abs := filepath.Join(root, filepath.FromSlash(e.path))
|
||
info.Files[abs] = e.code
|
||
}
|
||
info.Dirty = len(info.Files)
|
||
return info
|
||
}
|
||
|
||
type entry struct {
|
||
code string
|
||
path string
|
||
}
|
||
|
||
// parsePorcelain 解析 porcelain v1 -z 的输出。
|
||
func parsePorcelain(out string) []entry {
|
||
var res []entry
|
||
for _, rec := range strings.Split(out, "\x00") {
|
||
// "XY path":前两个字符是状态,第三个是空格
|
||
if len(rec) < 4 {
|
||
continue
|
||
}
|
||
code := codeFor(rec[0], rec[1])
|
||
if code == "" {
|
||
continue
|
||
}
|
||
res = append(res, entry{code: code, path: rec[3:]})
|
||
}
|
||
return res
|
||
}
|
||
|
||
// codeFor 把 XY 两位状态压成一个给人看的码。
|
||
func codeFor(x, y byte) string {
|
||
switch {
|
||
case x == '?' || y == '?':
|
||
return "??"
|
||
case x == 'U' || y == 'U':
|
||
return "U"
|
||
case x == 'D' || y == 'D':
|
||
return "D"
|
||
case x == 'R':
|
||
return "R"
|
||
case x == 'A':
|
||
return "A"
|
||
case x == 'M' || y == 'M':
|
||
return "M"
|
||
case x == 'T' || y == 'T':
|
||
return "M"
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// run 在 root 下执行 git 命令并返回标准输出。
|
||
func run(root string, args ...string) (string, error) {
|
||
full := append([]string{"-C", root}, args...)
|
||
cmd := exec.Command("git", full...)
|
||
cmd.SysProcAttr = procAttr()
|
||
// 只读查询不要抢 .git/index.lock,免得和外部 git 命令打架。
|
||
cmd.Env = append(cmd.Environ(), "GIT_OPTIONAL_LOCKS=0")
|
||
var buf bytes.Buffer
|
||
cmd.Stdout = &buf
|
||
if err := cmd.Run(); err != nil {
|
||
return "", err
|
||
}
|
||
return buf.String(), nil
|
||
}
|
||
|
||
// gitTimeout 是一次 git 命令的上限。pull/push 走网络,留足慢网的时间;
|
||
// 本地命令远用不了这么多。
|
||
const gitTimeout = 2 * time.Minute
|
||
|
||
// runOut 跑 git 并返回**合并后**的输出:git 的进度与报错大多走 stderr,
|
||
// pull/push 的结果要原样给用户看,得分开接。
|
||
func runOut(root string, args ...string) (string, error) {
|
||
ctx, cancel := context.WithTimeout(context.Background(), gitTimeout)
|
||
defer cancel()
|
||
full := append([]string{"-C", root}, args...)
|
||
cmd := exec.CommandContext(ctx, "git", full...)
|
||
cmd.SysProcAttr = procAttr()
|
||
var buf bytes.Buffer
|
||
cmd.Stdout = &buf
|
||
cmd.Stderr = &buf
|
||
err := cmd.Run()
|
||
return strings.TrimSpace(buf.String()), err
|
||
}
|
||
|
||
// Stage 把所有改动加入暂存区。
|
||
func Stage(root string) error {
|
||
_, err := run(root, "add", "-A")
|
||
return err
|
||
}
|
||
|
||
// StagePaths 只把指定文件加入暂存区(选择性暂存)。
|
||
// paths 是仓库相对路径(正斜杠);删除的文件 add 同样会记录删除。
|
||
// 一个都不选时直接成功——调用方应当在上游拦住「空提交」。
|
||
func StagePaths(root string, paths []string) error {
|
||
if len(paths) == 0 {
|
||
return nil
|
||
}
|
||
args := append([]string{"add", "--"}, paths...)
|
||
_, err := run(root, args...)
|
||
return err
|
||
}
|
||
|
||
// Commit 提交暂存区的内容。
|
||
func Commit(root, message string) error {
|
||
_, err := run(root, "commit", "-m", message)
|
||
return err
|
||
}
|
||
|
||
// Pull 拉取并合并当前分支。
|
||
//
|
||
// 用 --ff-only:分叉时直接失败并把 git 的提示原样带回来,
|
||
// 绝不偷偷做 merge commit——IDE 里一键操作宁可保守。
|
||
func Pull(root string) (string, error) {
|
||
return runOut(root, "pull", "--ff-only")
|
||
}
|
||
|
||
// Push 推送当前分支到上游;还没有上游时自动补一次 -u origin <分支>,
|
||
// 这是新仓库第一次推送的固定动作,替用户省一步。
|
||
func Push(root string) (string, error) {
|
||
out, err := runOut(root, "push")
|
||
if err == nil || !strings.Contains(out, "no upstream") {
|
||
return out, err
|
||
}
|
||
branch, berr := run(root, "rev-parse", "--abbrev-ref", "HEAD")
|
||
if berr != nil {
|
||
return out, err
|
||
}
|
||
return runOut(root, "push", "--set-upstream", "origin", strings.TrimSpace(branch))
|
||
}
|
||
|
||
// ShowFile 返回某文件在 HEAD 里的内容。
|
||
//
|
||
// 新文件(还没提交过)会报错,调用方把 old 当成空文本处理即可。
|
||
func ShowFile(root, path string) (string, error) {
|
||
rel, err := filepath.Rel(root, path)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return run(root, "show", "HEAD:"+filepath.ToSlash(rel))
|
||
}
|
||
|
||
// Numstat 一次拿到所有改动文件的行数增减,键是仓库相对路径(正斜杠)。
|
||
//
|
||
// 每个文件各起一次 git 进程太慢,状态栏每帧都要看这个数,
|
||
// 所以统一在后台刷一次存起来查。
|
||
func Numstat(root string) map[string][2]int {
|
||
out, err := run(root, "diff", "--numstat")
|
||
if err != nil {
|
||
return nil
|
||
}
|
||
m := map[string][2]int{}
|
||
for _, line := range strings.Split(out, "\n") {
|
||
f := strings.Fields(line)
|
||
if len(f) < 3 {
|
||
continue
|
||
}
|
||
var add, del int
|
||
// 二进制文件给的是 "-",算 0。
|
||
fmt.Sscanf(f[0], "%d", &add)
|
||
fmt.Sscanf(f[1], "%d", &del)
|
||
m[f[2]] = [2]int{add, del}
|
||
}
|
||
return m
|
||
}
|
||
|
||
// LogEntry 是一条提交记录(名字避开已有的 Commit 函数)。
|
||
type LogEntry struct {
|
||
Hash string
|
||
Author string
|
||
When string // 相对时间,如 "3 hours ago"
|
||
Subject string
|
||
}
|
||
|
||
// Log 取某个文件或目录的提交历史,limit 为 0 时用 50。
|
||
//
|
||
// 用 \x1f 分隔字段:提交标题里什么字符都可能有,只有控制符不会出现在里头。
|
||
func Log(root, path string, limit int) ([]LogEntry, error) {
|
||
if limit <= 0 {
|
||
limit = 50
|
||
}
|
||
args := []string{
|
||
"log",
|
||
fmt.Sprintf("--max-count=%d", limit),
|
||
"--pretty=format:%h\x1f%an\x1f%ar\x1f%s",
|
||
}
|
||
if path != "" {
|
||
rel, err := filepath.Rel(root, path)
|
||
if err == nil {
|
||
args = append(args, "--", filepath.ToSlash(rel))
|
||
}
|
||
}
|
||
out, err := run(root, args...)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var commits []LogEntry
|
||
for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
|
||
if line == "" {
|
||
continue
|
||
}
|
||
f := strings.SplitN(line, "\x1f", 4)
|
||
if len(f) < 4 {
|
||
continue
|
||
}
|
||
commits = append(commits, LogEntry{Hash: f[0], Author: f[1], When: f[2], Subject: f[3]})
|
||
}
|
||
return commits, nil
|
||
}
|
||
|
||
// ShowAt 取某文件在指定版本里的内容(rev 可以是 <hash> 或 <hash>^)。
|
||
func ShowAt(root, rev, path string) (string, error) {
|
||
rel, err := filepath.Rel(root, path)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return run(root, "show", rev+":"+filepath.ToSlash(rel))
|
||
}
|