Commit 034ca39e authored by Rob Pike's avatar Rob Pike

flag: visit the flags in sorted order, for better messages.

Fixes #1601.

R=rsc
CC=golang-dev
https://golang.org/cl/4249070
parent bbad6900
......@@ -68,6 +68,7 @@ package flag
import (
"fmt"
"os"
"sort"
"strconv"
)
......@@ -205,16 +206,34 @@ type allFlags struct {
var flags *allFlags
// VisitAll visits the flags, calling fn for each. It visits all flags, even those not set.
// sortFlags returns the flags as a slice in lexicographical sorted order.
func sortFlags(flags map[string]*Flag) []*Flag {
list := make(sort.StringArray, len(flags))
i := 0
for _, f := range flags {
list[i] = f.Name
i++
}
list.Sort()
result := make([]*Flag, len(list))
for i, name := range list {
result[i] = flags[name]
}
return result
}
// VisitAll visits the flags in lexicographical order, calling fn for each.
// It visits all flags, even those not set.
func VisitAll(fn func(*Flag)) {
for _, f := range flags.formal {
for _, f := range sortFlags(flags.formal) {
fn(f)
}
}
// Visit visits the flags, calling fn for each. It visits only those flags that have been set.
// Visit visits the flags in lexicographical order, calling fn for each.
// It visits only those flags that have been set.
func Visit(fn func(*Flag)) {
for _, f := range flags.actual {
for _, f := range sortFlags(flags.actual) {
fn(f)
}
}
......
......@@ -8,6 +8,7 @@ import (
. "flag"
"fmt"
"os"
"sort"
"testing"
)
......@@ -77,6 +78,12 @@ func TestEverything(t *testing.T) {
t.Log(k, *v)
}
}
// Now test they're visited in sort order.
var flagNames []string
Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
if !sort.StringsAreSorted(flagNames) {
t.Errorf("flag names not sorted: %v", flagNames)
}
}
func TestUsage(t *testing.T) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment