/
client.go
84 lines (71 loc) · 1.94 KB
/
client.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
package gitlab
import (
"context"
"fmt"
"github.com/unanet/eve/pkg/scm/types"
"net/http"
"strings"
"time"
"github.com/dghubble/sling"
ehttp "github.com/unanet/go/pkg/http"
"github.com/unanet/go/pkg/json"
)
const (
userAgent = "eve-gitlab"
)
type Config struct {
GitlabApiKey string `envconfig:"GITLAB_API_KEY"`
GitlabBaseUrl string `envconfig:"GITLAB_BASE_URL"`
GitlabTimeout time.Duration `envconfig:"GITLAB_TIMEOUT" default:"20s"`
}
type Client struct {
sling *sling.Sling
}
func NewClient(config Config) *Client {
var httpClient = &http.Client{
Timeout: config.GitlabTimeout,
Transport: ehttp.LoggingTransport,
}
if !strings.HasSuffix(config.GitlabBaseUrl, "/") {
config.GitlabBaseUrl += "/"
}
s := sling.New().Base(config.GitlabBaseUrl).Client(httpClient).
Add("PRIVATE-TOKEN", config.GitlabApiKey).
Add("User-Agent", userAgent).
ResponseDecoder(json.NewJsonDecoder())
return &Client{sling: s}
}
func (c *Client) TagCommit(ctx context.Context, options types.TagOptions) (*types.Tag, error) {
var success types.Tag
var failure types.ErrorResponse
r, err := c.sling.New().Post(fmt.Sprintf("v4/projects/%d/repository/tags", options.ProjectID)).QueryStruct(options).Request()
if err != nil {
return nil, err
}
resp, err := c.sling.Do(r.WithContext(ctx), &success, &failure)
if err != nil {
return nil, err
}
if http.StatusCreated == resp.StatusCode {
return &success, nil
} else {
return nil, failure
}
}
func (c *Client) GetTag(ctx context.Context, options types.TagOptions) (*types.Tag, error) {
var success types.Tag
var failure types.ErrorResponse
r, err := c.sling.New().Get(fmt.Sprintf("v4/projects/%d/repository/tags/%s", options.ProjectID, options.TagName)).Request()
if err != nil {
return nil, err
}
resp, err := c.sling.Do(r.WithContext(ctx), &success, &failure)
if err != nil {
return nil, err
}
switch {
case resp.StatusCode < 300:
return &success, nil
}
return nil, failure
}