go-git-example/_example/operate/read/folder/main.go

81 lines
1.8 KiB
Go

package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/go-git/go-git/v5"
. "github.com/go-git/go-git/v5/_examples"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
)
func main() {
CheckArgs("<url>", "<github_username>", "<github_password>", "<directory_path>")
url, username, password, find_directory := os.Args[1], os.Args[2], os.Args[3], os.Args[4]
directory := "./local-repo"
// 克隆裸仓库到本地
Info("git clone %s %s", url, directory)
_, err := git.PlainClone(directory, false, &git.CloneOptions{
Auth: &http.BasicAuth{
Username: username,
Password: password,
},
URL: url,
Progress: os.Stdout,
})
CheckIfError(err)
// 打开本地仓库
r, err := git.PlainOpen(directory)
// 获取 HEAD 引用
ref, err := r.Reference(plumbing.HEAD, true)
CheckIfError(err)
// 解析 HEAD 引用到提交对象
commit, err := r.CommitObject(ref.Hash())
CheckIfError(err)
// 获取提交对象的树对象
tree, err := commit.Tree()
CheckIfError(err)
// 遍历树对象中的文件
tree.Files().ForEach(func(f *object.File) error {
if strings.HasPrefix(f.Name, find_directory+"/") {
fmt.Printf("Found file: %s\n", f.Name)
// 获取 blob 对象
blob, err := r.BlobObject(f.Blob.Hash)
CheckIfError(err)
// 获取 blob 的内容
blobReader, err := blob.Reader()
CheckIfError(err)
defer blobReader.Close()
// 读取 blob 的内容
fileContent, err := ioutil.ReadAll(blobReader)
CheckIfError(err)
// 打印文件内容
fmt.Printf("%s:\n%s\n", f.Name, fileContent)
}
return nil
})
// 删除本地仓库
Info("Removing the local repository")
err = os.RemoveAll(directory)
CheckIfError(err)
}