/
stash.go
80 lines (67 loc) · 1.66 KB
/
stash.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
package main
import (
"fmt"
"regexp"
"github.com/bndr/gopencils"
)
type StashAPI struct {
*gopencils.Resource
}
type ResponseStashPullRequest struct {
FromRef struct {
// I dunno why stash developers names branch field as `displayId`
Branch string `json:"displayId"`
Repository struct {
Links struct {
// there is can be http and ssh clone urls
Clone []struct {
Href string
Name string
} `json:"clone"`
} `json:"links"`
} `json:"repository"`
} `json:"fromRef"`
}
var (
reStashURL = regexp.MustCompile(
`(https?://.*/)` +
`((users|projects)/([^/]+))` +
`/repos/([^/]+)` +
`/pull-requests/(\d+)`)
)
func getStashAPI(host, user, pass string) (*StashAPI, error) {
return &StashAPI{
gopencils.Api(
"http://"+host+"/rest/api/1.0",
&gopencils.BasicAuth{user, pass},
),
}, nil
}
// GetPullRequestInfo calls stash api and returns info about pull request:
// ssh clone url and full branch name (like refs/heads/dev)
func (api *StashAPI) GetPullRequestInfo(
project, repository, pullRequest string,
) (string, string, error) {
request, err := api.Res("projects").Res(project).
Res("repos").Res(repository).
Res("pull-requests").Res(pullRequest, &ResponseStashPullRequest{}).
Get()
if err != nil {
return "", "", err
}
info := *request.Response.(*ResponseStashPullRequest)
sshCloneURL := ""
for _, clone := range info.FromRef.Repository.Links.Clone {
if clone.Name != "ssh" {
continue
}
sshCloneURL = clone.Href
}
if sshCloneURL == "" {
return "", "", fmt.Errorf(
"can't get ssh clone url of specified pull request",
)
}
branch := "origin/" + info.FromRef.Branch
return sshCloneURL, branch, nil
}