Skip to content

Commit

Permalink
aliases uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
ariary committed Oct 27, 2023
1 parent 2615d17 commit 52b90cb
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
2 changes: 1 addition & 1 deletion examples/sayhello_subcommand.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func main() {
Subcommands: q.Subcommands{
{Name: "color", Aliases: q.Aliases("co", "x"), Description: "print coloured message", Function: Color},
{Name: "toto", Description: "??", Function: Toto},
{Name: "馃敟", Description: "try me", Function: Titi},
{Name: "馃敟", Aliases: q.Aliases("馃Н"), Description: "try me", Function: Titi},
},
}
cli.RunWithSubcommand()
Expand Down
39 changes: 32 additions & 7 deletions pkg/quicli/subcommand.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ type Subcommands []Subcommand

type SubcommandSet []string

var AllAliases mapset.Set[string]

// RunWithSubcommand: equivalent of Run function when cli has subcommand defined
func (c *Cli) RunWithSubcommand() {
var config Config
Expand Down Expand Up @@ -66,13 +68,9 @@ func (c *Cli) RunWithSubcommand() {

//Subcommands preliminary checks
if len(c.Subcommands) > 0 {
for i := 0; i < len(c.Subcommands); i++ {
sub := c.Subcommands[i]
if sub.Function == nil {
fmt.Println(QUICLI_ERROR_PREFIX+"subcommand", sub.Name, "does not defined mandatory 'Function' attribute")
os.Exit(2)
}
}
checkSubcommandFunctionIsDefined(c)
AllAliases = mapset.NewSet[string]()
checkSubcommandAliasesUniqueness(c)
}

//flags
Expand Down Expand Up @@ -269,3 +267,30 @@ func createFloatFlagFs(cfg Config, f Flag, shorts *[]string, wUsage *tabwriter.W
}
cfg.Flags[name] = &floatPtr
}

// checkSubcommandFunctionIsDefined: assert the subcommmand Function is filled, exit otherwise
func checkSubcommandFunctionIsDefined(c *Cli) {
for i := 0; i < len(c.Subcommands); i++ {
sub := c.Subcommands[i]
if sub.Function == nil {
fmt.Println(QUICLI_ERROR_PREFIX+"subcommand", sub.Name, "does not define mandatory 'Function' attribute")
os.Exit(2)
}
}
}

// checkSubcommandFunctionIsDefined: assert the subcommmand Aliases are unique (ie not same alias for two different subcommands), exit otherwise
func checkSubcommandAliasesUniqueness(c *Cli) {
for i := 0; i < len(c.Subcommands); i++ {
subcommandAliases := c.Subcommands[i].Aliases
if subcommandAliases != nil {
commonAliases := AllAliases.Intersect(subcommandAliases)
if commonAliases.Cardinality() == 0 {
AllAliases.Append(subcommandAliases.ToSlice()...)
} else {
fmt.Println(QUICLI_ERROR_PREFIX+"subcommand", c.Subcommands[i].Name, "define some already defined aliases ('", strings.Join(commonAliases.ToSlice(), ","), "')")
os.Exit(2)
}
}
}
}

0 comments on commit 52b90cb

Please sign in to comment.