Skip to content

Commit

Permalink
Add transform address for git #13
Browse files Browse the repository at this point in the history
- get https, ssh clone address from browser url
  • Loading branch information
at15 committed Jan 15, 2016
1 parent ba3ec36 commit fb7a95f
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 7 deletions.
48 changes: 42 additions & 6 deletions app/git/clone.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,62 @@
package git

import (
"fmt"
"regexp"

"github.com/go-errors/errors"
)

// browserRegexp extract information from browser url like https://github.com/dyweb/Ayi
var browserRegexp = "(http|https):\\/\\/(.*?)\\/(.*?)\\/(.*)"

const remoteSegmentsLen = 4

// Remote represents a remote git repo
type Remote struct {
// Protocol is http, https, ssh
Protocol string
// Host is the git host provider domain name, like github.com
Host string
Host string
// Org is user name or organization name
Org string
Org string
// Repo is repository name
Repo string
Repo string
}

func getRemote(url string) (remote Remote, err error) {
// parse the url
r, _ := regexp.Compile(browserRegexp)
if !r.MatchString(url) {
return remote, errors.New("invalid browser url" + url)
}
segments := r.FindStringSubmatch(url)

// the matched string is captured as segments[0]
if len(segments) != (remoteSegmentsLen + 1) {
return remote, errors.New(fmt.Errorf("got %d segments for url", len(segments)))
}

remote = Remote{Protocol: segments[1], Host: segments[2], Org: segments[3], Repo: segments[4]}

return remote, err
}

// transformAddress will turn remote browser address to valid ssh and http clone address
func transformAddress(remote string) (sshAddress string, httpAddress string) {
return "", ""
func transformAddress(url string) (sshAddress string, httpAddress string) {
remote, _ := getRemote(url)
// [email protected]:dyweb/Ayi.git
sshAddress = fmt.Sprintf("git@%s:%s/%s.git",
remote.Host,
remote.Org,
remote.Repo,
)
// https://github.com/dyweb/Ayi.git
httpAddress = fmt.Sprintf("%s://%s/%s/%s.git",
remote.Protocol,
remote.Host,
remote.Org,
remote.Repo,
)
return sshAddress, httpAddress
}

34 changes: 33 additions & 1 deletion app/git/clone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,36 @@ func TestRegexpGitLab(t *testing.T) {
t.Fail()
t.Log("cant match repo name")
}
}
}

func TestGetRemote(t *testing.T) {
r, e := getRemote("https://github.com/dyweb/Ayi")
if e != nil {
t.Fail()
t.Log("should have parsed remote properly")
}
if r.Protocol != "https" {
t.Fail()
}
if r.Host != "github.com" {
t.Fail()
}
if r.Org != "dyweb" {
t.Fail()
}
if r.Repo != "Ayi" {
t.Fail()
}
}

func TestTransformAddress(t *testing.T) {
ssh, http := transformAddress("https://github.com/dyweb/Ayi")
if ssh != "[email protected]:dyweb/Ayi.git" {
t.Fail()
t.Log(ssh)
}
if http != "https://github.com/dyweb/Ayi.git" {
t.Fail()
t.Log(http)
}
}

0 comments on commit fb7a95f

Please sign in to comment.