|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + |
| 7 | + "github.com/dvflw/mantle/internal/config" |
| 8 | + "github.com/dvflw/mantle/internal/db" |
| 9 | + "github.com/dvflw/mantle/internal/workflow" |
| 10 | + "github.com/spf13/cobra" |
| 11 | +) |
| 12 | + |
| 13 | +func newApplyCommand() *cobra.Command { |
| 14 | + return &cobra.Command{ |
| 15 | + Use: "apply <file>", |
| 16 | + Short: "Apply a workflow definition", |
| 17 | + Long: "Validates and stores a workflow definition as a new immutable version in the database.", |
| 18 | + Args: cobra.ExactArgs(1), |
| 19 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 20 | + filename := args[0] |
| 21 | + |
| 22 | + cfg := config.FromContext(cmd.Context()) |
| 23 | + if cfg == nil { |
| 24 | + return fmt.Errorf("config not loaded") |
| 25 | + } |
| 26 | + |
| 27 | + database, err := db.Open(cfg.Database.URL) |
| 28 | + if err != nil { |
| 29 | + return fmt.Errorf("failed to connect to database: %w", err) |
| 30 | + } |
| 31 | + defer database.Close() |
| 32 | + |
| 33 | + rawContent, err := os.ReadFile(filename) |
| 34 | + if err != nil { |
| 35 | + return fmt.Errorf("reading %s: %w", filename, err) |
| 36 | + } |
| 37 | + |
| 38 | + result, err := workflow.ParseBytes(rawContent) |
| 39 | + if err != nil { |
| 40 | + return fmt.Errorf("parsing %s: %w", filename, err) |
| 41 | + } |
| 42 | + |
| 43 | + version, err := workflow.Save(cmd.Context(), database, result, rawContent) |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + |
| 48 | + if version == 0 { |
| 49 | + latestVersion, _ := workflow.GetLatestVersion(cmd.Context(), database, result.Workflow.Name) |
| 50 | + fmt.Fprintf(cmd.OutOrStdout(), "No changes — %s is already at version %d\n", |
| 51 | + result.Workflow.Name, latestVersion) |
| 52 | + } else { |
| 53 | + fmt.Fprintf(cmd.OutOrStdout(), "Applied %s version %d\n", |
| 54 | + result.Workflow.Name, version) |
| 55 | + } |
| 56 | + |
| 57 | + return nil |
| 58 | + }, |
| 59 | + } |
| 60 | +} |
0 commit comments