@@ -0,0 +1,71 @@ |
| 1 | +// SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | + |
| 3 | +package main |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "sort" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/spf13/cobra" |
| 14 | + |
| 15 | + "github.com/tenseleyFlow/shithub/internal/infra/db" |
| 16 | +) |
| 17 | + |
| 18 | +var seedCmd = &cobra.Command{ |
| 19 | + Use: "seed", |
| 20 | + Short: "Load development seed SQL files from seeds/dev/ in lex order", |
| 21 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 22 | + dir, _ := cmd.Flags().GetString("dir") |
| 23 | + return runSeed(cmd.Context(), dir) |
| 24 | + }, |
| 25 | +} |
| 26 | + |
| 27 | +func init() { |
| 28 | + seedCmd.Flags().StringP("dir", "d", "seeds/dev", "Directory containing .sql seed files") |
| 29 | +} |
| 30 | + |
| 31 | +func runSeed(ctx context.Context, dir string) error { |
| 32 | + pool, err := db.Open(ctx, db.Defaults()) |
| 33 | + if err != nil { |
| 34 | + return err |
| 35 | + } |
| 36 | + defer pool.Close() |
| 37 | + |
| 38 | + entries, err := os.ReadDir(dir) |
| 39 | + if err != nil { |
| 40 | + return fmt.Errorf("seed: read %s: %w", dir, err) |
| 41 | + } |
| 42 | + var files []string |
| 43 | + for _, e := range entries { |
| 44 | + if e.IsDir() { |
| 45 | + continue |
| 46 | + } |
| 47 | + if !strings.HasSuffix(e.Name(), ".sql") { |
| 48 | + continue |
| 49 | + } |
| 50 | + files = append(files, filepath.Join(dir, e.Name())) |
| 51 | + } |
| 52 | + sort.Strings(files) |
| 53 | + |
| 54 | + if len(files) == 0 { |
| 55 | + fmt.Fprintln(os.Stderr, "seed: no .sql files in", dir, "(nothing to do)") |
| 56 | + return nil |
| 57 | + } |
| 58 | + |
| 59 | + for _, f := range files { |
| 60 | + body, err := os.ReadFile(f) //nolint:gosec // operator-supplied path |
| 61 | + if err != nil { |
| 62 | + return fmt.Errorf("seed: read %s: %w", f, err) |
| 63 | + } |
| 64 | + fmt.Fprintln(os.Stderr, "seed: applying", f) |
| 65 | + if _, err := pool.Exec(ctx, string(body)); err != nil { |
| 66 | + return fmt.Errorf("seed: %s: %w", f, err) |
| 67 | + } |
| 68 | + } |
| 69 | + fmt.Fprintln(os.Stderr, "seed: done") |
| 70 | + return nil |
| 71 | +} |