@@ -2,11 +2,11 @@ package cmd
22
33import (
44 "fmt"
5- "strings"
65 "sort"
6+ "strings"
77
8- "github.com/spf13/cobra"
98 "github.com/lets-cli/lets/set"
9+ "github.com/spf13/cobra"
1010)
1111
1212// newRootCmd represents the base command when called without any subcommands.
@@ -60,6 +60,36 @@ func PrintHelpMessage(cmd *cobra.Command) error {
6060 return err
6161}
6262
63+ func maxCommandNameLen (cmd * cobra.Command ) int {
64+ maxLen := 0
65+
66+ for _ , c := range cmd .Commands () {
67+ if l := len (c .Name ()); l > maxLen {
68+ maxLen = l
69+ }
70+ }
71+
72+ return maxLen
73+ }
74+
75+ func rpad (s string , padding int ) string {
76+ formattedString := fmt .Sprintf ("%%-%ds" , padding )
77+ return fmt .Sprintf (formattedString , s )
78+ }
79+
80+ func hasSubgroup (cmd * cobra.Command ) bool {
81+ subgroups := make (map [string ]struct {})
82+ for _ , c := range cmd .Commands () {
83+ if subgroup , ok := c .Annotations ["SubGroupName" ]; ok && subgroup != "" {
84+ subgroups [subgroup ] = struct {}{}
85+ if len (subgroups ) > 1 {
86+ return true
87+ }
88+ }
89+ }
90+ return false
91+ }
92+
6393func buildGroupCommandHelp (cmd * cobra.Command , group * cobra.Group ) string {
6494 help := ""
6595 cmds := []* cobra.Command {}
@@ -71,6 +101,8 @@ func buildGroupCommandHelp(cmd *cobra.Command, group *cobra.Group) string {
71101 }
72102 }
73103
104+ padding := maxCommandNameLen (cmd )
105+
74106 sort .Slice (cmds , func (i , j int ) bool {
75107 return cmds [i ].Name () < cmds [j ].Name ()
76108 })
@@ -88,24 +120,27 @@ func buildGroupCommandHelp(cmd *cobra.Command, group *cobra.Group) string {
88120 sort .Strings (subGroupNameList )
89121
90122 // generate output
91- help += fmt .Sprintf ("%s\n " , group .Title )
123+ help += group .Title + "\n "
124+
125+ intend := ""
126+ if hasSubgroup (cmd ) {
127+ intend = " "
128+ }
92129
93130 for _ , subgroupName := range subGroupNameList {
94- intend := ""
95131 if len (subGroupNameList ) > 1 {
96132 help += fmt .Sprintf ("\n %s\n " , subgroupName )
97- intend = " "
98133 }
99134 for _ , c := range cmds {
100135 if subgroup , ok := c .Annotations ["SubGroupName" ]; ok && subgroup == subgroupName {
101- help += fmt .Sprintf ("%s %-*s %s\n " , intend , cmd . NamePadding (), c .Name (), c .Short )
136+ help += fmt .Sprintf (" %s%s %s\n " , intend , rpad ( c .Name (), padding ), c .Short )
102137 }
103138 }
104139 }
105140
106141 for _ , c := range cmds {
107142 if _ , ok := c .Annotations ["SubGroupName" ]; ! ok {
108- help += fmt .Sprintf (" %-*s %s\n " , cmd . NamePadding (), c .Name (), c .Short )
143+ help += fmt .Sprintf (" %s%s %s\n " , rpad ( c .Name (), padding ), intend , c .Short )
109144 }
110145 }
111146
@@ -114,7 +149,6 @@ func buildGroupCommandHelp(cmd *cobra.Command, group *cobra.Group) string {
114149 return help
115150}
116151
117-
118152func PrintRootHelpMessage (cmd * cobra.Command ) error {
119153 help := ""
120154 help = fmt .Sprintf ("%s\n \n %s" , cmd .Short , help )
0 commit comments