cobra icon indicating copy to clipboard operation
cobra copied to clipboard

custom flag in-order processing

Open duglin opened this issue 2 years ago • 2 comments

I want to be able to support something like this:

app --min=1 --max=5
or
app --range=1:5
or
app --min=2  --range=1:10 --max=5

Meaning, there's a min and max value that can be set independently, or the user can use a short cut (--range) to set both at the same time via --range 1:5. However, I need it to be ordered. So, in the final case the processing would be:

  • set min to 2
  • set min to 1 and max to 10
  • set max to 5

if I were to only see the --range flag after all other flags were processed I wouldn't know that --max actually overrode what --range set.

Is there a way to define a func/callback that will be called at the time that --range is seen by cobra so I can do my custom logic for it at the appropriate time?

duglin avatar Sep 02 '22 20:09 duglin

So you want to have different flags setting the same underlying values but with an implicit priority involved?

Just a suggestion but I think it may be easier to simply use the new features for defining those flags as conflicting so they can't be defined at the same time. Define one set (min/max) or the other (range) but not both.

If you really want to do what youre describing and need the hook; I think there is another existing issue or two about wishing there were more clear hooks for this sort of thing (I think there are some but there are some edge cases if I remember correctly).

I think a simple solution that I've used before (prior to the flag group logic I described above) is to add a persistent pre-run that applies the cross-flag logic.

johnSchnake avatar Sep 07 '22 12:09 johnSchnake

yup - a hook that allows me to do custom logic when the flag.Set() is called is basically what I want. Then it would be called in the order in which the args are processed (I assume).

Your suggestion is to use MarkFlagsMutuallyExclusive right? But, to make sure I understand it, I think I'd need to call it twice, once for "scale+min" and once for "scale+max" since I do want to allow min+max at the same time. Do I have that right?

thanks!!

duglin avatar Sep 07 '22 14:09 duglin

The Cobra project currently lacks enough contributors to adequately respond to all issues. This bot triages issues and PRs according to the following rules:

  • After 60d of inactivity, lifecycle/stale is applied. - After 30d of inactivity since lifecycle/stale was applied, lifecycle/rotten is applied and the issue is closed. You can:
  • Make a comment to remove the stale label and show your support. The 60 days reset. - If an issue has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening

github-actions[bot] avatar Nov 07 '22 00:11 github-actions[bot]