Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 191 additions & 0 deletions internal/cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8770,3 +8770,194 @@ func TestRefreshPersistsToKeychain(t *testing.T) {
t.Errorf("AccessToken = %q, want the refreshed token persisted", creds.AccessToken)
}
}

func TestFlagUpdateUndoHint(t *testing.T) {
// 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)
}
}
}
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; "{api}" stands for the fake server's URL
}{
{
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: "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"},
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",
},
{
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) {
// Given
f := flagUpdateEnv(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
stdout, stderr, err := runSplit("", append(args, "--yes")...)

// Then
if err != nil {
t.Fatalf("%v: %v\nstderr: %s", tc.args, err, stderr)
}
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)

// When
stdout, stderr, err := runSplit("", "flag", "update", "no_such_feature", "--enable", "--yes")

// Then
if err == nil {
t.Fatalf("want an error, got stderr %s", stderr)
}
if got := undoLine(t, stdout, stderr); got != "" {
t.Errorf("undo = %q after a failed update, want none", got)
}
})
}

func TestUndoValueArgs(t *testing.T) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// Given stored values of each type, including ones a --value can't restate
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 {
// 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)
}
}
}
5 changes: 5 additions & 0 deletions internal/cmd/flag_identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 4 additions & 0 deletions internal/cmd/flag_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

resp, err := cred.client().UpdateFlag(cmd.Context(), env.APIKey, feature.ID, req)
if err != nil {
return err
Expand All @@ -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
Expand Down
152 changes: 152 additions & 0 deletions internal/cmd/undo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
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) {
var target []string
if segmentID != 0 {
target = []string{"--segment", strconv.Itoa(segmentID)}
}
scope := scopeArgs(cmd, target...)
if segmentID != 0 && before == nil {
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) && enabled != m.enable {
if enabled {
args = append(args, "--enable")
} else {
args = append(args, "--disable")
}
}
if m.setValue && !sameAsRequested(value) {
restore, ok := valueArgs(value)
if !ok {
return "", false
}
args = append(args, restore...)
}
if priority != nil {
args = append(args, "--priority", strconv.Itoa(*priority))
}
if len(args) == 4+len(scope) {
return "", false // nothing changed that needs reverting
}
return strings.Join(args, " "), true
}

// 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{"api-url", "organisation", "project", "environment"} {
if f := cmd.Flags().Lookup(name); f != nil && f.Changed {
args = append(args, "--"+name, shellQuote(f.Value.String()))
}
}
return append(args, target...)
}

// 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)
}
}