go-git-example/_example/operate/create/main.go

86 lines
2.0 KiB
Go

package main
import (
"os"
"path/filepath"
"time"
"github.com/go-git/go-git/v5"
. "github.com/go-git/go-git/v5/_examples"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
)
// Basic example of how to commit changes to the current branch to an existing
// repository.
func main() {
CheckArgs("<url>", "<github_username>", "<github_password>")
url, username, password := os.Args[1], os.Args[2], os.Args[3]
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)
// 打开本地仓库
repo, err := git.PlainOpen(directory)
CheckIfError(err)
// 获取工作树
worktree, err := repo.Worktree()
CheckIfError(err)
// 创建或更新文件
file := filepath.Join(worktree.Filesystem.Root(), "example-git-file")
err = os.WriteFile(file, []byte("Hello World!"), 0644)
CheckIfError(err)
// 添加文件到暂存区
Info("Adding the new file to the staging area")
_, err = worktree.Add(".")
CheckIfError(err)
// 提交更改
Info("Committing the changes")
_, err = worktree.Commit("example go-git create file", &git.CommitOptions{
Author: &object.Signature{
Name: "John Doe",
Email: "john@doe.org",
When: time.Now(),
},
})
CheckIfError(err)
// 获取远程配置
remoteConfig, err := repo.Remote("origin")
CheckIfError(err)
// 推送到裸仓库
Info("Pushing the changes to the bare repository")
err = remoteConfig.Push(&git.PushOptions{
RefSpecs: []config.RefSpec{
config.RefSpec("refs/heads/master:refs/heads/master"),
},
Auth: &http.BasicAuth{
Username: username,
Password: password,
},
})
CheckIfError(err)
// 删除本地仓库
Info("Removing the local repository")
err = os.RemoveAll(directory)
CheckIfError(err)
}