golang里实现获取当前git仓库、分支的方法
需要写一个获取当前git仓库的地址和分支的方法,这里想到的最快的方法就是通过命令行的形式,关键代码如下:
package git import ( "fmt" "os/exec" "strings" ) // ExecShell ... func ExecShell(command string, arg ...string) (out string, err error) { var Stdout []byte cmd := exec.Command(command, arg...) Stdout, err = cmd.CombinedOutput() out = string(Stdout) return } // Repo ... func Repo() (repo string, err error) { var ( out string ) if out, err = ExecShell("/bin/sh", "-c", "git remote -v"); err != nil { return } if repo = out[strings.Index(out, ":")+1 : strings.Index(out, ".git")]; repo == "" { err = fmt.Errorf("not found, %s", out) return } return } // Branch ... func Branch() (branch string, err error) { var ( out string ) if out, err = ExecShell("/bin/sh", "-c", "git branch"); err != nil { return } list := strings.Split(out, "\n") for _, v := range list { if strings.HasPrefix(v, "*") { branch = v[strings.Index(v, "*")+2:] return } } err = fmt.Errorf("not found, %s", out) return }
调用方式如下:
func main() { repo, err := git.Repo() if err != nil { return } fmt.Println("仓库:" + repo) branch, err := git.Branch() if err != nil { return } fmt.Println("分支:" + branch) }