|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/apply" |
| 14 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/plan" |
| 15 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/render" |
| 16 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/state/sqlite" |
| 17 | + "github.com/mattn/go-isatty" |
| 18 | + "github.com/spf13/cobra" |
| 19 | +) |
| 20 | + |
| 21 | +// EnvAutoApprove is read when true-like to skip the apply confirmation prompt (non-TTY / CI). |
| 22 | +const EnvAutoApprove = "AGENTCTL_AUTO_APPROVE" |
| 23 | + |
| 24 | +func newApplyCmd() *cobra.Command { |
| 25 | + var autoApprove bool |
| 26 | + cmd := &cobra.Command{ |
| 27 | + Use: "apply", |
| 28 | + Short: "Apply desired project state to the deployment store", |
| 29 | + SilenceUsage: true, |
| 30 | + Long: `Load and validate the project, compute the plan against the SQLite deployment store, |
| 31 | +then persist changes unless you decline at the prompt. |
| 32 | +
|
| 33 | +Use --auto-approve to skip confirmation, or set ` + EnvAutoApprove + `=1 for non-interactive runs |
| 34 | +(CI, scripts). When stdin is not a terminal and the plan is non-empty, one of those is required. |
| 35 | +
|
| 36 | +The state database defaults to .agentic/state.db under --project, or project.spec.state.dsn, |
| 37 | +unless overridden by global --state. |
| 38 | +
|
| 39 | +Exit codes (section 11.2): |
| 40 | + 0 — success (including nothing to apply) |
| 41 | + 1 — generic failure (e.g. cannot open SQLite, non-interactive without approval, cancelled) |
| 42 | + 2 — validation failure (invalid project), or non-table output without approval when the plan is non-empty |
| 43 | + 3 — plan/apply conflict (reserved for optimistic concurrency; not used in this MVP)`, |
| 44 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 45 | + _ = args |
| 46 | + return runApply(cmd, autoApprove) |
| 47 | + }, |
| 48 | + } |
| 49 | + cmd.Flags().BoolVar(&autoApprove, "auto-approve", false, "apply without confirmation prompt") |
| 50 | + return cmd |
| 51 | +} |
| 52 | + |
| 53 | +func envAutoApproveEnabled() bool { |
| 54 | + v := strings.TrimSpace(os.Getenv(EnvAutoApprove)) |
| 55 | + switch strings.ToLower(v) { |
| 56 | + case "1", "true", "yes", "on": |
| 57 | + return true |
| 58 | + default: |
| 59 | + return false |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +func runApply(cmd *cobra.Command, flagAutoApprove bool) error { |
| 64 | + ctx := context.Background() |
| 65 | + g := Globals() |
| 66 | + approved := flagAutoApprove || envAutoApproveEnabled() |
| 67 | + |
| 68 | + graph, root, err := prepareProjectGraph(g.ProjectRoot, g) |
| 69 | + if err != nil { |
| 70 | + return NewExitError(ExitValidationError, err) |
| 71 | + } |
| 72 | + |
| 73 | + env := planEnvironment(g) |
| 74 | + dsn, err := resolveStateSQLitePath(root, graph, g.StatePath) |
| 75 | + if err != nil { |
| 76 | + return fmt.Errorf("apply: resolve state path: %w", err) |
| 77 | + } |
| 78 | + if err := os.MkdirAll(filepath.Dir(dsn), 0o755); err != nil { |
| 79 | + return fmt.Errorf("apply: create state directory: %w", err) |
| 80 | + } |
| 81 | + |
| 82 | + st, err := sqlite.Open(ctx, dsn) |
| 83 | + if err != nil { |
| 84 | + return fmt.Errorf("apply: open sqlite %q: %w", dsn, err) |
| 85 | + } |
| 86 | + defer func() { _ = st.Close() }() |
| 87 | + |
| 88 | + pl, err := plan.NewPlanner(st).ComputePlan(ctx, env, graph) |
| 89 | + if err != nil { |
| 90 | + return fmt.Errorf("apply: compute plan: %w", err) |
| 91 | + } |
| 92 | + |
| 93 | + if len(pl.Operations) == 0 { |
| 94 | + return writeApplyEmptyOutput(cmd, env, dsn, pl, g) |
| 95 | + } |
| 96 | + |
| 97 | + if g.Output != render.FormatTable { |
| 98 | + if !approved { |
| 99 | + return NewExitErrorf(ExitValidationError, "apply: when the plan is non-empty, -o %s requires --auto-approve or %s=1", g.Output, EnvAutoApprove) |
| 100 | + } |
| 101 | + } else if !approved { |
| 102 | + if !isatty.IsTerminal(os.Stdin.Fd()) { |
| 103 | + return NewExitErrorf(ExitGenericFailure, "apply: not a terminal; use --auto-approve or set %s=1 to apply without confirmation", EnvAutoApprove) |
| 104 | + } |
| 105 | + if _, err := fmt.Fprint(cmd.OutOrStdout(), plan.FormatPlan(pl)); err != nil { |
| 106 | + return err |
| 107 | + } |
| 108 | + if _, err := fmt.Fprint(cmd.OutOrStdout(), "\n\n"); err != nil { |
| 109 | + return err |
| 110 | + } |
| 111 | + if _, err := fmt.Fprint(cmd.ErrOrStderr(), "Do you want to apply these changes? [y/N]: "); err != nil { |
| 112 | + return err |
| 113 | + } |
| 114 | + ok, err := readApplyConfirmation(cmd.InOrStdin()) |
| 115 | + if err != nil { |
| 116 | + return fmt.Errorf("apply: read confirmation: %w", err) |
| 117 | + } |
| 118 | + if !ok { |
| 119 | + return NewExitErrorf(ExitGenericFailure, "apply: cancelled") |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + at := time.Now().UTC() |
| 124 | + if err := apply.NewApplier(st).ApplyPlan(ctx, env, graph, pl, at); err != nil { |
| 125 | + return fmt.Errorf("apply: %w", err) |
| 126 | + } |
| 127 | + |
| 128 | + return writeApplySuccessOutput(cmd, env, dsn, pl, g, at) |
| 129 | +} |
| 130 | + |
| 131 | +func readApplyConfirmation(r io.Reader) (bool, error) { |
| 132 | + line, err := bufio.NewReader(r).ReadString('\n') |
| 133 | + if err != nil && err != io.EOF { |
| 134 | + return false, err |
| 135 | + } |
| 136 | + s := strings.TrimSpace(strings.ToLower(line)) |
| 137 | + return s == "y" || s == "yes", nil |
| 138 | +} |
| 139 | + |
| 140 | +func writeApplyEmptyOutput(cmd *cobra.Command, env, dsn string, pl *plan.Plan, g *Global) error { |
| 141 | + out := cmd.OutOrStdout() |
| 142 | + switch g.Output { |
| 143 | + case render.FormatJSON: |
| 144 | + m := planJSONModel(env, dsn, pl) |
| 145 | + m["applied"] = false |
| 146 | + m["message"] = "no changes" |
| 147 | + return render.WriteJSON(out, m) |
| 148 | + case render.FormatYAML: |
| 149 | + m := planJSONModel(env, dsn, pl) |
| 150 | + m["applied"] = false |
| 151 | + m["message"] = "no changes" |
| 152 | + return render.WriteYAML(out, m) |
| 153 | + default: |
| 154 | + _, err := fmt.Fprintf(out, "Environment: %s\nState: %s\n\nNo changes. Deployment already matches the project.\n", env, dsn) |
| 155 | + return err |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +func writeApplySuccessOutput(cmd *cobra.Command, env, dsn string, pl *plan.Plan, g *Global, at time.Time) error { |
| 160 | + out := cmd.OutOrStdout() |
| 161 | + c, u, d := planCounts(pl) |
| 162 | + switch g.Output { |
| 163 | + case render.FormatJSON: |
| 164 | + m := planJSONModel(env, dsn, pl) |
| 165 | + m["applied"] = true |
| 166 | + m["appliedAt"] = at.Format(time.RFC3339Nano) |
| 167 | + return render.WriteJSON(out, m) |
| 168 | + case render.FormatYAML: |
| 169 | + m := planJSONModel(env, dsn, pl) |
| 170 | + m["applied"] = true |
| 171 | + m["appliedAt"] = at.Format(time.RFC3339Nano) |
| 172 | + return render.WriteYAML(out, m) |
| 173 | + default: |
| 174 | + _, err := fmt.Fprintf(out, "Environment: %s\nState: %s\n\nApply complete. (%d added, %d changed, %d deleted)\n", env, dsn, c, u, d) |
| 175 | + return err |
| 176 | + } |
| 177 | +} |
0 commit comments