-
1. 入门
-
2. Git 基础
-
3. Git 分支
-
4. Git 服务器
- 4.1 协议
- 4.2 在服务器上安装 Git
- 4.3 生成 SSH 公钥
- 4.4 设置服务器
- 4.5 Git Daemon
- 4.6 Smart HTTP
- 4.7 GitWeb
- 4.8 GitLab
- 4.9 第三方托管选项
- 4.10 总结
-
5. 分布式 Git
-
A1. 附录 A:其他环境中的 Git
- A1.1 图形界面
- A1.2 Visual Studio 中的 Git
- A1.3 Visual Studio Code 中的 Git
- A1.4 IntelliJ / PyCharm / WebStorm / PhpStorm / RubyMine 中的 Git
- A1.5 Sublime Text 中的 Git
- A1.6 Bash 中的 Git
- A1.7 Zsh 中的 Git
- A1.8 PowerShell 中的 Git
- A1.9 总结
-
A2. 附录 B:在您的应用程序中嵌入 Git
-
A3. 附录 C:Git 命令
A2.4 附录 B:在您的应用程序中嵌入 Git - go-git
go-git
如果您想将 Git 集成到用 Golang 编写的服务中,也有一个纯 Go 库实现。此实现没有任何原生依赖项,因此不易出现手动内存管理错误。它对于标准的 Golang 性能分析工具(如 CPU、内存分析器、竞争检测器等)也是透明的。
go-git 专注于可扩展性、兼容性,并支持大多数底层 API,文档位于https://github.com/go-git/go-git/blob/master/COMPATIBILITY.md。
这是一个使用 Go API 的基本示例
import "github.com/go-git/go-git/v5"
r, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{
URL: "https://github.com/go-git/go-git",
Progress: os.Stdout,
})
一旦有了 Repository
实例,您就可以访问信息并对其执行修改
// retrieves the branch pointed by HEAD
ref, err := r.Head()
// get the commit object, pointed by ref
commit, err := r.CommitObject(ref.Hash())
// retrieves the commit history
history, err := commit.History()
// iterates over the commits and print each
for _, c := range history {
fmt.Println(c)
}
高级功能
go-git 有一些值得注意的高级功能,其中之一是可插拔的存储系统,类似于 Libgit2 后端。默认实现是内存存储,速度非常快。
r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
URL: "https://github.com/go-git/go-git",
})
可插拔存储提供了许多有趣的选项。例如,https://github.com/go-git/go-git/tree/master/_examples/storage 允许您将引用、对象和配置存储在 Aerospike 数据库中。
另一个功能是灵活的文件系统抽象。使用 https://pkg.go.dev/github.com/go-git/go-billy/v5?tab=doc#Filesystem 可以很容易地以不同的方式存储所有文件,例如,将它们全部打包到磁盘上的单个存档中,或者将它们全部保存在内存中。
另一个高级用例包括一个微调的 HTTP 客户端,例如在 https://github.com/go-git/go-git/blob/master/_examples/custom_http/main.go 中找到的。
customClient := &http.Client{
Transport: &http.Transport{ // accept any certificate (might be useful for testing)
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Timeout: 15 * time.Second, // 15 second timeout
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse // don't follow redirect
},
}
// Override http(s) default protocol to use our custom client
client.InstallProtocol("https", githttp.NewClient(customClient))
// Clone repository using the new client if the protocol is https://
r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: url})
进一步阅读
go-git 功能的完整处理超出了本书的范围。如果您想了解有关 go-git 的更多信息,请访问 https://pkg.go.dev/github.com/go-git/go-git/v5 查看 API 文档,并在 https://github.com/go-git/go-git/tree/master/_examples 找到一组使用示例。