2 Star 7 Fork 10

王布衣/engine

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gitcmd.go 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
package utils
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"syscall"
)
// Config for git command
type Config struct {
Bin string // default "git"
}
// Client of git command
type Client interface {
CanExec() error
Exec(string, ...string) (string, error)
InsideWorkTree() error
}
type clientImpl struct {
config *Config
}
// NewGit git command client
func NewGit(config *Config) Client {
bin := "git"
if config != nil {
if config.Bin != "" {
bin = config.Bin
}
}
return &clientImpl{
config: &Config{
Bin: bin,
},
}
}
// CanExec check whether the git command is executable
func (client *clientImpl) CanExec() error {
_, err := exec.LookPath(client.config.Bin)
if err != nil {
return fmt.Errorf("\"%s\" does not exists", client.config.Bin)
}
return nil
}
// Exec executes the git command
func (client *clientImpl) Exec(subcmd string, args ...string) (string, error) {
arr := append([]string{subcmd}, args...)
var out bytes.Buffer
cmd := exec.Command(client.config.Bin, arr...)
cmd.Stdout = &out
cmd.Stderr = ioutil.Discard
err := cmd.Run()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok {
if waitStatus.ExitStatus() != 0 {
return "", err
}
}
}
return strings.TrimRight(strings.TrimSpace(out.String()), "\000"), nil
}
// InsideWorkTree check whether the current working directory is inside the git repository
func (client *clientImpl) InsideWorkTree() error {
out, err := client.Exec("rev-parse", "--is-inside-work-tree")
if err != nil {
return err
}
if out != "true" {
cwd, err := os.Getwd()
if err != nil {
return err
}
return fmt.Errorf("\"%s\" is no git repository", cwd)
}
return nil
}
var (
git = NewGit(nil)
)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/quant1x/engine.git
git@gitee.com:quant1x/engine.git
quant1x
engine
engine
v1.8.24

搜索帮助