package main import ( "bytes" "context" "encoding/csv" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "os/signal" "path" "runtime" "syscall" "gitea.urkob.com/mcr-swiss/gogstea/internal/domain" "gitea.urkob.com/mcr-swiss/gogstea/kit/config" ) 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.Organizations.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 + "/org-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/admin/users/%s/orgs", cfg.Gitea.URL, record[2])) if err != nil { panic(err) } bodyReq := domain.OrgCreateRequest{ Description: record[0], Email: "", FullName: "", Location: "", RepoAdminChangeTeamAccess: true, Username: record[0], Visibility: "private", Website: "", } bts, err := json.Marshal(bodyReq) if err != nil { panic(err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, 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 resp.StatusCode != http.StatusOK { bts, _ := io.ReadAll(resp.Body) if _, err := outputFile.WriteString(fmt.Sprintf("%s | %d: %s\n", record[3], resp.StatusCode, 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 REPO %s | %s | OK\n", bodyReq.Username, 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 }