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

91 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
// 创建文件夹
err = os.MkdirAll(filepath.Join(directory, "new_folder"), 0755)
CheckIfError(err)
// 创建文件由于git不允许创建空的文件夹这里创建.keep文件来保证文件夹正常创建
filePath := filepath.Join(directory, "new_folder", ".keep")
err = os.WriteFile(filePath, []byte(""), 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)
}