Files
gitlab-cleanup-handler/gitlab/client.go
T
2022-09-09 14:50:14 +02:00

69 lines
1.6 KiB
Go

package gitlab
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
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
}
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"`
}