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