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) } // STEP 1 MIGRATE USERS { f1, err := os.Open(cfg.Users.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 + "/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(cfg.Gitea.URL + "/admin/users")) if err != nil { panic(err) } u := domain.UserCreateRequest{ Email: record[4], FullName: record[2], LoginName: record[1], MustChangePassword: true, Password: cfg.Users.DefaultPassword, Restricted: false, SendNotify: false, SourceID: 0, Username: record[1], } bts, err := json.Marshal(u) 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", u.Email, resp.StatusCode, string(bts))); err != nil { panic(err) } continue } bts, err = io.ReadAll(resp.Body) if err != nil { panic(err) } var uResp domain.UserGet if err := json.Unmarshal(bts, &uResp); err != nil { panic(err) } if _, err := outputFile.WriteString(fmt.Sprintf("USER %d | %s | OK\n", uResp.ID, uResp.Email)); 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 }