Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Incorrect behavior when restoring default value of slice type flags. #14

Open
sagan opened this issue May 15, 2024 · 1 comment
Open

Comments

@sagan
Copy link

sagan commented May 15, 2024

If PersistFlagValues is false, cobra-prompt restore all flags to default value after every command execution.

cobra-prompt.go

func findSuggestions(co *CobraPrompt, d *prompt.Document) []prompt.Suggest {
	//...
	addFlags := func(flag *pflag.Flag) {
		if flag.Changed && !persistFlagValues {
			flag.Value.Set(flag.DefValue)
		}
		//...
	}
	//...
}

However, if the flag is a SliceValue (e.g. []string), the flag.DefValue is the result of value.String(), which basically is a csv enclaved in "[]", e.g. [foo,bar]. Also, the Set(value string) method of SliceValue will only append the value to existing array. To set the whole flag values to new array, Replace method should be used instead.

To handle slice flags correctly, I suggest make the following changes:

import "encoding/csv"

func findSuggestions(co *CobraPrompt, d *prompt.Document) []prompt.Suggest {
	//...
	addFlags := func(flag *pflag.Flag) {
		if flag.Changed && !persistFlagValues {
			if sv, ok := flag.Value.(pflag.SliceValue); ok {
				// flag.DefValue is  "[" + writeAsCSV(values) + "]"
				stringReader := strings.NewReader(flag.DefValue[1 : len(flag.DefValue)-1])
				csvReader := csv.NewReader(stringReader)
				values, err := csvReader.Read()
				if err == nil {
					sv.Replace(values)
				}
			} else {
				flag.Value.Set(flag.DefValue)
			}
		}
		//...
	}
	//...
}
@avirtopeanu-ionos
Copy link

This should be fixed in this fork https://github.com/ionoscloudsdk/comptplus

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants