Skip to content

Commit

Permalink
add custom flag desc support (#186)
Browse files Browse the repository at this point in the history
  • Loading branch information
vipcxj committed Feb 4, 2024
1 parent 3fcf1a0 commit 8d76a1d
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 8 deletions.
6 changes: 4 additions & 2 deletions load.go
Expand Up @@ -149,8 +149,10 @@ func (c *Config) LoadFlags(keys []string) (err error) {

// bind vars
for _, key := range keys {
key, typ := parseVarNameAndType(key)
desc := "config flag " + key
key, typ, desc := parseVarNameAndType(key)
if desc == "" {
desc = "config flag " + key
}

switch typ {
case "int":
Expand Down
8 changes: 7 additions & 1 deletion load_test.go
@@ -1,6 +1,7 @@
package config

import (
"flag"
"os"
"reflect"
"runtime"
Expand Down Expand Up @@ -166,10 +167,11 @@ func TestLoadFlags(t *testing.T) {
"--name", "inhere",
"--unknownTyp", "val",
"--debug",
"--desc=abc",
}

// load flag info
keys := []string{"name", "env", "debug:bool", "age:int", "var0:uint", "unknownTyp:notExist"}
keys := []string{"name", "env", "debug:bool", "age:int", "var0:uint", "unknownTyp:notExist", "desc:string:This is a custom description: abc"}
err := LoadFlags(keys)
is.Nil(err)
is.Eq("inhere", c.String("name", ""))
Expand All @@ -179,6 +181,10 @@ func TestLoadFlags(t *testing.T) {
is.Eq(uint(20), c.Uint("not-exist", uint(20)))
is.Eq("val", c.Get("unknownTyp"))
is.True(c.Bool("debug", false))
is.Eq("abc", c.String("desc"))
descFlag := flag.Lookup("desc")
is.NotNil(descFlag)
is.Eq("This is a custom description: abc", descFlag.Usage)

// set sub key
c = New("flag")
Expand Down
2 changes: 1 addition & 1 deletion testdata/issues59.ini
@@ -1,4 +1,4 @@
; exported at 2024-01-13 12:00:15
; exported at 2024-02-02 12:16:14

age = 123
baseKey = value
Expand Down
11 changes: 7 additions & 4 deletions util.go
Expand Up @@ -134,20 +134,23 @@ func Getenv(name string, defVal ...string) (val string) {
return
}

func parseVarNameAndType(key string) (string, string) {
func parseVarNameAndType(key string) (string, string, string) {
typ := "string"
key = strings.Trim(key, "-")

var desc string
// can set var type: int, uint, bool
if strings.IndexByte(key, ':') > 0 {
list := strings.SplitN(key, ":", 2)
list := strings.SplitN(key, ":", 3)
key, typ = list[0], list[1]
if len(list) == 3 {
desc = list[2]
}

if _, ok := validTypes[typ]; !ok {
typ = "string"
}
}
return key, typ
return key, typ, desc
}

// format key
Expand Down

0 comments on commit 8d76a1d

Please sign in to comment.