-
Notifications
You must be signed in to change notification settings - Fork 2
/
clone.go
79 lines (70 loc) · 1.84 KB
/
clone.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package cmd
import (
"github.com/AlecAivazis/survey/v2"
"github.com/linuxsuren/cgit/pkg"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os/exec"
"path"
"strings"
)
type cloneOption struct {
ws bool
protocol string
}
// NewCloneCommand returns the clone command
func NewCloneCommand() (cmd *cobra.Command) {
opt := &cloneOption{}
cmd = &cobra.Command{
Use: "clone",
Short: "A smart way to clone repositories from GitHub",
RunE: opt.runE,
}
flags := cmd.Flags()
flags.BoolVarP(&opt.ws, "ws", "", false, "Clone the code into ~/ws/github/org/repo if it is true")
flags.StringVarP(&opt.protocol, "protocol", "p", "https", "The protocol, support: https, ssh, git")
return
}
func (o *cloneOption) runE(_ *cobra.Command, args []string) (err error) {
output := func(arg string) string {
if orgAndRepo := strings.Split(arg, "/"); len(orgAndRepo) == 2 {
return path.Join(viper.GetString("ws"), arg)
}
return ""
}
if !o.ws {
output = nil
}
args = pkg.ParseShortCodeWithProtocol(args, o.protocol, output)
var targetDir string
gitAddress := args[0]
if len(args) >= 2 {
targetDir = args[1]
}
var gitBinary string
if gitBinary, err = exec.LookPath("git"); err == nil {
gitArgs := []string{"clone"}
gitArgs = append(gitArgs, args...)
pkg.UseMirror(gitArgs)
if err = pkg.ExecCommandInDir(gitBinary, "", gitArgs...); err == nil {
err = pkg.ExecCommandInDir(gitBinary, targetDir, "remote", "set-url", "origin", gitAddress)
}
}
if err != nil {
return
}
var ghBinary string
if ghBinary, err = exec.LookPath("gh"); err == nil {
prompt := &survey.Confirm{
Message: "do you want to fork it?",
}
var ok bool
if err = survey.AskOne(prompt, &ok); err == nil && ok {
err = pkg.ExecCommandInDir(ghBinary, targetDir, "repo", "fork", "--remote")
}
} else {
// it's ok if no gh found
err = nil
}
return
}