github.com/pengwynn/gh@v1.0.1-0.20140118055701-14327ca3942e/commands/clone.go (about) 1 package commands 2 3 import ( 4 "github.com/jingweno/gh/github" 5 "regexp" 6 "strings" 7 ) 8 9 var cmdClone = &Command{ 10 Run: clone, 11 GitExtension: true, 12 Usage: "clone [-p] OPTIONS [USER/]REPOSITORY DIRECTORY", 13 Short: "Clone a remote repository into a new directory", 14 Long: `Clone repository "git://github.com/USER/REPOSITORY.git" into 15 DIRECTORY as with git-clone(1). When USER/ is omitted, assumes 16 your GitHub login. With -p, clone private repositories over SSH. 17 For repositories under your GitHub login, -p is implicit. 18 `, 19 } 20 21 func init() { 22 CmdRunner.Use(cmdClone) 23 } 24 25 /** 26 $ gh clone jingweno/gh 27 > git clone git://github.com/jingweno/gh.git 28 29 $ gh clone -p jingweno/gh 30 > git clone git@github.com:jingweno/gh.git 31 32 $ gh clone jekyll_and_hyde 33 > git clone git://github.com/YOUR_LOGIN/jekyll_and_hyde.git 34 35 $ gh clone -p jekyll_and_hyde 36 > git clone git@github.com:YOUR_LOGIN/jekyll_and_hyde.git 37 */ 38 func clone(command *Command, args *Args) { 39 if !args.IsParamsEmpty() { 40 transformCloneArgs(args) 41 } 42 } 43 44 func transformCloneArgs(args *Args) { 45 isSSH := parseClonePrivateFlag(args) 46 hasValueRegxp := regexp.MustCompile("^(--(upload-pack|template|depth|origin|branch|reference|name)|-[ubo])$") 47 nameWithOwnerRegexp := regexp.MustCompile(NameWithOwnerRe) 48 for i := 0; i < args.ParamsSize(); i++ { 49 a := args.Params[i] 50 51 if strings.HasPrefix(a, "-") { 52 if hasValueRegxp.MatchString(a) { 53 i++ 54 } 55 } else { 56 if nameWithOwnerRegexp.MatchString(a) && !isDir(a) { 57 name, owner := parseCloneNameAndOwner(a) 58 var credentials *github.Credentials 59 if owner == "" { 60 configs := github.CurrentConfigs() 61 credentials = configs.DefaultCredentials() 62 owner = credentials.User 63 } 64 65 var host string 66 if credentials != nil { 67 host = credentials.Host 68 } 69 70 project := github.NewProject(owner, name, host) 71 isSSH = isSSH || 72 args.Command != "submodule" && 73 credentials != nil && 74 project.Owner == credentials.User 75 76 url := project.GitURL(name, owner, isSSH) 77 args.ReplaceParam(i, url) 78 } 79 80 break 81 } 82 } 83 } 84 85 func parseClonePrivateFlag(args *Args) bool { 86 if i := args.IndexOfParam("-p"); i != -1 { 87 args.RemoveParam(i) 88 return true 89 } 90 91 return false 92 } 93 94 func parseCloneNameAndOwner(arg string) (name, owner string) { 95 name, owner = arg, "" 96 if strings.Contains(arg, "/") { 97 split := strings.SplitN(arg, "/", 2) 98 name = split[1] 99 owner = split[0] 100 } 101 102 return 103 }