Files
gitlab-cleanup-handler/gitlab/client.go
T

124 lines
3.2 KiB
Go

package gitlab
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
func New(token string) *RestClient {
return &RestClient{token: token, client: http.DefaultClient}
}
type RestClient struct {
client *http.Client
token string
}
func (r *RestClient) UpdateCleanupPolicy(project string, versions []string) error {
encoded := url.QueryEscape(project)
reqUrl, err := url.Parse(fmt.Sprintf("https://gitlab.com/api/v4/projects/%s", encoded))
if err != nil {
return err
}
options := ProjectConfig{
ContainerExpirationPolicyAttributes: ContainerExpirationPolicyAttributes{
Cadence: "1d",
Enabled: true,
KeepN: 10,
OlderThan: "14d",
NameRegex: ".*",
NameRegexKeep: fmt.Sprintf("(main|master|%s)", strings.Join(versions, "|")),
},
}
buff := &bytes.Buffer{}
encoder := json.NewEncoder(buff)
err = encoder.Encode(&options)
if err != nil {
return err
}
header := http.Header{}
header.Add("Content-Type", "application/json;charset=UTF-8")
header.Add("PRIVATE-TOKEN", r.token)
req := &http.Request{
Method: "PUT",
URL: reqUrl,
Header: header,
Body: io.NopCloser(buff),
}
_, err = r.client.Do(req)
return err
}
func (r *RestClient) GetTags(project string) ([]Tag, error) {
encoded := url.QueryEscape(project)
reqUrl, err := url.Parse(fmt.Sprintf("https://gitlab.com/api/v4/projects/%s/repository/tags", encoded))
if err != nil {
return nil, err
}
header := http.Header{}
header.Add("Content-Type", "application/json;charset=UTF-8")
header.Add("PRIVATE-TOKEN", r.token)
req := &http.Request{
Method: "GET",
URL: reqUrl,
Header: header,
}
resp, err := r.client.Do(req)
if err != nil {
return nil, err
}
var tags []Tag
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&tags)
return tags, err
}
type ProjectConfig struct {
ContainerExpirationPolicyAttributes ContainerExpirationPolicyAttributes `json:"container_expiration_policy_attributes"`
}
type ContainerExpirationPolicyAttributes struct {
Cadence string `json:"cadence"`
Enabled bool `json:"enabled"`
KeepN int `json:"keep_n"`
OlderThan string `json:"older_than"`
NameRegex string `json:"name_regex"`
NameRegexKeep string `json:"name_regex_keep"`
}
type Tag struct {
Commit Commit `json:"commit"`
Release Release `json:"release"`
Name string `json:"name"`
Target string `json:"target"`
Message interface{} `json:"message"`
Protected bool `json:"protected"`
}
type Commit struct {
ID string `json:"id"`
ShortID string `json:"short_id"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
ParentIds []string `json:"parent_ids"`
Message string `json:"message"`
AuthorName string `json:"author_name"`
AuthorEmail string `json:"author_email"`
AuthoredDate string `json:"authored_date"`
CommitterName string `json:"committer_name"`
CommitterEmail string `json:"committer_email"`
CommittedDate string `json:"committed_date"`
}
type Release struct {
TagName string `json:"tag_name"`
Description string `json:"description"`
}