gogstea/cmd/collaborator/main.go

144 lines
2.7 KiB
Go
Raw Normal View History

2024-08-30 13:45:18 +02:00
package main
import (
"bytes"
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"runtime"
"slices"
"syscall"
"gitea.urkob.com/mcr-swiss/gogstea/internal/domain"
"gitea.urkob.com/mcr-swiss/gogstea/kit/config"
)
var okStatuses = []int{
http.StatusOK,
http.StatusCreated,
http.StatusNoContent,
}
func main() {
ctx, cancel := context.WithCancel(signalContext(context.Background()))
defer cancel()
cfgFile := os.Getenv("CONFIG_FILE")
if cfgFile == "" {
// Get root path
_, filename, _, _ := runtime.Caller(0)
cfgFile = path.Join(path.Dir(filename), "configs", "app.yml")
}
cfg, err := config.LoadConfig(cfgFile)
if err != nil {
panic(err)
}
wd, err := os.Getwd()
if err != nil {
panic(err)
}
f1, err := os.Open(cfg.Collaborators.CSVPath)
if err != nil {
panic(err)
}
defer f1.Close()
r1 := csv.NewReader(f1)
r1.Comma = ',' // Set the delimiter to comma
r1.LazyQuotes = true
r1.TrimLeadingSpace = false
outputFile, err := os.Create(wd + "/collab-output.txt")
if err != nil {
panic(err)
}
defer outputFile.Close()
for {
record, err := r1.Read()
if err != nil {
if !errors.Is(err, io.EOF) {
panic(err)
}
break // Stop on EOF or other errors.
}
cli := http.DefaultClient
parsedURL, err := url.Parse(fmt.Sprintf("%s/repos/%s/%s/collaborators/%s", cfg.Gitea.URL, record[1], record[0], record[2]))
if err != nil {
panic(err)
}
// permission, err := strconv.Atoi(record[3])
// if err != nil {
// panic(err)
// }
collabReq := domain.CollaboratorCreateRequest{
Permission: record[4],
}
bts, err := json.Marshal(collabReq)
if err != nil {
panic(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPut, parsedURL.String(), bytes.NewReader(bts))
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "token "+cfg.Gitea.ApiKey)
req.Header.Add("Content-Type", "application/json")
resp, err := cli.Do(req)
if err != nil {
panic(err)
}
if !slices.Contains(okStatuses, resp.StatusCode) {
bts, _ := io.ReadAll(resp.Body)
if _, err := outputFile.WriteString(fmt.Sprintf("ERROR COLLAB | %d | %s | %s\n", resp.StatusCode, parsedURL.String(), string(bts))); err != nil {
panic(err)
}
continue
}
bts, err = io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
if _, err := outputFile.WriteString(fmt.Sprintf("OK COLLAB | %s \n", string(bts))); err != nil {
panic(err)
}
}
}
func signalContext(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
signal.Stop(sigs)
close(sigs)
cancel()
}()
return ctx
}