اگر میخواهید Git را در یک سرویس نوشتهشده با Golang ادغام کنید، یک پیادهسازی کامل به زبان Go نیز وجود دارد. این پیادهسازی هیچ وابستگی بومی (native) ندارد و بنابراین در معرض خطاهای مدیریت حافظه دستی نیست. همچنین برای ابزارهای استاندارد تحلیل عملکرد Golang مانند پروفایلر CPU، پروفایلر حافظه، و race detector شفاف است.
go-git بر قابلیت توسعه (extensibility) و سازگاری تمرکز دارد و از بیشتر APIهای سطح پایین (plumbing) پشتیبانی میکند، که مستندات آن در https://github.com/go-git/go-git/blob/master/COMPATIBILITY.md موجود است.
در اینجا یک مثال ساده از استفاده از APIهای Go آمده است:
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 دارای چند ویژگی پیشرفته قابل توجه است، یکی از آنها سیستم ذخیرهسازی قابل افزونه (pluggable storage) است، مشابه backendهای Libgit2. پیادهسازی پیشفرض، ذخیرهسازی در حافظه (in-memory) است که بسیار سریع است.
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 را فراهم میکند.
ویژگی دیگر، انتزاع انعطافپذیر سیستم فایل (flexible filesystem abstraction) است. با استفاده از 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، مستندات API در https://pkg.go.dev/github.com/go-git/go-git/v5 و مجموعهای از مثالهای کاربردی در https://github.com/go-git/go-git/tree/master/_examples در دسترس هستند.