clone.go 2.0 KB
Newer Older
J
Jingwen Owen Ou 已提交
1 2 3 4 5 6 7 8 9 10 11
package commands

import (
	"github.com/jingweno/gh/github"
	"regexp"
	"strings"
)

var cmdClone = &Command{
	Run:          clone,
	GitExtension: true,
J
Jingwen Owen Ou 已提交
12 13
	Usage:        "Clone [-p] OPTIONS [USER/]REPOSITORY DIRECTORY",
	Short:        "Clone a remote repository into a new directory",
14 15 16 17 18
	Long: `Clone repository "git://github.com/USER/REPOSITORY.git" into
DIRECTORY as with git-clone(1). When USER/ is omitted, assumes
your GitHub login. With -p, clone private repositories over SSH.
For repositories under your GitHub login, -p is implicit.
`,
J
Jingwen Owen Ou 已提交
19 20 21 22 23 24 25 26 27 28 29 30
}

/**
  $ gh clone jingweno/gh
  > git clone git://github.com/jingweno/gh

  $ gh clone -p jingweno/gh
  > git clone git@github.com:jingweno/gh.git

  $ gh clone jekyll_and_hype
  > git clone git://github.com/YOUR_LOGIN/jekyll_and_hype.

J
Jingwen Owen Ou 已提交
31 32
  $ gh clone -p jekyll_and_hyde
  > git clone git@github.com:YOUR_LOGIN/jekyll_and_hyde.git
J
Jingwen Owen Ou 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
*/
func clone(command *Command, args *Args) {
	if !args.IsEmpty() {
		transformCloneArgs(args)
	}
}

func transformCloneArgs(args *Args) {
	isSSH := parseClonePrivateFlag(args)
	hasValueRegxp := regexp.MustCompile("^(--(upload-pack|template|depth|origin|branch|reference|name)|-[ubo])$")
	nameWithOwnerRegexp := regexp.MustCompile(NameWithOwnerRe)
	for i, a := range args.Array() {
		if hasValueRegxp.MatchString(a) {
			continue
		}

		if nameWithOwnerRegexp.MatchString(a) && !isDir(a) {
50
			name, owner := parseCloneNameAndOwner(a)
51 52 53 54 55 56
			config := github.CurrentConfig()
			if owner == "" {
				owner = config.User
			}
			isSSH = isSSH || owner == config.User

J
Jingwen Owen Ou 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
			project := github.Project{Name: name, Owner: owner}
			url := project.GitURL(name, owner, isSSH)
			args.Replace(i, url)

			break
		}
	}
}

func parseClonePrivateFlag(args *Args) bool {
	if i := args.IndexOf("-p"); i != -1 {
		args.Remove(i)
		return true
	}

	return false
}
74 75 76 77 78 79 80 81 82 83 84

func parseCloneNameAndOwner(arg string) (name, owner string) {
	name, owner = arg, ""
	if strings.Contains(arg, "/") {
		split := strings.SplitN(arg, "/", 2)
		name = split[1]
		owner = split[0]
	}

	return
}