Commits

Ross Light  committed 8b1d7ca

Add Set.PrintUsage method

  • Participants
  • Parent commits 696c2ae

Comments (0)

Files changed (1)

 	return nil
 }
 
+// PrintUsage prints, to standard error unless configured otherwise, the set
+// name, the commands in the set, and the global flags' defaults.
+func (s *Set) PrintUsage() {
+	f := s.outWriter()
+	fmt.Fprintln(f, s.Name, "[options] COMMAND ...")
+
+	fmt.Fprintln(f)
+	fmt.Fprintln(f, "commands:")
+	var maxLen int
+	for i := range s.Commands {
+		c := &s.Commands[i]
+		if n := len(c.Name); n > maxLen {
+			maxLen = n
+		}
+	}
+	cmdFmt := "  %-"+fmt.Sprint(maxLen)+"s  %s\n"
+	for i := range s.Commands {
+		c := &s.Commands[i]
+		fmt.Fprintf(f, cmdFmt, c.Name, c.Description)
+	}
+
+	if gf := s.GlobalFlags; gf != nil {
+		fmt.Fprintln(f)
+		fset := flag.NewFlagSet(s.Name, flag.ContinueOnError)
+		fset.SetOutput(f)
+		gf(fset)
+		fmt.Fprintln(f, "options:")
+		fmt.Fprintln(f)
+		fset.PrintDefaults()
+	}
+}
+
 // Func is a function that runs a command.  The first element of args must
 // be the command's name as it was invoked.
 type Func func(set *Set, cmd *Command, args []string) error
 func (c *Command) PrintUsage(set *Set, fset *flag.FlagSet) {
 	f := set.outWriter()
 	if c.Synopsis != "" {
-		fmt.Fprintf(f, "%s %s\n\n", set.Name, c.Synopsis)
+		fmt.Fprintf(f, "%s %s\n", set.Name, c.Synopsis)
 	} else {
-		fmt.Fprintf(f, "Usage of %s %s:\n\n", set.Name, c.Name)
+		fmt.Fprintf(f, "Usage of %s %s:\n", set.Name, c.Name)
 	}
 	if c.Description != "" {
-		fmt.Fprint(f, c.Description + "\n\n")
+		fmt.Fprintln(f)
+		fmt.Fprintln(f, c.Description)
 	}
 	if al := c.Aliases; len(al) > 0 {
-		fmt.Fprintf(f, "aliases: %s\n\n", strings.Join(al, ", "))
+		fmt.Fprintln(f)
+		fmt.Fprintln(f, "aliases:", strings.Join(al, ", "))
 	}
 	if fset != nil {
-		fmt.Fprint(f, "options:\n\n")
+		fmt.Fprintln(f)
+		fmt.Fprintln(f, "options:")
+		fmt.Fprintln(f)
 		fset.PrintDefaults()
 	}
 }
 // PrintSynopsis prints, to standard error unless configured otherwise, the
 // command's synopsis.
 func (c *Command) PrintSynopsis(set *Set) {
-	fmt.Fprintf(set.outWriter(), "usage: %s %s\n", set.Name, c.Synopsis)
+	fmt.Fprintln(set.outWriter(), "usage:", set.Name, c.Synopsis)
 }
 
 // summary returns the first line of a string.