From b877edc0dbc314d8f68ad59c0f2efd1259bbfe2e Mon Sep 17 00:00:00 2001 From: Vikram Singh Date: Fri, 27 Nov 2026 14:28:05 +0530 Subject: [PATCH 1/2] feat: Print an undo command after a flag change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After flag update, flag enable or flag disable succeeds, print the command that puts the flag back, on stderr under the confirmation: ✓ Set max_items to 30 in environment Production (…) Undo: flagsmith flag update max_items --value 25 It is worked out from the state read before the write. A new segment override is undone with flag delete --segment. An explicit --project or --environment is repeated so the command works from anywhere. No hint is printed when the previous state can't be restated as a command (an unset value, re-weighted variants) or when nothing changed. Part of #65. --- internal/cmd/cmd_test.go | 129 ++++++++++++++++++++++++++++++++++++ internal/cmd/flag_update.go | 4 ++ internal/cmd/undo.go | 107 ++++++++++++++++++++++++++++++ 3 files changed, 240 insertions(+) create mode 100644 internal/cmd/undo.go diff --git a/internal/cmd/cmd_test.go b/internal/cmd/cmd_test.go index 8e6b338..e4e80b6 100644 --- a/internal/cmd/cmd_test.go +++ b/internal/cmd/cmd_test.go @@ -8770,3 +8770,132 @@ func TestRefreshPersistsToKeychain(t *testing.T) { t.Errorf("AccessToken = %q, want the refreshed token persisted", creds.AccessToken) } } + +func TestFlagUpdateUndoHint(t *testing.T) { + undoLine := func(out string) string { + for _, line := range strings.Split(out, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "Undo: ") { + return strings.TrimPrefix(strings.TrimSpace(line), "Undo: ") + } + } + return "" + } + cases := []struct { + name string + setup func(f *fakeInstance) + args []string + want string // "" = no hint + }{ + { + name: "enable restores the previous enabled state", + args: []string{"flag", "enable", "max_items"}, + want: "flagsmith flag update max_items --disable", + }, + { + name: "a value change restores the previous value", + args: []string{"flag", "update", "max_items", "--value", "30"}, + want: "flagsmith flag update max_items --value 25", + }, + { + name: "an explicit environment is repeated", + args: []string{"flag", "update", "max_items", "--enable", "--environment", "WqXhZk8sVY3dGgTqZ9pJmN"}, + want: "flagsmith flag update max_items --environment WqXhZk8sVY3dGgTqZ9pJmN --disable", + }, + { + name: "no hint when the previous value was unset", + args: []string{"flag", "update", "onboarding_banner", "--value", "hi"}, + want: "", + }, + { + name: "no hint when nothing changed", + args: []string{"flag", "enable", "onboarding_banner"}, + want: "", + }, + { + name: "a segment override restores its previous value", + setup: func(f *fakeInstance) { + withSegmentOverride(f, true) + withFeatureSegments(f, 2, map[string]any{"id": 1200, "segment": 12, "segment_name": "powerusers", "priority": 1, "environment": 1}) + }, + args: []string{"flag", "update", "max_items", "--segment", "12", "--value", "new"}, + want: "flagsmith flag update max_items --segment 12 --value special", + }, + { + name: "a priority move restores the previous priority", + setup: func(f *fakeInstance) { + withSegmentOverride(f, true) + f.features["101"][0]["num_segment_overrides"] = 2 + withFeatureSegments(f, 2, + map[string]any{"id": 1199, "segment": 9, "segment_name": "beta", "priority": 0, "environment": 1}, + map[string]any{"id": 1200, "segment": 12, "segment_name": "powerusers", "priority": 1, "environment": 1}, + ) + }, + args: []string{"flag", "update", "max_items", "--segment", "12", "--priority", "0"}, + want: "flagsmith flag update max_items --segment 12 --priority 1", + }, + { + name: "a new segment override is undone by deleting it", + setup: func(f *fakeInstance) { + withSegmentOverride(f, false) + withFeatureSegments(f, 2, map[string]any{"id": 1200, "segment": 12, "segment_name": "powerusers", "priority": 0}) + }, + args: []string{"flag", "update", "max_items", "--segment", "7", "--enable"}, + want: "flagsmith flag delete max_items --segment 7", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + // Given + f := flagUpdateEnv(t) + if tc.setup != nil { + tc.setup(f) + } + + // When + out, err := run("", append(tc.args, "--yes")...) + + // Then + if err != nil { + t.Fatalf("%v: %v\noutput: %s", tc.args, err, out) + } + if got := undoLine(out); got != tc.want { + t.Errorf("undo = %q, want %q\noutput: %s", got, tc.want, out) + } + }) + } + + t.Run("no hint when the update fails", func(t *testing.T) { + flagUpdateEnv(t) + out, err := run("", "flag", "update", "no_such_feature", "--enable", "--yes") + if err == nil { + t.Fatalf("want an error, got output %s", out) + } + if got := undoLine(out); got != "" { + t.Errorf("undo = %q after a failed update, want none", got) + } + }) +} + +func TestUndoValueArgs(t *testing.T) { + cases := []struct { + in any + want string + ok bool + }{ + {true, "--value true", true}, + {float64(25), "--value 25", true}, + {float64(2.5), "", false}, + {"hello", "--value hello", true}, + {"42", "--value 42 --type string", true}, + {"false", "--value false --type string", true}, + {"two words", "--value 'two words'", true}, + {"it's", `--value 'it'\''s'`, true}, + {nil, "", false}, + } + for _, tc := range cases { + args, ok := valueArgs(tc.in) + if got := strings.Join(args, " "); ok != tc.ok || got != tc.want { + t.Errorf("valueArgs(%#v) = %q, %v; want %q, %v", tc.in, got, ok, tc.want, tc.ok) + } + } +} diff --git a/internal/cmd/flag_update.go b/internal/cmd/flag_update.go index 9c5696b..0028b41 100644 --- a/internal/cmd/flag_update.go +++ b/internal/cmd/flag_update.go @@ -294,6 +294,9 @@ func applyFlagMutation(cmd *cobra.Command, name string, m flagMutation) error { return err } + // Worked out from the state before the write, printed once it succeeds. + undo, undoOK := undoFlagMutation(cmd, name, segmentID, target, meta.priority, m) + resp, err := cred.client().UpdateFlag(cmd.Context(), env.APIKey, feature.ID, req) if err != nil { return err @@ -314,6 +317,7 @@ func applyFlagMutation(cmd *cobra.Command, name string, m flagMutation) error { if m.setPriority { output.Success(errOut, "Set %s priority to %d %s", name, m.priority, scope) } + printUndo(cmd, undo, undoOK) // Result model: an update also prints the resulting resource to stdout. The // response carries the flag's whole state in the environment, so the detail diff --git a/internal/cmd/undo.go b/internal/cmd/undo.go new file mode 100644 index 0000000..b062511 --- /dev/null +++ b/internal/cmd/undo.go @@ -0,0 +1,107 @@ +package cmd + +import ( + "fmt" + "math" + "regexp" + "strconv" + "strings" + + "github.com/spf13/cobra" + + "github.com/Flagsmith/flagsmith-cli/v2/internal/api" +) + +// undoFlagMutation returns the command that reverts m, given the state it +// changed (before is nil when m creates a segment override). It returns false +// when the previous state can't be restated as a command — an unset value, or +// re-weighted variants — so that no hint is better than a wrong one. +func undoFlagMutation(cmd *cobra.Command, name string, segmentID int, before *api.FeatureState, prevPriority int, m flagMutation) (string, bool) { + scope := scopeArgs(cmd, segmentID) + if segmentID != 0 && before == nil { + return strings.Join(append([]string{"flagsmith", "flag", "delete", shellQuote(name)}, scope...), " "), true + } + if before == nil || len(m.weights) > 0 { + return "", false + } + + args := []string{"flagsmith", "flag", "update", shellQuote(name)} + args = append(args, scope...) + if (m.enable || m.disable) && before.Enabled != m.enable { + if before.Enabled { + args = append(args, "--enable") + } else { + args = append(args, "--disable") + } + } + if m.setValue { + value, ok := valueArgs(before.Value) + if !ok { + return "", false + } + args = append(args, value...) + } + if m.setPriority && prevPriority != m.priority { + args = append(args, "--priority", strconv.Itoa(prevPriority)) + } + if len(args) == 4+len(scope) { + return "", false // nothing changed that needs reverting + } + return strings.Join(args, " "), true +} + +// scopeArgs repeats the targeting the user gave explicitly, so the undo command +// hits the same project, environment and override from any directory. +func scopeArgs(cmd *cobra.Command, segmentID int) []string { + var args []string + for _, name := range []string{"project", "environment"} { + if f := cmd.Flags().Lookup(name); f != nil && f.Changed { + args = append(args, "--"+name, shellQuote(f.Value.String())) + } + } + if segmentID != 0 { + args = append(args, "--segment", strconv.Itoa(segmentID)) + } + return args +} + +// valueArgs restates a stored flag value as --value (and --type when inference +// would read it differently). A flag with no value can't be restored this way. +func valueArgs(v any) ([]string, bool) { + switch v := v.(type) { + case bool: + return []string{"--value", strconv.FormatBool(v)}, true + case float64: + if v != math.Trunc(v) || math.Abs(v) > 1<<53 { + return nil, false + } + return []string{"--value", strconv.FormatInt(int64(v), 10)}, true + case int: + return []string{"--value", strconv.Itoa(v)}, true + case string: + args := []string{"--value", shellQuote(v)} + if inferred, _ := inferFeatureValue(v, ""); inferred.Type != "string" { + args = append(args, "--type", "string") + } + return args, true + default: + return nil, false + } +} + +var shellSafe = regexp.MustCompile(`^[A-Za-z0-9_./:@%+=,-]+$`) + +// shellQuote returns s ready to paste into a POSIX shell. +func shellQuote(s string) string { + if shellSafe.MatchString(s) { + return s + } + return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" +} + +// printUndo writes the undo hint after a successful mutation. +func printUndo(cmd *cobra.Command, undo string, ok bool) { + if ok { + fmt.Fprintf(cmd.ErrOrStderr(), " Undo: %s\n", undo) + } +} From 026137fadc80e386c56083b0e71ebfa8ff272f80 Mon Sep 17 00:00:00 2001 From: Vikram Singh Date: Tue, 1 Dec 2026 08:20:17 +0530 Subject: [PATCH 2/2] fix: Cover identity overrides and explicit context in undo hints - Repeat an explicit --api-url and --organisation in the undo command. - Print no hint when --value sets the value it already had. - Print undo hints for --identifier updates: a new override is undone by deleting it, an existing one by restoring its state. - Assert the hint is on stderr, after the confirmation lines. - Add Given/When/Then sections to TestUndoValueArgs. --- internal/cmd/cmd_test.go | 88 +++++++++++++++++++++++++++++------ internal/cmd/flag_identity.go | 5 ++ internal/cmd/undo.go | 79 ++++++++++++++++++++++++------- 3 files changed, 142 insertions(+), 30 deletions(-) diff --git a/internal/cmd/cmd_test.go b/internal/cmd/cmd_test.go index e4e80b6..c245642 100644 --- a/internal/cmd/cmd_test.go +++ b/internal/cmd/cmd_test.go @@ -8772,19 +8772,36 @@ func TestRefreshPersistsToKeychain(t *testing.T) { } func TestFlagUpdateUndoHint(t *testing.T) { - undoLine := func(out string) string { - for _, line := range strings.Split(out, "\n") { - if strings.HasPrefix(strings.TrimSpace(line), "Undo: ") { - return strings.TrimPrefix(strings.TrimSpace(line), "Undo: ") + // undoLine returns the hint from stderr, and checks it comes after the + // confirmation (✓) lines and never on stdout, which carries the result. + undoLine := func(t *testing.T, stdout, stderr string) string { + t.Helper() + if strings.Contains(stdout, "Undo: ") { + t.Errorf("undo hint on stdout, want stderr only:\n%s", stdout) + } + hint, ticks := "", 0 + for _, line := range strings.Split(stderr, "\n") { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "Undo: "): + hint = strings.TrimPrefix(line, "Undo: ") + case strings.HasPrefix(line, "✓"): + ticks++ + if hint != "" { + t.Errorf("confirmation %q printed after the undo hint", line) + } } } - return "" + if hint != "" && ticks == 0 { + t.Errorf("undo hint without a confirmation line:\n%s", stderr) + } + return hint } cases := []struct { name string setup func(f *fakeInstance) args []string - want string // "" = no hint + want string // "" = no hint; "{api}" stands for the fake server's URL }{ { name: "enable restores the previous enabled state", @@ -8796,11 +8813,21 @@ func TestFlagUpdateUndoHint(t *testing.T) { args: []string{"flag", "update", "max_items", "--value", "30"}, want: "flagsmith flag update max_items --value 25", }, + { + name: "no hint when the value is set to what it already is", + args: []string{"flag", "update", "max_items", "--value", "25"}, + want: "", + }, { name: "an explicit environment is repeated", args: []string{"flag", "update", "max_items", "--enable", "--environment", "WqXhZk8sVY3dGgTqZ9pJmN"}, want: "flagsmith flag update max_items --environment WqXhZk8sVY3dGgTqZ9pJmN --disable", }, + { + name: "an explicit API host is repeated", + args: []string{"flag", "update", "max_items", "--enable", "--api-url", "{api}"}, + want: "flagsmith flag update max_items --api-url {api} --disable", + }, { name: "no hint when the previous value was unset", args: []string{"flag", "update", "onboarding_banner", "--value", "hi"}, @@ -8842,6 +8869,27 @@ func TestFlagUpdateUndoHint(t *testing.T) { args: []string{"flag", "update", "max_items", "--segment", "7", "--enable"}, want: "flagsmith flag delete max_items --segment 7", }, + { + name: "an identity override restores its previous value", + setup: func(f *fakeInstance) { + f.coreOverrides[501] = map[int]*fakeFS{2: {id: 9001, enabled: true, value: 7}} + }, + args: []string{"flag", "update", "max_items", "--identifier", "user-1", "--value", "42"}, + want: "flagsmith flag update max_items --identifier user-1 --value 7", + }, + { + name: "a new identity override is undone by deleting it", + args: []string{"flag", "update", "max_items", "--identifier", "user-1", "--value", "42"}, + want: "flagsmith flag delete max_items --identifier user-1", + }, + { + name: "a new edge identity override is undone by deleting it", + setup: func(f *fakeInstance) { + withEdgeIdentities(f) + }, + args: []string{"flag", "enable", "max_items", "--identifier", "edge-user"}, + want: "flagsmith flag delete max_items --identifier edge-user", + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -8850,33 +8898,44 @@ func TestFlagUpdateUndoHint(t *testing.T) { if tc.setup != nil { tc.setup(f) } + args := make([]string, 0, len(tc.args)+1) + for _, a := range tc.args { + args = append(args, strings.ReplaceAll(a, "{api}", f.srv.URL)) + } + want := strings.ReplaceAll(tc.want, "{api}", f.srv.URL) // When - out, err := run("", append(tc.args, "--yes")...) + stdout, stderr, err := runSplit("", append(args, "--yes")...) // Then if err != nil { - t.Fatalf("%v: %v\noutput: %s", tc.args, err, out) + t.Fatalf("%v: %v\nstderr: %s", tc.args, err, stderr) } - if got := undoLine(out); got != tc.want { - t.Errorf("undo = %q, want %q\noutput: %s", got, tc.want, out) + if got := undoLine(t, stdout, stderr); got != want { + t.Errorf("undo = %q, want %q\nstderr: %s", got, want, stderr) } }) } t.Run("no hint when the update fails", func(t *testing.T) { + // Given flagUpdateEnv(t) - out, err := run("", "flag", "update", "no_such_feature", "--enable", "--yes") + + // When + stdout, stderr, err := runSplit("", "flag", "update", "no_such_feature", "--enable", "--yes") + + // Then if err == nil { - t.Fatalf("want an error, got output %s", out) + t.Fatalf("want an error, got stderr %s", stderr) } - if got := undoLine(out); got != "" { + if got := undoLine(t, stdout, stderr); got != "" { t.Errorf("undo = %q after a failed update, want none", got) } }) } func TestUndoValueArgs(t *testing.T) { + // Given stored values of each type, including ones a --value can't restate cases := []struct { in any want string @@ -8893,7 +8952,10 @@ func TestUndoValueArgs(t *testing.T) { {nil, "", false}, } for _, tc := range cases { + // When args, ok := valueArgs(tc.in) + + // Then if got := strings.Join(args, " "); ok != tc.ok || got != tc.want { t.Errorf("valueArgs(%#v) = %q, %v; want %q, %v", tc.in, got, ok, tc.want, tc.ok) } diff --git a/internal/cmd/flag_identity.go b/internal/cmd/flag_identity.go index ee1078d..ac54193 100644 --- a/internal/cmd/flag_identity.go +++ b/internal/cmd/flag_identity.go @@ -155,6 +155,10 @@ func runIdentityUpdate(cmd *cobra.Command, cred *activeCredential, env api.Envir return err } + // Worked out from the state before the write, printed once it succeeds. + undo, undoOK := undoIdentityMutation(cmd, feature.Name, identifier, current, + flagMutation{enable: enable, disable: disable, setValue: setValue}) + if edge { err = cred.client().SetEdgeIdentityOverride(cmd.Context(), env.APIKey, identifier, feature.ID, enabled, value) } else { @@ -183,6 +187,7 @@ func runIdentityUpdate(cmd *cobra.Command, cred *activeCredential, env api.Envir if disable { output.Success(errOut, "Disabled %s for %s", feature.Name, scope) } + printUndo(cmd, undo, undoOK) // The written override is fully known — both enabled and value were chosen // locally — so the detail renders without re-reading it. diff --git a/internal/cmd/undo.go b/internal/cmd/undo.go index b062511..c0ea74a 100644 --- a/internal/cmd/undo.go +++ b/internal/cmd/undo.go @@ -17,32 +17,62 @@ import ( // when the previous state can't be restated as a command — an unset value, or // re-weighted variants — so that no hint is better than a wrong one. func undoFlagMutation(cmd *cobra.Command, name string, segmentID int, before *api.FeatureState, prevPriority int, m flagMutation) (string, bool) { - scope := scopeArgs(cmd, segmentID) + var target []string + if segmentID != 0 { + target = []string{"--segment", strconv.Itoa(segmentID)} + } + scope := scopeArgs(cmd, target...) if segmentID != 0 && before == nil { - return strings.Join(append([]string{"flagsmith", "flag", "delete", shellQuote(name)}, scope...), " "), true + return deleteOverride(name, scope), true } if before == nil || len(m.weights) > 0 { return "", false } + var priority *int + if m.setPriority && prevPriority != m.priority { + priority = &prevPriority + } + return revertArgs(name, scope, before.Enabled, before.Value, m, priority) +} +// undoIdentityMutation is undoFlagMutation for an identity override: before is +// nil when the update creates the override, which is then undone by deleting +// it. (A core identity created along the way stays; only its override goes.) +func undoIdentityMutation(cmd *cobra.Command, name, identifier string, before *api.IdentityFeatureState, m flagMutation) (string, bool) { + scope := scopeArgs(cmd, "--identifier", shellQuote(identifier)) + if before == nil { + return deleteOverride(name, scope), true + } + return revertArgs(name, scope, before.Enabled, before.Value, m, nil) +} + +func deleteOverride(name string, scope []string) string { + return strings.Join(append([]string{"flagsmith", "flag", "delete", shellQuote(name)}, scope...), " ") +} + +// revertArgs builds the `flag update` that puts back what m changed: the +// enabled state, the value and the priority (nil when unchanged). Properties m +// sets to what they already were are left out; if nothing is left, there is +// nothing to undo. +func revertArgs(name string, scope []string, enabled bool, value any, m flagMutation, priority *int) (string, bool) { args := []string{"flagsmith", "flag", "update", shellQuote(name)} args = append(args, scope...) - if (m.enable || m.disable) && before.Enabled != m.enable { - if before.Enabled { + if (m.enable || m.disable) && enabled != m.enable { + if enabled { args = append(args, "--enable") } else { args = append(args, "--disable") } } - if m.setValue { - value, ok := valueArgs(before.Value) + if m.setValue && !sameAsRequested(value) { + restore, ok := valueArgs(value) if !ok { return "", false } - args = append(args, value...) + args = append(args, restore...) } - if m.setPriority && prevPriority != m.priority { - args = append(args, "--priority", strconv.Itoa(prevPriority)) + if priority != nil { + args = append(args, "--priority", strconv.Itoa(*priority)) } if len(args) == 4+len(scope) { return "", false // nothing changed that needs reverting @@ -50,19 +80,34 @@ func undoFlagMutation(cmd *cobra.Command, name string, segmentID int, before *ap return strings.Join(args, " "), true } -// scopeArgs repeats the targeting the user gave explicitly, so the undo command -// hits the same project, environment and override from any directory. -func scopeArgs(cmd *cobra.Command, segmentID int) []string { +// sameAsRequested reports whether the stored value v already equals the +// --value (and --type) being written, compared as the arguments that would +// restore it. +func sameAsRequested(v any) bool { + fv, err := inferFeatureValue(flagValueFlag, flagTypeFlag) + if err != nil { + return false + } + requested, err := nativeScalar(fv) + if err != nil { + return false + } + have, okHave := valueArgs(v) + want, okWant := valueArgs(requested) + return okHave && okWant && strings.Join(have, " ") == strings.Join(want, " ") +} + +// scopeArgs repeats the context the user gave explicitly — API host, +// organisation, project, environment — followed by target (the override), so +// the undo command hits the same flag from any directory. +func scopeArgs(cmd *cobra.Command, target ...string) []string { var args []string - for _, name := range []string{"project", "environment"} { + for _, name := range []string{"api-url", "organisation", "project", "environment"} { if f := cmd.Flags().Lookup(name); f != nil && f.Changed { args = append(args, "--"+name, shellQuote(f.Value.String())) } } - if segmentID != 0 { - args = append(args, "--segment", strconv.Itoa(segmentID)) - } - return args + return append(args, target...) } // valueArgs restates a stored flag value as --value (and --type when inference