forked from mislav/hub
/
clone.go
116 lines (96 loc) · 2.72 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package commands
import (
"regexp"
"strings"
"github.com/github/hub/github"
"github.com/github/hub/utils"
)
var cmdClone = &Command{
Run: clone,
GitExtension: true,
Usage: "clone [-p] OPTIONS [USER/]REPOSITORY [DIRECTORY]",
Short: "Clone a remote repository into a new directory",
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.
`,
}
func init() {
CmdRunner.Use(cmdClone)
}
/**
$ hub clone jingweno/gh
> git clone git://github.com/jingweno/gh.git
$ hub clone -p jingweno/gh
> git clone git@github.com:jingweno/gh.git
$ hub clone jekyll_and_hyde
> git clone git://github.com/YOUR_LOGIN/jekyll_and_hyde.git
$ hub clone -p jekyll_and_hyde
> git clone git@github.com:YOUR_LOGIN/jekyll_and_hyde.git
$ hub clone jekyll_and_hyde jekyll
> git clone git://github.com/YOUR_LOGIN/jekyll_and_hyde.git jekyll
*/
func clone(command *Command, args *Args) {
if !args.IsParamsEmpty() {
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 := 0; i < args.ParamsSize(); i++ {
a := args.Params[i]
if strings.HasPrefix(a, "-") {
if hasValueRegxp.MatchString(a) {
i++
}
} else {
if nameWithOwnerRegexp.MatchString(a) && !isCloneable(a) {
name, owner := parseCloneNameAndOwner(a)
var host *github.Host
if owner == "" {
config := github.CurrentConfig()
h, err := config.DefaultHost()
if err != nil {
utils.Check(github.FormatError("cloning repository", err))
}
host = h
owner = host.User
}
var hostStr string
if host != nil {
hostStr = host.Host
}
project := github.NewProject(owner, name, hostStr)
if !isSSH &&
args.Command != "submodule" &&
!github.IsHttpsProtocol() {
client := github.NewClient(project.Host)
repo, err := client.Repository(project)
isSSH = (err == nil) && (repo.Private || repo.Permissions.Push)
}
url := project.GitURL(name, owner, isSSH)
args.ReplaceParam(i, url)
}
break
}
}
}
func parseClonePrivateFlag(args *Args) bool {
if i := args.IndexOfParam("-p"); i != -1 {
args.RemoveParam(i)
return true
}
return false
}
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
}