浏览代码

use tabwriter to display usage in mflag

Docker-DCO-1.1-Signed-off-by: Victor Vieux <vieux@docker.com> (github: vieux)
Victor Vieux 11 年之前
父节点
当前提交
77098d5b5b
共有 2 个文件被更改,包括 22 次插入8 次删除
  1. 8 5
      pkg/mflag/example/example.go
  2. 14 3
      pkg/mflag/flag.go

+ 8 - 5
pkg/mflag/example/example.go

@@ -2,6 +2,7 @@ package main
 
 import (
 	"fmt"
+
 	flag "github.com/dotcloud/docker/pkg/mflag"
 )
 
@@ -19,15 +20,17 @@ func init() {
 	flag.IntVar(&i, []string{"-integer", "-number"}, -1, "a simple integer")
 	flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage
 	flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help")
+	flag.StringVar(&str, []string{"mode"}, "mode1", "set the mode\nmode1: use the mode1\nmode2: use the mode2\nmode3: use the mode3")
 	flag.Parse()
 }
 func main() {
 	if h {
 		flag.PrintDefaults()
+	} else {
+		fmt.Printf("s/#hidden/-string: %s\n", str)
+		fmt.Printf("b: %b\n", b)
+		fmt.Printf("-bool: %b\n", b2)
+		fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String())
+		fmt.Printf("ARGS: %v\n", flag.Args())
 	}
-	fmt.Printf("s/#hidden/-string: %s\n", str)
-	fmt.Printf("b: %b\n", b)
-	fmt.Printf("-bool: %b\n", b2)
-	fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String())
-	fmt.Printf("ARGS: %v\n", flag.Args())
 }

+ 14 - 3
pkg/mflag/flag.go

@@ -83,6 +83,7 @@ import (
 	"sort"
 	"strconv"
 	"strings"
+	"text/tabwriter"
 	"time"
 )
 
@@ -419,11 +420,12 @@ func Set(name, value string) error {
 // PrintDefaults prints, to standard error unless configured
 // otherwise, the default values of all defined flags in the set.
 func (f *FlagSet) PrintDefaults() {
+	writer := tabwriter.NewWriter(f.out(), 20, 1, 3, ' ', 0)
 	f.VisitAll(func(flag *Flag) {
-		format := "  -%s=%s: %s\n"
+		format := "  -%s=%s"
 		if _, ok := flag.Value.(*stringValue); ok {
 			// put quotes on the value
-			format = "  -%s=%q: %s\n"
+			format = "  -%s=%q"
 		}
 		names := []string{}
 		for _, name := range flag.Names {
@@ -432,9 +434,18 @@ func (f *FlagSet) PrintDefaults() {
 			}
 		}
 		if len(names) > 0 {
-			fmt.Fprintf(f.out(), format, strings.Join(names, ", -"), flag.DefValue, flag.Usage)
+			fmt.Fprintf(writer, format, strings.Join(names, ", -"), flag.DefValue)
+			for i, line := range strings.Split(flag.Usage, "\n") {
+				if i != 0 {
+					line = "  " + line
+				}
+				fmt.Fprintln(writer, "\t", line)
+			}
+			//			start := fmt.Sprintf(format, strings.Join(names, ", -"), flag.DefValue)
+			//			fmt.Fprintln(f.out(), start, strings.Replace(flag.Usage, "\n", "\n"+strings.Repeat(" ", len(start)+1), -1))
 		}
 	})
+	writer.Flush()
 }
 
 // PrintDefaults prints to standard error the default values of all defined command-line flags.