cobra icon indicating copy to clipboard operation
cobra copied to clipboard

expose ValidateRequiredFlags and ValidateFlagGroups

Open jinlohwu opened this issue 2 years ago • 3 comments

Hi, dear reviewers,

In my project, there is one complex command with a lot of flags, we need to set part of them as required, and other flags are optional, all optional flags were defined from an API server. I have implemented this feature to add dynamic flags in issue #1758. as talked with @marckhouzam in the last issue, it looks like my method is on the right way.

In the next work, I add some flags in init() function and call MarkFlagRequired to mark them as required flags. but, because I have set DisableFlagParsing as true, and need to call func (c *Command) ParseFlags(args []string) error to parse all flags manually, the function which validates the required flag will not be called.

for now, I have to set up a map and store all required flags, then check if exist in arguments one bye one before ParseFlags(). It works but looks not graceful.

I went through the source code of Cobra, and it looks like I need to call validateRequiredFlags() and validateFlagGroups() manually after ParseFlags(args []string), and function validateRequiredFlags() was called by Execute(), so I created this PR to expose these two functions.

Thx for reviewing this PR.

B&R, Skeet

jinlohwu avatar Jul 21 '22 02:07 jinlohwu

CLA assistant check
All committers have signed the CLA.

CLAassistant avatar Jul 21 '22 02:07 CLAassistant

The Cobra project currently lacks enough contributors to adequately respond to all PRs. 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 PR is closed. You can:
  • Make a comment to remove the stale label and show your support. The 60 days reset. - If a PR has lifecycle/rotten and is closed, comment and ask maintainers if they'd be interseted in reopening.

github-actions[bot] avatar Sep 20 '22 00:09 github-actions[bot]

Hi, exposing these two functions is more convenient and does not conflict with other parts. I have changed it in my local workspace, it works well. please help to review.

jinlohwu avatar Sep 20 '22 01:09 jinlohwu

This seems reasonable to give users more flexibility in handling flags.

marckhouzam avatar Sep 23 '22 12:09 marckhouzam

@marckhouzam thx for reviewing and helping to merge the code. I feel so glad to contribute code to a so popular project. 😃

jinlohwu avatar Sep 28 '22 05:09 jinlohwu