clidocgen: Support nested commands properly (#58)

This commit is contained in:
Nils Hanke 2022-09-05 10:34:46 +02:00 committed by GitHub
parent f8c01a0298
commit 2dfa591c41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -29,7 +29,10 @@ func main() {
body := &bytes.Buffer{}
for _, c := range allSubCommands(rootCmd) {
name := c.Name()
fmt.Fprintf(cmdList, "* [%v](#constellation-%v): %v\n", name, name, c.Short)
fullName, level := determineFullNameAndLevel(c)
// First two arguments are used to create indentation for nested commands (2 spaces per level).
fmt.Fprintf(cmdList, "%*s* [%v](#constellation-%v): %v\n", 2*level, "", name, fullName, c.Short)
if err := doc.GenMarkdown(c, body); err != nil {
panic(err)
}
@ -49,3 +52,15 @@ func allSubCommands(cmd *cobra.Command) []*cobra.Command {
}
return all
}
func determineFullNameAndLevel(cmd *cobra.Command) (string, int) {
// Traverse the command tree upwards and determine the full name and level of the command.
name := cmd.Name()
level := 0
for cmd.HasParent() && cmd.Parent().Name() != "constellation" {
cmd = cmd.Parent()
name = cmd.Name() + "-" + name // Use '-' as separator since we pipe it into a Markdown link.
level++
}
return name, level
}