84 lines
1.6 KiB
Go
84 lines
1.6 KiB
Go
package remotes
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/xanzy/go-gitlab"
|
|
"gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/config"
|
|
)
|
|
|
|
type Client struct {
|
|
Ctx context.Context
|
|
Config *config.GitlabConfig
|
|
apiClient *gitlab.Client
|
|
}
|
|
|
|
type Clients []*Client
|
|
|
|
type ClientOpts struct {
|
|
Ctx context.Context
|
|
Name string
|
|
Host string
|
|
Token string
|
|
}
|
|
|
|
func (c *Clients) AddClients(gitlabClient ...*Client) error {
|
|
var err error
|
|
for _, client := range gitlabClient {
|
|
if c.GetClientByHost(client.Config.Host) != nil {
|
|
err = errors.Join(err, fmt.Errorf("Client with host %s already exists", client.Config.Host))
|
|
} else {
|
|
*c = append(*c, client)
|
|
}
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (c *Clients) GetClientByHost(host string) *Client {
|
|
for _, client := range *c {
|
|
if client.Config.Host == host {
|
|
return client
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func NewCLients() *Clients {
|
|
var clients Clients
|
|
clients = make([]*Client, 0)
|
|
return &clients
|
|
}
|
|
|
|
func NewGitlabClients(clientOpts []*ClientOpts) (*Clients, error) {
|
|
var err error
|
|
clients := NewCLients()
|
|
for _, opts := range clientOpts {
|
|
gitlabClient, e := NewGitlabClient(opts)
|
|
if e != nil {
|
|
err = errors.Join(err, e)
|
|
continue
|
|
}
|
|
err = errors.Join(err, clients.AddClients(gitlabClient))
|
|
}
|
|
return clients, err
|
|
}
|
|
|
|
func NewGitlabClient(opts *ClientOpts) (*Client, error) {
|
|
client, err := gitlab.NewClient(opts.Token, gitlab.WithBaseURL(opts.Host))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
gitlabClient := &Client{
|
|
Ctx: opts.Ctx,
|
|
Config: &config.GitlabConfig{
|
|
Name: opts.Name,
|
|
Host: opts.Host,
|
|
Token: opts.Token,
|
|
},
|
|
apiClient: client,
|
|
}
|
|
return gitlabClient, nil
|
|
}
|