Test and docs for TextUnmarshaler and json.Unmarshaler.

This commit is contained in:
Alec Thomas
2020-01-10 12:15:38 +11:00
parent d4df212f82
commit 01b720cb19
4 changed files with 46 additions and 4 deletions
+5 -1
View File
@@ -392,7 +392,11 @@ specifies the element type. For maps, the tag has the format
<a id="markdown-custom-decoders-mappers" name="custom-decoders-mappers"></a>
## Custom decoders (mappers)
If a field implements the [MapperValue](https://godoc.org/github.com/alecthomas/kong#MapperValue)
Any field implementing `encoding.TextUnmarshaler` or `json.Unmarshaler` will use those interfaces
for decoding values.
For more fine-grained control, if a field implements the
[MapperValue](https://godoc.org/github.com/alecthomas/kong#MapperValue)
interface it will be used to decode arguments into the field.
<a id="markdown-supported-tags" name="supported-tags"></a>
-1
View File
@@ -2,7 +2,6 @@ module github.com/alecthomas/kong
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/mitchellh/mapstructure v1.1.2
github.com/pkg/errors v0.8.1
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.2.2
-2
View File
@@ -1,7 +1,5 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+41
View File
@@ -2,11 +2,13 @@ package kong_test
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"reflect"
"strings"
"testing"
"time"
@@ -28,6 +30,45 @@ func TestValueMapper(t *testing.T) {
require.Equal(t, "MOO", cli.Flag)
}
type textUnmarshalerValue string
func (m *textUnmarshalerValue) UnmarshalText(text []byte) error {
*m = textUnmarshalerValue(strings.ToUpper(string(text)))
return nil
}
func TestTextUnmarshaler(t *testing.T) {
var cli struct {
Value textUnmarshalerValue
}
p := mustNew(t, &cli)
_, err := p.Parse([]string{"--value=hello"})
require.NoError(t, err)
require.Equal(t, "HELLO", string(cli.Value))
}
type jsonUnmarshalerValue string
func (j *jsonUnmarshalerValue) UnmarshalJSON(text []byte) error {
var v string
err := json.Unmarshal(text, &v)
if err != nil {
return err
}
*j = jsonUnmarshalerValue(strings.ToUpper(v))
return nil
}
func TestJSONUnmarshaler(t *testing.T) {
var cli struct {
Value jsonUnmarshalerValue
}
p := mustNew(t, &cli)
_, err := p.Parse([]string{"--value=hello"})
require.NoError(t, err)
require.Equal(t, "HELLO", string(cli.Value))
}
func TestNamedMapper(t *testing.T) {
var cli struct {
Flag string `type:"moo"`