|
|
|
@ -2,12 +2,10 @@ package base |
|
|
|
|
|
|
|
|
|
import ( |
|
|
|
|
"context" |
|
|
|
|
"errors" |
|
|
|
|
"os" |
|
|
|
|
"os/exec" |
|
|
|
|
"path" |
|
|
|
|
"strings" |
|
|
|
|
|
|
|
|
|
"github.com/go-git/go-git/v5" |
|
|
|
|
) |
|
|
|
|
|
|
|
|
|
// Repo is git repository manager.
|
|
|
|
@ -18,11 +16,17 @@ type Repo struct { |
|
|
|
|
|
|
|
|
|
// NewRepo new a repository manager.
|
|
|
|
|
func NewRepo(url string) *Repo { |
|
|
|
|
start := strings.Index(url, "//") |
|
|
|
|
var start int |
|
|
|
|
start = strings.Index(url, "//") |
|
|
|
|
if start == -1 { |
|
|
|
|
start = strings.Index(url, ":") + 1 |
|
|
|
|
} else { |
|
|
|
|
start += 2 |
|
|
|
|
} |
|
|
|
|
end := strings.LastIndex(url, "/") |
|
|
|
|
return &Repo{ |
|
|
|
|
url: url, |
|
|
|
|
home: kratosHomeWithDir("repo/" + url[start+2:end]), |
|
|
|
|
home: kratosHomeWithDir("repo/" + url[start:end]), |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
@ -30,25 +34,19 @@ func NewRepo(url string) *Repo { |
|
|
|
|
func (r *Repo) Path() string { |
|
|
|
|
start := strings.LastIndex(r.url, "/") |
|
|
|
|
end := strings.LastIndex(r.url, ".git") |
|
|
|
|
if end == -1 { |
|
|
|
|
end = len(r.url) |
|
|
|
|
} |
|
|
|
|
return path.Join(r.home, r.url[start+1:end]) |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
// Pull fetch the repository from remote url.
|
|
|
|
|
func (r *Repo) Pull(ctx context.Context) error { |
|
|
|
|
repo, err := git.PlainOpen(r.Path()) |
|
|
|
|
if err != nil { |
|
|
|
|
return err |
|
|
|
|
} |
|
|
|
|
w, err := repo.Worktree() |
|
|
|
|
if err != nil { |
|
|
|
|
return err |
|
|
|
|
} |
|
|
|
|
if err = w.PullContext(ctx, &git.PullOptions{ |
|
|
|
|
RemoteName: "origin", |
|
|
|
|
Progress: os.Stdout, |
|
|
|
|
}); errors.Is(err, git.NoErrAlreadyUpToDate) { |
|
|
|
|
return nil |
|
|
|
|
} |
|
|
|
|
cmd := exec.Command("git", "pull") |
|
|
|
|
cmd.Dir = r.Path() |
|
|
|
|
cmd.Stdout = os.Stdout |
|
|
|
|
cmd.Stderr = os.Stderr |
|
|
|
|
err := cmd.Run() |
|
|
|
|
return err |
|
|
|
|
} |
|
|
|
|
|
|
|
|
@ -57,10 +55,10 @@ func (r *Repo) Clone(ctx context.Context) error { |
|
|
|
|
if _, err := os.Stat(r.Path()); !os.IsNotExist(err) { |
|
|
|
|
return r.Pull(ctx) |
|
|
|
|
} |
|
|
|
|
_, err := git.PlainCloneContext(ctx, r.Path(), false, &git.CloneOptions{ |
|
|
|
|
URL: r.url, |
|
|
|
|
Progress: os.Stdout, |
|
|
|
|
}) |
|
|
|
|
cmd := exec.Command("git", "clone", r.url, r.Path()) |
|
|
|
|
cmd.Stdout = os.Stdout |
|
|
|
|
cmd.Stderr = os.Stderr |
|
|
|
|
err := cmd.Run() |
|
|
|
|
return err |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|