forked from LaconicNetwork/kompose
Update vendoring
This updates the libcompose vendoring as well as a general update to vendoring (adds the latest git commit of libcompose). Closes https://github.com/kubernetes-incubator/kompose/issues/426 Closes https://github.com/kubernetes-incubator/kompose/issues/471
This commit is contained in:
+2
@@ -2,6 +2,8 @@
|
||||
|
||||
package logrus
|
||||
|
||||
import "io"
|
||||
|
||||
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||
func IsTerminal(f io.Writer) bool {
|
||||
return true
|
||||
|
||||
+1
-1
@@ -3,6 +3,7 @@
|
||||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
@@ -10,7 +11,6 @@ import (
|
||||
|
||||
// IsTerminal returns true if the given file descriptor is a terminal.
|
||||
func IsTerminal(f io.Writer) bool {
|
||||
var termios Termios
|
||||
switch v := f.(type) {
|
||||
case *os.File:
|
||||
_, err := unix.IoctlGetTermios(int(v.Fd()), unix.TCGETA)
|
||||
|
||||
+2
-2
@@ -8,8 +8,8 @@
|
||||
package logrus
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"io"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
+28
-12
@@ -49,9 +49,26 @@ type TextFormatter struct {
|
||||
// be desired.
|
||||
DisableSorting bool
|
||||
|
||||
// QuoteEmptyFields will wrap empty fields in quotes if true
|
||||
QuoteEmptyFields bool
|
||||
|
||||
// QuoteCharacter can be set to the override the default quoting character "
|
||||
// with something else. For example: ', or `.
|
||||
QuoteCharacter string
|
||||
|
||||
// Whether the logger's out is to a terminal
|
||||
isTerminal bool
|
||||
terminalOnce sync.Once
|
||||
isTerminal bool
|
||||
|
||||
sync.Once
|
||||
}
|
||||
|
||||
func (f *TextFormatter) init(entry *Entry) {
|
||||
if len(f.QuoteCharacter) == 0 {
|
||||
f.QuoteCharacter = "\""
|
||||
}
|
||||
if entry.Logger != nil {
|
||||
f.isTerminal = IsTerminal(entry.Logger.Out)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
@@ -72,11 +89,7 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
|
||||
prefixFieldClashes(entry.Data)
|
||||
|
||||
f.terminalOnce.Do(func() {
|
||||
if entry.Logger != nil {
|
||||
f.isTerminal = IsTerminal(entry.Logger.Out)
|
||||
}
|
||||
})
|
||||
f.Do(func() { f.init(entry) })
|
||||
|
||||
isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
|
||||
|
||||
@@ -132,7 +145,10 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []strin
|
||||
}
|
||||
}
|
||||
|
||||
func needsQuoting(text string) bool {
|
||||
func (f *TextFormatter) needsQuoting(text string) bool {
|
||||
if f.QuoteEmptyFields && len(text) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, ch := range text {
|
||||
if !((ch >= 'a' && ch <= 'z') ||
|
||||
(ch >= 'A' && ch <= 'Z') ||
|
||||
@@ -155,17 +171,17 @@ func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interf
|
||||
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
|
||||
switch value := value.(type) {
|
||||
case string:
|
||||
if !needsQuoting(value) {
|
||||
if !f.needsQuoting(value) {
|
||||
b.WriteString(value)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%q", value)
|
||||
fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, value, f.QuoteCharacter)
|
||||
}
|
||||
case error:
|
||||
errmsg := value.Error()
|
||||
if !needsQuoting(errmsg) {
|
||||
if !f.needsQuoting(errmsg) {
|
||||
b.WriteString(errmsg)
|
||||
} else {
|
||||
fmt.Fprintf(b, "%q", errmsg)
|
||||
fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, errmsg, f.QuoteCharacter)
|
||||
}
|
||||
default:
|
||||
fmt.Fprint(b, value)
|
||||
|
||||
+19
-10
@@ -11,39 +11,48 @@ func (logger *Logger) Writer() *io.PipeWriter {
|
||||
}
|
||||
|
||||
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
|
||||
return NewEntry(logger).WriterLevel(level)
|
||||
}
|
||||
|
||||
func (entry *Entry) Writer() *io.PipeWriter {
|
||||
return entry.WriterLevel(InfoLevel)
|
||||
}
|
||||
|
||||
func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
|
||||
reader, writer := io.Pipe()
|
||||
|
||||
var printFunc func(args ...interface{})
|
||||
|
||||
switch level {
|
||||
case DebugLevel:
|
||||
printFunc = logger.Debug
|
||||
printFunc = entry.Debug
|
||||
case InfoLevel:
|
||||
printFunc = logger.Info
|
||||
printFunc = entry.Info
|
||||
case WarnLevel:
|
||||
printFunc = logger.Warn
|
||||
printFunc = entry.Warn
|
||||
case ErrorLevel:
|
||||
printFunc = logger.Error
|
||||
printFunc = entry.Error
|
||||
case FatalLevel:
|
||||
printFunc = logger.Fatal
|
||||
printFunc = entry.Fatal
|
||||
case PanicLevel:
|
||||
printFunc = logger.Panic
|
||||
printFunc = entry.Panic
|
||||
default:
|
||||
printFunc = logger.Print
|
||||
printFunc = entry.Print
|
||||
}
|
||||
|
||||
go logger.writerScanner(reader, printFunc)
|
||||
go entry.writerScanner(reader, printFunc)
|
||||
runtime.SetFinalizer(writer, writerFinalizer)
|
||||
|
||||
return writer
|
||||
}
|
||||
|
||||
func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
|
||||
func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
|
||||
scanner := bufio.NewScanner(reader)
|
||||
for scanner.Scan() {
|
||||
printFunc(scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
logger.Errorf("Error while reading from Writer: %s", err)
|
||||
entry.Errorf("Error while reading from Writer: %s", err)
|
||||
}
|
||||
reader.Close()
|
||||
}
|
||||
|
||||
+2
@@ -86,6 +86,7 @@ var schemaDataV1 = `{
|
||||
"log_opt": {"type": "object"},
|
||||
"mac_address": {"type": "string"},
|
||||
"mem_limit": {"type": ["number", "string"]},
|
||||
"mem_reservation": {"type": ["number", "string"]},
|
||||
"memswap_limit": {"type": ["number", "string"]},
|
||||
"mem_swappiness": {"type": "integer"},
|
||||
"net": {"type": "string"},
|
||||
@@ -298,6 +299,7 @@ var servicesSchemaDataV2 = `{
|
||||
|
||||
"mac_address": {"type": "string"},
|
||||
"mem_limit": {"type": ["number", "string"]},
|
||||
"mem_reservation": {"type": ["number", "string"]},
|
||||
"memswap_limit": {"type": ["number", "string"]},
|
||||
"mem_swappiness": {"type": "integer"},
|
||||
"network_mode": {"type": "string"},
|
||||
|
||||
+1
@@ -117,6 +117,7 @@ type ServiceConfig struct {
|
||||
Logging Log `yaml:"logging,omitempty"`
|
||||
MacAddress string `yaml:"mac_address,omitempty"`
|
||||
MemLimit yaml.MemStringorInt `yaml:"mem_limit,omitempty"`
|
||||
MemReservation yaml.MemStringorInt `yaml:"mem_reservation,omitempty"`
|
||||
MemSwapLimit yaml.MemStringorInt `yaml:"memswap_limit,omitempty"`
|
||||
MemSwappiness yaml.MemStringorInt `yaml:"mem_swappiness,omitempty"`
|
||||
NetworkMode string `yaml:"network_mode,omitempty"`
|
||||
|
||||
+16
-5
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -65,7 +66,17 @@ func NewProject(context *Context, runtime RuntimeProject, parseOptions *config.P
|
||||
}
|
||||
|
||||
if context.EnvironmentLookup == nil {
|
||||
cwd, err := os.Getwd()
|
||||
var envPath, absPath, cwd string
|
||||
var err error
|
||||
if len(context.ComposeFiles) > 0 {
|
||||
absPath, err = filepath.Abs(context.ComposeFiles[0])
|
||||
dir, _ := path.Split(absPath)
|
||||
envPath = filepath.Join(dir, ".env")
|
||||
} else {
|
||||
cwd, err = os.Getwd()
|
||||
envPath = filepath.Join(cwd, ".env")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Errorf("Could not get the rooted path name to the current directory: %v", err)
|
||||
return nil
|
||||
@@ -73,7 +84,7 @@ func NewProject(context *Context, runtime RuntimeProject, parseOptions *config.P
|
||||
context.EnvironmentLookup = &lookup.ComposableEnvLookup{
|
||||
Lookups: []config.EnvironmentLookup{
|
||||
&lookup.EnvfileLookup{
|
||||
Path: filepath.Join(cwd, ".env"),
|
||||
Path: envPath,
|
||||
},
|
||||
&lookup.OsEnvLookup{},
|
||||
},
|
||||
@@ -150,7 +161,7 @@ func (p *Project) CreateService(name string) (Service, error) {
|
||||
|
||||
// check the environment for extra build Args that are set but not given a value in the compose file
|
||||
for arg, value := range config.Build.Args {
|
||||
if value == "\x00" {
|
||||
if *value == "\x00" {
|
||||
envValue := p.context.EnvironmentLookup.Lookup(arg, &config)
|
||||
// depending on what we get back we do different things
|
||||
switch l := len(envValue); l {
|
||||
@@ -158,7 +169,7 @@ func (p *Project) CreateService(name string) (Service, error) {
|
||||
delete(config.Build.Args, arg)
|
||||
case 1:
|
||||
parts := strings.SplitN(envValue[0], "=", 2)
|
||||
config.Build.Args[parts[0]] = parts[1]
|
||||
config.Build.Args[parts[0]] = &parts[1]
|
||||
default:
|
||||
return nil, fmt.Errorf("tried to set Build Arg %#v to multi-value %#v", arg, envValue)
|
||||
}
|
||||
@@ -312,7 +323,7 @@ func (p *Project) handleVolumeConfig() {
|
||||
}
|
||||
|
||||
vol, ok := p.VolumeConfigs[volume.Source]
|
||||
if !ok {
|
||||
if !ok || vol == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
+11
-10
@@ -12,7 +12,7 @@ import (
|
||||
type Build struct {
|
||||
Context string
|
||||
Dockerfile string
|
||||
Args map[string]string
|
||||
Args map[string]*string
|
||||
}
|
||||
|
||||
// MarshalYAML implements the Marshaller interface.
|
||||
@@ -63,8 +63,8 @@ func (b *Build) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||
return errors.New("Failed to unmarshal Build")
|
||||
}
|
||||
|
||||
func handleBuildArgs(value interface{}) (map[string]string, error) {
|
||||
var args map[string]string
|
||||
func handleBuildArgs(value interface{}) (map[string]*string, error) {
|
||||
var args map[string]*string
|
||||
switch v := value.(type) {
|
||||
case map[interface{}]interface{}:
|
||||
return handleBuildArgMap(v)
|
||||
@@ -75,25 +75,26 @@ func handleBuildArgs(value interface{}) (map[string]string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func handleBuildArgSlice(s []interface{}) (map[string]string, error) {
|
||||
var args = map[string]string{}
|
||||
func handleBuildArgSlice(s []interface{}) (map[string]*string, error) {
|
||||
var args = map[string]*string{}
|
||||
for _, arg := range s {
|
||||
// check if a value is provided
|
||||
switch v := strings.SplitN(arg.(string), "=", 2); len(v) {
|
||||
case 1:
|
||||
// if we have not specified a a value for this build arg, we assign it an ascii null value and query the environment
|
||||
// later when we build the service
|
||||
args[v[0]] = "\x00"
|
||||
str := "\x00"
|
||||
args[v[0]] = &str
|
||||
case 2:
|
||||
// if we do have a value provided, we use it
|
||||
args[v[0]] = v[1]
|
||||
args[v[0]] = &v[1]
|
||||
}
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func handleBuildArgMap(m map[interface{}]interface{}) (map[string]string, error) {
|
||||
args := map[string]string{}
|
||||
func handleBuildArgMap(m map[interface{}]interface{}) (map[string]*string, error) {
|
||||
args := map[string]*string{}
|
||||
for mapKey, mapValue := range m {
|
||||
var argValue string
|
||||
name, ok := mapKey.(string)
|
||||
@@ -110,7 +111,7 @@ func handleBuildArgMap(m map[interface{}]interface{}) (map[string]string, error)
|
||||
default:
|
||||
return args, fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", mapValue, mapValue)
|
||||
}
|
||||
args[name] = argValue
|
||||
args[name] = &argValue
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
|
||||
+22
-8
@@ -69,6 +69,9 @@ type DecoderConfig struct {
|
||||
// - empty array = empty map and vice versa
|
||||
// - negative numbers to overflowed uint values (base 10)
|
||||
// - slice of maps to a merged map
|
||||
// - single values are converted to slices if required. Each
|
||||
// element is weakly decoded. For example: "4" can become []int{4}
|
||||
// if the target type is an int slice.
|
||||
//
|
||||
WeaklyTypedInput bool
|
||||
|
||||
@@ -584,17 +587,28 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
|
||||
|
||||
valSlice := val
|
||||
if valSlice.IsNil() || d.config.ZeroFields {
|
||||
|
||||
// Check input type
|
||||
if dataValKind != reflect.Array && dataValKind != reflect.Slice {
|
||||
// Accept empty map instead of array/slice in weakly typed mode
|
||||
if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 {
|
||||
val.Set(reflect.MakeSlice(sliceType, 0, 0))
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf(
|
||||
"'%s': source data must be an array or slice, got %s", name, dataValKind)
|
||||
if d.config.WeaklyTypedInput {
|
||||
switch {
|
||||
// Empty maps turn into empty slices
|
||||
case dataValKind == reflect.Map:
|
||||
if dataVal.Len() == 0 {
|
||||
val.Set(reflect.MakeSlice(sliceType, 0, 0))
|
||||
return nil
|
||||
}
|
||||
|
||||
// All other types we try to convert to the slice type
|
||||
// and "lift" it into it. i.e. a string becomes a string slice.
|
||||
default:
|
||||
// Just re-try this function with data as a slice.
|
||||
return d.decodeSlice(name, []interface{}{data}, val)
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf(
|
||||
"'%s': source data must be an array or slice, got %s", name, dataValKind)
|
||||
|
||||
}
|
||||
|
||||
// Make a new slice to hold our result, same size as the original data.
|
||||
|
||||
+16
-9
@@ -31,8 +31,13 @@ func NewReader(rd io.Reader) *Reader {
|
||||
}
|
||||
}
|
||||
|
||||
type runeWithSize struct {
|
||||
r rune
|
||||
size int
|
||||
}
|
||||
|
||||
func (rd *Reader) feedBuffer() error {
|
||||
r, _, err := rd.input.ReadRune()
|
||||
r, size, err := rd.input.ReadRune()
|
||||
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
@@ -41,7 +46,9 @@ func (rd *Reader) feedBuffer() error {
|
||||
r = EOF
|
||||
}
|
||||
|
||||
rd.buffer.PushBack(r)
|
||||
newRuneWithSize := runeWithSize{r, size}
|
||||
|
||||
rd.buffer.PushBack(newRuneWithSize)
|
||||
if rd.current == nil {
|
||||
rd.current = rd.buffer.Back()
|
||||
}
|
||||
@@ -49,17 +56,17 @@ func (rd *Reader) feedBuffer() error {
|
||||
}
|
||||
|
||||
// ReadRune reads the next rune from buffer, or from the underlying reader if needed.
|
||||
func (rd *Reader) ReadRune() (rune, error) {
|
||||
func (rd *Reader) ReadRune() (rune, int, error) {
|
||||
if rd.current == rd.buffer.Back() || rd.current == nil {
|
||||
err := rd.feedBuffer()
|
||||
if err != nil {
|
||||
return EOF, err
|
||||
return EOF, 0, err
|
||||
}
|
||||
}
|
||||
|
||||
r := rd.current.Value
|
||||
runeWithSize := rd.current.Value.(runeWithSize)
|
||||
rd.current = rd.current.Next()
|
||||
return r.(rune), nil
|
||||
return runeWithSize.r, runeWithSize.size, nil
|
||||
}
|
||||
|
||||
// UnreadRune pushes back the previously read rune in the buffer, extending it if needed.
|
||||
@@ -84,9 +91,9 @@ func (rd *Reader) Forget() {
|
||||
}
|
||||
}
|
||||
|
||||
// Peek returns at most the next n runes, reading from the uderlying source if
|
||||
// PeekRune returns at most the next n runes, reading from the uderlying source if
|
||||
// needed. Does not move the current index. It includes EOF if reached.
|
||||
func (rd *Reader) Peek(n int) []rune {
|
||||
func (rd *Reader) PeekRunes(n int) []rune {
|
||||
res := make([]rune, 0, n)
|
||||
cursor := rd.current
|
||||
for i := 0; i < n; i++ {
|
||||
@@ -98,7 +105,7 @@ func (rd *Reader) Peek(n int) []rune {
|
||||
cursor = rd.buffer.Back()
|
||||
}
|
||||
if cursor != nil {
|
||||
r := cursor.Value.(rune)
|
||||
r := cursor.Value.(runeWithSize).r
|
||||
res = append(res, r)
|
||||
if r == EOF {
|
||||
return res
|
||||
|
||||
+4
-4
@@ -36,7 +36,7 @@ type tomlLexer struct {
|
||||
// Basic read operations on input
|
||||
|
||||
func (l *tomlLexer) read() rune {
|
||||
r, err := l.input.ReadRune()
|
||||
r, _, err := l.input.ReadRune()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ func (l *tomlLexer) emit(t tokenType) {
|
||||
}
|
||||
|
||||
func (l *tomlLexer) peek() rune {
|
||||
r, err := l.input.ReadRune()
|
||||
r, _, err := l.input.ReadRune()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -99,7 +99,7 @@ func (l *tomlLexer) peek() rune {
|
||||
|
||||
func (l *tomlLexer) follow(next string) bool {
|
||||
for _, expectedRune := range next {
|
||||
r, err := l.input.ReadRune()
|
||||
r, _, err := l.input.ReadRune()
|
||||
defer l.input.UnreadRune()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -219,7 +219,7 @@ func (l *tomlLexer) lexRvalue() tomlLexStateFn {
|
||||
break
|
||||
}
|
||||
|
||||
possibleDate := string(l.input.Peek(35))
|
||||
possibleDate := string(l.input.PeekRunes(35))
|
||||
dateMatch := dateRegexp.FindString(possibleDate)
|
||||
if dateMatch != "" {
|
||||
l.fastForward(len(dateMatch))
|
||||
|
||||
+2
-1
@@ -135,5 +135,6 @@ func isDigit(r rune) bool {
|
||||
|
||||
func isHexDigit(r rune) bool {
|
||||
return isDigit(r) ||
|
||||
r == 'A' || r == 'B' || r == 'C' || r == 'D' || r == 'E' || r == 'F'
|
||||
(r >= 'a' && r <= 'f') ||
|
||||
(r >= 'A' && r <= 'F')
|
||||
}
|
||||
|
||||
+2
-2
@@ -10,13 +10,13 @@ import (
|
||||
)
|
||||
|
||||
type tomlValue struct {
|
||||
value interface{}
|
||||
value interface{} // string, int64, uint64, float64, bool, time.Time, [] of any of this list
|
||||
position Position
|
||||
}
|
||||
|
||||
// TomlTree is the result of the parsing of a TOML file.
|
||||
type TomlTree struct {
|
||||
values map[string]interface{}
|
||||
values map[string]interface{} // string -> *tomlValue, *TomlTree, []*TomlTree
|
||||
position Position
|
||||
}
|
||||
|
||||
|
||||
-227
@@ -1,227 +0,0 @@
|
||||
package toml
|
||||
|
||||
// Tools to convert a TomlTree to different representations
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// encodes a string to a TOML-compliant string value
|
||||
func encodeTomlString(value string) string {
|
||||
result := ""
|
||||
for _, rr := range value {
|
||||
intRr := uint16(rr)
|
||||
switch rr {
|
||||
case '\b':
|
||||
result += "\\b"
|
||||
case '\t':
|
||||
result += "\\t"
|
||||
case '\n':
|
||||
result += "\\n"
|
||||
case '\f':
|
||||
result += "\\f"
|
||||
case '\r':
|
||||
result += "\\r"
|
||||
case '"':
|
||||
result += "\\\""
|
||||
case '\\':
|
||||
result += "\\\\"
|
||||
default:
|
||||
if intRr < 0x001F {
|
||||
result += fmt.Sprintf("\\u%0.4X", intRr)
|
||||
} else {
|
||||
result += string(rr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Value print support function for ToString()
|
||||
// Outputs the TOML compliant string representation of a value
|
||||
func toTomlValue(item interface{}, indent int) string {
|
||||
tab := strings.Repeat(" ", indent)
|
||||
switch value := item.(type) {
|
||||
case int:
|
||||
return tab + strconv.FormatInt(int64(value), 10)
|
||||
case int8:
|
||||
return tab + strconv.FormatInt(int64(value), 10)
|
||||
case int16:
|
||||
return tab + strconv.FormatInt(int64(value), 10)
|
||||
case int32:
|
||||
return tab + strconv.FormatInt(int64(value), 10)
|
||||
case int64:
|
||||
return tab + strconv.FormatInt(value, 10)
|
||||
case uint:
|
||||
return tab + strconv.FormatUint(uint64(value), 10)
|
||||
case uint8:
|
||||
return tab + strconv.FormatUint(uint64(value), 10)
|
||||
case uint16:
|
||||
return tab + strconv.FormatUint(uint64(value), 10)
|
||||
case uint32:
|
||||
return tab + strconv.FormatUint(uint64(value), 10)
|
||||
case uint64:
|
||||
return tab + strconv.FormatUint(value, 10)
|
||||
case float32:
|
||||
return tab + strconv.FormatFloat(float64(value), 'f', -1, 32)
|
||||
case float64:
|
||||
return tab + strconv.FormatFloat(value, 'f', -1, 64)
|
||||
case string:
|
||||
return tab + "\"" + encodeTomlString(value) + "\""
|
||||
case bool:
|
||||
if value {
|
||||
return "true"
|
||||
}
|
||||
return "false"
|
||||
case time.Time:
|
||||
return tab + value.Format(time.RFC3339)
|
||||
case []interface{}:
|
||||
values := []string{}
|
||||
for _, item := range value {
|
||||
values = append(values, toTomlValue(item, 0))
|
||||
}
|
||||
return "[" + strings.Join(values, ",") + "]"
|
||||
case nil:
|
||||
return ""
|
||||
default:
|
||||
panic(fmt.Errorf("unsupported value type %T: %v", value, value))
|
||||
}
|
||||
}
|
||||
|
||||
// Recursive support function for ToString()
|
||||
// Outputs a tree, using the provided keyspace to prefix table names
|
||||
func (t *TomlTree) toToml(indent, keyspace string) string {
|
||||
resultChunks := []string{}
|
||||
for k, v := range t.values {
|
||||
// figure out the keyspace
|
||||
combinedKey := k
|
||||
if keyspace != "" {
|
||||
combinedKey = keyspace + "." + combinedKey
|
||||
}
|
||||
resultChunk := ""
|
||||
// output based on type
|
||||
switch node := v.(type) {
|
||||
case []*TomlTree:
|
||||
for _, item := range node {
|
||||
if len(item.Keys()) > 0 {
|
||||
resultChunk += fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey)
|
||||
}
|
||||
resultChunk += item.toToml(indent+" ", combinedKey)
|
||||
}
|
||||
resultChunks = append(resultChunks, resultChunk)
|
||||
case *TomlTree:
|
||||
if len(node.Keys()) > 0 {
|
||||
resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
|
||||
}
|
||||
resultChunk += node.toToml(indent+" ", combinedKey)
|
||||
resultChunks = append(resultChunks, resultChunk)
|
||||
case map[string]interface{}:
|
||||
sub := TreeFromMap(node)
|
||||
|
||||
if len(sub.Keys()) > 0 {
|
||||
resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
|
||||
}
|
||||
resultChunk += sub.toToml(indent+" ", combinedKey)
|
||||
resultChunks = append(resultChunks, resultChunk)
|
||||
case map[string]string:
|
||||
sub := TreeFromMap(convertMapStringString(node))
|
||||
|
||||
if len(sub.Keys()) > 0 {
|
||||
resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
|
||||
}
|
||||
resultChunk += sub.toToml(indent+" ", combinedKey)
|
||||
resultChunks = append(resultChunks, resultChunk)
|
||||
case map[interface{}]interface{}:
|
||||
sub := TreeFromMap(convertMapInterfaceInterface(node))
|
||||
|
||||
if len(sub.Keys()) > 0 {
|
||||
resultChunk += fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
|
||||
}
|
||||
resultChunk += sub.toToml(indent+" ", combinedKey)
|
||||
resultChunks = append(resultChunks, resultChunk)
|
||||
case *tomlValue:
|
||||
resultChunk = fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(node.value, 0))
|
||||
resultChunks = append([]string{resultChunk}, resultChunks...)
|
||||
default:
|
||||
resultChunk = fmt.Sprintf("%s%s = %s\n", indent, k, toTomlValue(v, 0))
|
||||
resultChunks = append([]string{resultChunk}, resultChunks...)
|
||||
}
|
||||
|
||||
}
|
||||
return strings.Join(resultChunks, "")
|
||||
}
|
||||
|
||||
// Same as ToToml(), but does not panic and returns an error
|
||||
func (t *TomlTree) toTomlSafe(indent, keyspace string) (result string, err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
result = ""
|
||||
switch x := r.(type) {
|
||||
case error:
|
||||
err = x
|
||||
default:
|
||||
err = fmt.Errorf("unknown panic: %s", r)
|
||||
}
|
||||
}
|
||||
}()
|
||||
result = t.toToml(indent, keyspace)
|
||||
return
|
||||
}
|
||||
|
||||
func convertMapStringString(in map[string]string) map[string]interface{} {
|
||||
result := make(map[string]interface{}, len(in))
|
||||
for k, v := range in {
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func convertMapInterfaceInterface(in map[interface{}]interface{}) map[string]interface{} {
|
||||
result := make(map[string]interface{}, len(in))
|
||||
for k, v := range in {
|
||||
result[k.(string)] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ToString generates a human-readable representation of the current tree.
|
||||
// Output spans multiple lines, and is suitable for ingest by a TOML parser.
|
||||
// If the conversion cannot be performed, ToString returns a non-nil error.
|
||||
func (t *TomlTree) ToString() (string, error) {
|
||||
return t.toTomlSafe("", "")
|
||||
}
|
||||
|
||||
// String generates a human-readable representation of the current tree.
|
||||
// Alias of ToString.
|
||||
func (t *TomlTree) String() string {
|
||||
result, _ := t.ToString()
|
||||
return result
|
||||
}
|
||||
|
||||
// ToMap recursively generates a representation of the current tree using map[string]interface{}.
|
||||
func (t *TomlTree) ToMap() map[string]interface{} {
|
||||
result := map[string]interface{}{}
|
||||
|
||||
for k, v := range t.values {
|
||||
switch node := v.(type) {
|
||||
case []*TomlTree:
|
||||
var array []interface{}
|
||||
for _, item := range node {
|
||||
array = append(array, item.ToMap())
|
||||
}
|
||||
result[k] = array
|
||||
case *TomlTree:
|
||||
result[k] = node.ToMap()
|
||||
case map[string]interface{}:
|
||||
sub := TreeFromMap(node)
|
||||
result[k] = sub.ToMap()
|
||||
case *tomlValue:
|
||||
result[k] = node.value
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package toml
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// encodes a string to a TOML-compliant string value
|
||||
func encodeTomlString(value string) string {
|
||||
result := ""
|
||||
for _, rr := range value {
|
||||
switch rr {
|
||||
case '\b':
|
||||
result += "\\b"
|
||||
case '\t':
|
||||
result += "\\t"
|
||||
case '\n':
|
||||
result += "\\n"
|
||||
case '\f':
|
||||
result += "\\f"
|
||||
case '\r':
|
||||
result += "\\r"
|
||||
case '"':
|
||||
result += "\\\""
|
||||
case '\\':
|
||||
result += "\\\\"
|
||||
default:
|
||||
intRr := uint16(rr)
|
||||
if intRr < 0x001F {
|
||||
result += fmt.Sprintf("\\u%0.4X", intRr)
|
||||
} else {
|
||||
result += string(rr)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func tomlValueStringRepresentation(v interface{}) (string, error) {
|
||||
switch value := v.(type) {
|
||||
case uint64:
|
||||
return strconv.FormatUint(value, 10), nil
|
||||
case int64:
|
||||
return strconv.FormatInt(value, 10), nil
|
||||
case float64:
|
||||
return strconv.FormatFloat(value, 'f', -1, 32), nil
|
||||
case string:
|
||||
return "\"" + encodeTomlString(value) + "\"", nil
|
||||
case bool:
|
||||
if value {
|
||||
return "true", nil
|
||||
}
|
||||
return "false", nil
|
||||
case time.Time:
|
||||
return value.Format(time.RFC3339), nil
|
||||
case nil:
|
||||
return "", nil
|
||||
case []interface{}:
|
||||
values := []string{}
|
||||
for _, item := range value {
|
||||
itemRepr, err := tomlValueStringRepresentation(item)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
values = append(values, itemRepr)
|
||||
}
|
||||
return "[" + strings.Join(values, ",") + "]", nil
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported value type %T: %v", value, value)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TomlTree) writeTo(w io.Writer, indent, keyspace string, bytesCount int64) (int64, error) {
|
||||
simpleValuesKeys := make([]string, 0)
|
||||
complexValuesKeys := make([]string, 0)
|
||||
|
||||
for k := range t.values {
|
||||
v := t.values[k]
|
||||
switch v.(type) {
|
||||
case *TomlTree, []*TomlTree:
|
||||
complexValuesKeys = append(complexValuesKeys, k)
|
||||
default:
|
||||
simpleValuesKeys = append(simpleValuesKeys, k)
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(simpleValuesKeys)
|
||||
sort.Strings(complexValuesKeys)
|
||||
|
||||
for _, k := range simpleValuesKeys {
|
||||
v, ok := t.values[k].(*tomlValue)
|
||||
if !ok {
|
||||
return bytesCount, fmt.Errorf("invalid key type at %s: %T", k, t.values[k])
|
||||
}
|
||||
|
||||
repr, err := tomlValueStringRepresentation(v.value)
|
||||
if err != nil {
|
||||
return bytesCount, err
|
||||
}
|
||||
|
||||
kvRepr := fmt.Sprintf("%s%s = %s\n", indent, k, repr)
|
||||
writtenBytesCount, err := w.Write([]byte(kvRepr))
|
||||
bytesCount += int64(writtenBytesCount)
|
||||
if err != nil {
|
||||
return bytesCount, err
|
||||
}
|
||||
}
|
||||
|
||||
for _, k := range complexValuesKeys {
|
||||
v := t.values[k]
|
||||
|
||||
combinedKey := k
|
||||
if keyspace != "" {
|
||||
combinedKey = keyspace + "." + combinedKey
|
||||
}
|
||||
|
||||
switch node := v.(type) {
|
||||
// node has to be of those two types given how keys are sorted above
|
||||
case *TomlTree:
|
||||
tableName := fmt.Sprintf("\n%s[%s]\n", indent, combinedKey)
|
||||
writtenBytesCount, err := w.Write([]byte(tableName))
|
||||
bytesCount += int64(writtenBytesCount)
|
||||
if err != nil {
|
||||
return bytesCount, err
|
||||
}
|
||||
bytesCount, err = node.writeTo(w, indent+" ", combinedKey, bytesCount)
|
||||
if err != nil {
|
||||
return bytesCount, err
|
||||
}
|
||||
case []*TomlTree:
|
||||
for _, subTree := range node {
|
||||
if len(subTree.values) > 0 {
|
||||
tableArrayName := fmt.Sprintf("\n%s[[%s]]\n", indent, combinedKey)
|
||||
writtenBytesCount, err := w.Write([]byte(tableArrayName))
|
||||
bytesCount += int64(writtenBytesCount)
|
||||
if err != nil {
|
||||
return bytesCount, err
|
||||
}
|
||||
|
||||
bytesCount, err = subTree.writeTo(w, indent+" ", combinedKey, bytesCount)
|
||||
if err != nil {
|
||||
return bytesCount, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return bytesCount, nil
|
||||
}
|
||||
|
||||
// WriteTo encode the TomlTree as Toml and writes it to the writer w.
|
||||
// Returns the number of bytes written in case of success, or an error if anything happened.
|
||||
func (t *TomlTree) WriteTo(w io.Writer) (int64, error) {
|
||||
return t.writeTo(w, "", "", 0)
|
||||
}
|
||||
|
||||
// ToTomlString generates a human-readable representation of the current tree.
|
||||
// Output spans multiple lines, and is suitable for ingest by a TOML parser.
|
||||
// If the conversion cannot be performed, ToString returns a non-nil error.
|
||||
func (t *TomlTree) ToTomlString() (string, error) {
|
||||
var buf bytes.Buffer
|
||||
_, err := t.WriteTo(&buf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// String generates a human-readable representation of the current tree.
|
||||
// Alias of ToString. Present to implement the fmt.Stringer interface.
|
||||
func (t *TomlTree) String() string {
|
||||
result, _ := t.ToTomlString()
|
||||
return result
|
||||
}
|
||||
|
||||
// ToMap recursively generates a representation of the tree using Go built-in structures.
|
||||
// The following types are used:
|
||||
// * uint64
|
||||
// * int64
|
||||
// * bool
|
||||
// * string
|
||||
// * time.Time
|
||||
// * map[string]interface{} (where interface{} is any of this list)
|
||||
// * []interface{} (where interface{} is any of this list)
|
||||
func (t *TomlTree) ToMap() map[string]interface{} {
|
||||
result := map[string]interface{}{}
|
||||
|
||||
for k, v := range t.values {
|
||||
switch node := v.(type) {
|
||||
case []*TomlTree:
|
||||
var array []interface{}
|
||||
for _, item := range node {
|
||||
array = append(array, item.ToMap())
|
||||
}
|
||||
result[k] = array
|
||||
case *TomlTree:
|
||||
result[k] = node.ToMap()
|
||||
case map[string]interface{}:
|
||||
sub := TreeFromMap(node)
|
||||
result[k] = sub.ToMap()
|
||||
case *tomlValue:
|
||||
result[k] = node.value
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
+70
@@ -3,80 +3,150 @@
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package cast provides easy and safe casting in Go.
|
||||
package cast
|
||||
|
||||
import "time"
|
||||
|
||||
// ToBool casts an interface to a bool type.
|
||||
func ToBool(i interface{}) bool {
|
||||
v, _ := ToBoolE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToTime casts an interface to a time.Time type.
|
||||
func ToTime(i interface{}) time.Time {
|
||||
v, _ := ToTimeE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToDuration casts an interface to a time.Duration type.
|
||||
func ToDuration(i interface{}) time.Duration {
|
||||
v, _ := ToDurationE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToFloat64 casts an interface to a float64 type.
|
||||
func ToFloat64(i interface{}) float64 {
|
||||
v, _ := ToFloat64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToFloat32 casts an interface to a float32 type.
|
||||
func ToFloat32(i interface{}) float32 {
|
||||
v, _ := ToFloat32E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt64 casts an interface to an int64 type.
|
||||
func ToInt64(i interface{}) int64 {
|
||||
v, _ := ToInt64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt32 casts an interface to an int32 type.
|
||||
func ToInt32(i interface{}) int32 {
|
||||
v, _ := ToInt32E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt16 casts an interface to an int16 type.
|
||||
func ToInt16(i interface{}) int16 {
|
||||
v, _ := ToInt16E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt8 casts an interface to an int8 type.
|
||||
func ToInt8(i interface{}) int8 {
|
||||
v, _ := ToInt8E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt casts an interface to an int type.
|
||||
func ToInt(i interface{}) int {
|
||||
v, _ := ToIntE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint casts an interface to a uint type.
|
||||
func ToUint(i interface{}) uint {
|
||||
v, _ := ToUintE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint64 casts an interface to a uint64 type.
|
||||
func ToUint64(i interface{}) uint64 {
|
||||
v, _ := ToUint64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint32 casts an interface to a uint32 type.
|
||||
func ToUint32(i interface{}) uint32 {
|
||||
v, _ := ToUint32E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint16 casts an interface to a uint16 type.
|
||||
func ToUint16(i interface{}) uint16 {
|
||||
v, _ := ToUint16E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint8 casts an interface to a uint8 type.
|
||||
func ToUint8(i interface{}) uint8 {
|
||||
v, _ := ToUint8E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToString casts an interface to a string type.
|
||||
func ToString(i interface{}) string {
|
||||
v, _ := ToStringE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMapString casts an interface to a map[string]string type.
|
||||
func ToStringMapString(i interface{}) map[string]string {
|
||||
v, _ := ToStringMapStringE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMapStringSlice casts an interface to a map[string][]string type.
|
||||
func ToStringMapStringSlice(i interface{}) map[string][]string {
|
||||
v, _ := ToStringMapStringSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMapBool casts an interface to a map[string]bool type.
|
||||
func ToStringMapBool(i interface{}) map[string]bool {
|
||||
v, _ := ToStringMapBoolE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMap casts an interface to a map[string]interface{} type.
|
||||
func ToStringMap(i interface{}) map[string]interface{} {
|
||||
v, _ := ToStringMapE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToSlice casts an interface to a []interface{} type.
|
||||
func ToSlice(i interface{}) []interface{} {
|
||||
v, _ := ToSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToBoolSlice casts an interface to a []bool type.
|
||||
func ToBoolSlice(i interface{}) []bool {
|
||||
v, _ := ToBoolSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringSlice casts an interface to a []string type.
|
||||
func ToStringSlice(i interface{}) []string {
|
||||
v, _ := ToStringSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToIntSlice casts an interface to a []int type.
|
||||
func ToIntSlice(i interface{}) []int {
|
||||
v, _ := ToIntSliceE(i)
|
||||
return v
|
||||
|
||||
+659
-80
@@ -6,6 +6,7 @@
|
||||
package cast
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"reflect"
|
||||
@@ -14,7 +15,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// ToTimeE casts an empty interface to time.Time.
|
||||
var errNegativeNotAllowed = errors.New("unable to cast negative value")
|
||||
|
||||
// ToTimeE casts an interface to a time.Time type.
|
||||
func ToTimeE(i interface{}) (tim time.Time, err error) {
|
||||
i = indirect(i)
|
||||
|
||||
@@ -22,30 +25,32 @@ func ToTimeE(i interface{}) (tim time.Time, err error) {
|
||||
case time.Time:
|
||||
return v, nil
|
||||
case string:
|
||||
d, e := StringToDate(v)
|
||||
if e == nil {
|
||||
return d, nil
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("Could not parse Date/Time format: %v\n", e)
|
||||
return StringToDate(v)
|
||||
case int:
|
||||
return time.Unix(int64(v), 0), nil
|
||||
case int32:
|
||||
return time.Unix(int64(v), 0), nil
|
||||
case int64:
|
||||
return time.Unix(v, 0), nil
|
||||
case int32:
|
||||
return time.Unix(int64(v), 0), nil
|
||||
case uint:
|
||||
return time.Unix(int64(v), 0), nil
|
||||
case uint64:
|
||||
return time.Unix(int64(v), 0), nil
|
||||
case uint32:
|
||||
return time.Unix(int64(v), 0), nil
|
||||
default:
|
||||
return time.Time{}, fmt.Errorf("Unable to Cast %#v to Time\n", i)
|
||||
return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToDurationE casts an empty interface to time.Duration.
|
||||
// ToDurationE casts an interface to a time.Duration type.
|
||||
func ToDurationE(i interface{}) (d time.Duration, err error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case time.Duration:
|
||||
return s, nil
|
||||
case int64, int32, int16, int8, int:
|
||||
case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
|
||||
d = time.Duration(ToInt64(s))
|
||||
return
|
||||
case float32, float64:
|
||||
@@ -59,14 +64,13 @@ func ToDurationE(i interface{}) (d time.Duration, err error) {
|
||||
}
|
||||
return
|
||||
default:
|
||||
err = fmt.Errorf("Unable to Cast %#v to Duration\n", i)
|
||||
err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// ToBoolE casts an empty interface to a bool.
|
||||
// ToBoolE casts an interface to a bool type.
|
||||
func ToBoolE(i interface{}) (bool, error) {
|
||||
|
||||
i = indirect(i)
|
||||
|
||||
switch b := i.(type) {
|
||||
@@ -82,11 +86,11 @@ func ToBoolE(i interface{}) (bool, error) {
|
||||
case string:
|
||||
return strconv.ParseBool(i.(string))
|
||||
default:
|
||||
return false, fmt.Errorf("Unable to Cast %#v to bool", i)
|
||||
return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToFloat64E casts an empty interface to a float64.
|
||||
// ToFloat64E casts an interface to a float64 type.
|
||||
func ToFloat64E(i interface{}) (float64, error) {
|
||||
i = indirect(i)
|
||||
|
||||
@@ -95,6 +99,8 @@ func ToFloat64E(i interface{}) (float64, error) {
|
||||
return s, nil
|
||||
case float32:
|
||||
return float64(s), nil
|
||||
case int:
|
||||
return float64(s), nil
|
||||
case int64:
|
||||
return float64(s), nil
|
||||
case int32:
|
||||
@@ -103,55 +109,266 @@ func ToFloat64E(i interface{}) (float64, error) {
|
||||
return float64(s), nil
|
||||
case int8:
|
||||
return float64(s), nil
|
||||
case int:
|
||||
case uint:
|
||||
return float64(s), nil
|
||||
case uint64:
|
||||
return float64(s), nil
|
||||
case uint32:
|
||||
return float64(s), nil
|
||||
case uint16:
|
||||
return float64(s), nil
|
||||
case uint8:
|
||||
return float64(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
if err == nil {
|
||||
return float64(v), nil
|
||||
return v, nil
|
||||
}
|
||||
return 0.0, fmt.Errorf("Unable to Cast %#v to float", i)
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
default:
|
||||
return 0.0, fmt.Errorf("Unable to Cast %#v to float", i)
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToInt64E casts an empty interface to an int64.
|
||||
// ToFloat32E casts an interface to a float32 type.
|
||||
func ToFloat32E(i interface{}) (float32, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case float64:
|
||||
return float32(s), nil
|
||||
case float32:
|
||||
return s, nil
|
||||
case int:
|
||||
return float32(s), nil
|
||||
case int64:
|
||||
return float32(s), nil
|
||||
case int32:
|
||||
return float32(s), nil
|
||||
case int16:
|
||||
return float32(s), nil
|
||||
case int8:
|
||||
return float32(s), nil
|
||||
case uint:
|
||||
return float32(s), nil
|
||||
case uint64:
|
||||
return float32(s), nil
|
||||
case uint32:
|
||||
return float32(s), nil
|
||||
case uint16:
|
||||
return float32(s), nil
|
||||
case uint8:
|
||||
return float32(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseFloat(s, 32)
|
||||
if err == nil {
|
||||
return float32(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToInt64E casts an interface to an int64 type.
|
||||
func ToInt64E(i interface{}) (int64, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case int64:
|
||||
return s, nil
|
||||
case int:
|
||||
return int64(s), nil
|
||||
case int64:
|
||||
return s, nil
|
||||
case int32:
|
||||
return int64(s), nil
|
||||
case int16:
|
||||
return int64(s), nil
|
||||
case int8:
|
||||
return int64(s), nil
|
||||
case uint:
|
||||
return int64(s), nil
|
||||
case uint64:
|
||||
return int64(s), nil
|
||||
case uint32:
|
||||
return int64(s), nil
|
||||
case uint16:
|
||||
return int64(s), nil
|
||||
case uint8:
|
||||
return int64(s), nil
|
||||
case float64:
|
||||
return int64(s), nil
|
||||
case float32:
|
||||
return int64(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
if err == nil {
|
||||
return v, nil
|
||||
}
|
||||
return 0, fmt.Errorf("Unable to Cast %#v to int64", i)
|
||||
case float64:
|
||||
return int64(s), nil
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
|
||||
case bool:
|
||||
if bool(s) {
|
||||
return int64(1), nil
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return int64(0), nil
|
||||
return 0, nil
|
||||
case nil:
|
||||
return int64(0), nil
|
||||
return 0, nil
|
||||
default:
|
||||
return int64(0), fmt.Errorf("Unable to Cast %#v to int64", i)
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToIntE casts an empty interface to an int.
|
||||
// ToInt32E casts an interface to an int32 type.
|
||||
func ToInt32E(i interface{}) (int32, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case int:
|
||||
return int32(s), nil
|
||||
case int64:
|
||||
return int32(s), nil
|
||||
case int32:
|
||||
return s, nil
|
||||
case int16:
|
||||
return int32(s), nil
|
||||
case int8:
|
||||
return int32(s), nil
|
||||
case uint:
|
||||
return int32(s), nil
|
||||
case uint64:
|
||||
return int32(s), nil
|
||||
case uint32:
|
||||
return int32(s), nil
|
||||
case uint16:
|
||||
return int32(s), nil
|
||||
case uint8:
|
||||
return int32(s), nil
|
||||
case float64:
|
||||
return int32(s), nil
|
||||
case float32:
|
||||
return int32(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
if err == nil {
|
||||
return int32(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToInt16E casts an interface to an int16 type.
|
||||
func ToInt16E(i interface{}) (int16, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case int:
|
||||
return int16(s), nil
|
||||
case int64:
|
||||
return int16(s), nil
|
||||
case int32:
|
||||
return int16(s), nil
|
||||
case int16:
|
||||
return s, nil
|
||||
case int8:
|
||||
return int16(s), nil
|
||||
case uint:
|
||||
return int16(s), nil
|
||||
case uint64:
|
||||
return int16(s), nil
|
||||
case uint32:
|
||||
return int16(s), nil
|
||||
case uint16:
|
||||
return int16(s), nil
|
||||
case uint8:
|
||||
return int16(s), nil
|
||||
case float64:
|
||||
return int16(s), nil
|
||||
case float32:
|
||||
return int16(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
if err == nil {
|
||||
return int16(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToInt8E casts an interface to an int8 type.
|
||||
func ToInt8E(i interface{}) (int8, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case int:
|
||||
return int8(s), nil
|
||||
case int64:
|
||||
return int8(s), nil
|
||||
case int32:
|
||||
return int8(s), nil
|
||||
case int16:
|
||||
return int8(s), nil
|
||||
case int8:
|
||||
return s, nil
|
||||
case uint:
|
||||
return int8(s), nil
|
||||
case uint64:
|
||||
return int8(s), nil
|
||||
case uint32:
|
||||
return int8(s), nil
|
||||
case uint16:
|
||||
return int8(s), nil
|
||||
case uint8:
|
||||
return int8(s), nil
|
||||
case float64:
|
||||
return int8(s), nil
|
||||
case float32:
|
||||
return int8(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
if err == nil {
|
||||
return int8(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToIntE casts an interface to an int type.
|
||||
func ToIntE(i interface{}) (int, error) {
|
||||
i = indirect(i)
|
||||
|
||||
@@ -166,23 +383,375 @@ func ToIntE(i interface{}) (int, error) {
|
||||
return int(s), nil
|
||||
case int8:
|
||||
return int(s), nil
|
||||
case uint:
|
||||
return int(s), nil
|
||||
case uint64:
|
||||
return int(s), nil
|
||||
case uint32:
|
||||
return int(s), nil
|
||||
case uint16:
|
||||
return int(s), nil
|
||||
case uint8:
|
||||
return int(s), nil
|
||||
case float64:
|
||||
return int(s), nil
|
||||
case float32:
|
||||
return int(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
if err == nil {
|
||||
return int(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("Unable to Cast %#v to int", i)
|
||||
case float64:
|
||||
return int(s), nil
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
|
||||
case bool:
|
||||
if bool(s) {
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("Unable to Cast %#v to int", i)
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToUintE casts an interface to a uint type.
|
||||
func ToUintE(i interface{}) (uint, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case string:
|
||||
v, err := strconv.ParseUint(s, 0, 0)
|
||||
if err == nil {
|
||||
return uint(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err)
|
||||
case int:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case int64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case int32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case int16:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case int8:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case uint:
|
||||
return s, nil
|
||||
case uint64:
|
||||
return uint(s), nil
|
||||
case uint32:
|
||||
return uint(s), nil
|
||||
case uint16:
|
||||
return uint(s), nil
|
||||
case uint8:
|
||||
return uint(s), nil
|
||||
case float64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case float32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint(s), nil
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToUint64E casts an interface to a uint64 type.
|
||||
func ToUint64E(i interface{}) (uint64, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case string:
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
if err == nil {
|
||||
return v, nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v to uint64: %s", i, err)
|
||||
case int:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case int64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case int32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case int16:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case int8:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case uint:
|
||||
return uint64(s), nil
|
||||
case uint64:
|
||||
return s, nil
|
||||
case uint32:
|
||||
return uint64(s), nil
|
||||
case uint16:
|
||||
return uint64(s), nil
|
||||
case uint8:
|
||||
return uint64(s), nil
|
||||
case float32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case float64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint64(s), nil
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToUint32E casts an interface to a uint32 type.
|
||||
func ToUint32E(i interface{}) (uint32, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case string:
|
||||
v, err := strconv.ParseUint(s, 0, 32)
|
||||
if err == nil {
|
||||
return uint32(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v to uint32: %s", i, err)
|
||||
case int:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case int64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case int32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case int16:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case int8:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case uint:
|
||||
return uint32(s), nil
|
||||
case uint64:
|
||||
return uint32(s), nil
|
||||
case uint32:
|
||||
return s, nil
|
||||
case uint16:
|
||||
return uint32(s), nil
|
||||
case uint8:
|
||||
return uint32(s), nil
|
||||
case float64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case float32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint32(s), nil
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToUint16E casts an interface to a uint16 type.
|
||||
func ToUint16E(i interface{}) (uint16, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case string:
|
||||
v, err := strconv.ParseUint(s, 0, 16)
|
||||
if err == nil {
|
||||
return uint16(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v to uint16: %s", i, err)
|
||||
case int:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case int64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case int32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case int16:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case int8:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case uint:
|
||||
return uint16(s), nil
|
||||
case uint64:
|
||||
return uint16(s), nil
|
||||
case uint32:
|
||||
return uint16(s), nil
|
||||
case uint16:
|
||||
return s, nil
|
||||
case uint8:
|
||||
return uint16(s), nil
|
||||
case float64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case float32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint16(s), nil
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToUint8E casts an interface to a uint type.
|
||||
func ToUint8E(i interface{}) (uint8, error) {
|
||||
i = indirect(i)
|
||||
|
||||
switch s := i.(type) {
|
||||
case string:
|
||||
v, err := strconv.ParseUint(s, 0, 8)
|
||||
if err == nil {
|
||||
return uint8(v), nil
|
||||
}
|
||||
return 0, fmt.Errorf("unable to cast %#v to uint8: %s", i, err)
|
||||
case int:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case int64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case int32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case int16:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case int8:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case uint:
|
||||
return uint8(s), nil
|
||||
case uint64:
|
||||
return uint8(s), nil
|
||||
case uint32:
|
||||
return uint8(s), nil
|
||||
case uint16:
|
||||
return uint8(s), nil
|
||||
case uint8:
|
||||
return s, nil
|
||||
case float64:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case float32:
|
||||
if s < 0 {
|
||||
return 0, errNegativeNotAllowed
|
||||
}
|
||||
return uint8(s), nil
|
||||
case bool:
|
||||
if s {
|
||||
return 1, nil
|
||||
}
|
||||
return 0, nil
|
||||
case nil:
|
||||
return 0, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,7 +794,7 @@ func indirectToStringerOrError(a interface{}) interface{} {
|
||||
return v.Interface()
|
||||
}
|
||||
|
||||
// ToStringE casts an empty interface to a string.
|
||||
// ToStringE casts an interface to a string type.
|
||||
func ToStringE(i interface{}) (string, error) {
|
||||
i = indirectToStringerOrError(i)
|
||||
|
||||
@@ -235,11 +804,29 @@ func ToStringE(i interface{}) (string, error) {
|
||||
case bool:
|
||||
return strconv.FormatBool(s), nil
|
||||
case float64:
|
||||
return strconv.FormatFloat(i.(float64), 'f', -1, 64), nil
|
||||
case int64:
|
||||
return strconv.FormatInt(i.(int64), 10), nil
|
||||
return strconv.FormatFloat(s, 'f', -1, 64), nil
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
|
||||
case int:
|
||||
return strconv.FormatInt(int64(i.(int)), 10), nil
|
||||
return strconv.Itoa(s), nil
|
||||
case int64:
|
||||
return strconv.FormatInt(s, 10), nil
|
||||
case int32:
|
||||
return strconv.Itoa(int(s)), nil
|
||||
case int16:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case int8:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case uint:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case uint64:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case uint32:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case uint16:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case uint8:
|
||||
return strconv.FormatInt(int64(s), 10), nil
|
||||
case []byte:
|
||||
return string(s), nil
|
||||
case template.HTML:
|
||||
@@ -259,13 +846,12 @@ func ToStringE(i interface{}) (string, error) {
|
||||
case error:
|
||||
return s.Error(), nil
|
||||
default:
|
||||
return "", fmt.Errorf("Unable to Cast %#v to string", i)
|
||||
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToStringMapStringE casts an empty interface to a map[string]string.
|
||||
// ToStringMapStringE casts an interface to a map[string]string type.
|
||||
func ToStringMapStringE(i interface{}) (map[string]string, error) {
|
||||
|
||||
var m = map[string]string{}
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -287,13 +873,12 @@ func ToStringMapStringE(i interface{}) (map[string]string, error) {
|
||||
}
|
||||
return m, nil
|
||||
default:
|
||||
return m, fmt.Errorf("Unable to Cast %#v to map[string]string", i)
|
||||
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToStringMapStringSliceE casts an empty interface to a map[string][]string.
|
||||
// ToStringMapStringSliceE casts an interface to a map[string][]string type.
|
||||
func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
|
||||
|
||||
var m = map[string][]string{}
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -339,23 +924,22 @@ func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
|
||||
for k, val := range v {
|
||||
key, err := ToStringE(k)
|
||||
if err != nil {
|
||||
return m, fmt.Errorf("Unable to Cast %#v to map[string][]string", i)
|
||||
return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
|
||||
}
|
||||
value, err := ToStringSliceE(val)
|
||||
if err != nil {
|
||||
return m, fmt.Errorf("Unable to Cast %#v to map[string][]string", i)
|
||||
return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
|
||||
}
|
||||
m[key] = value
|
||||
}
|
||||
default:
|
||||
return m, fmt.Errorf("Unable to Cast %#v to map[string][]string", i)
|
||||
return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// ToStringMapBoolE casts an empty interface to a map[string]bool.
|
||||
// ToStringMapBoolE casts an interface to a map[string]bool type.
|
||||
func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
|
||||
|
||||
var m = map[string]bool{}
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -372,13 +956,12 @@ func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
|
||||
case map[string]bool:
|
||||
return v, nil
|
||||
default:
|
||||
return m, fmt.Errorf("Unable to Cast %#v to map[string]bool", i)
|
||||
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToStringMapE casts an empty interface to a map[string]interface{}.
|
||||
// ToStringMapE casts an interface to a map[string]interface{} type.
|
||||
func ToStringMapE(i interface{}) (map[string]interface{}, error) {
|
||||
|
||||
var m = map[string]interface{}{}
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -390,36 +973,31 @@ func ToStringMapE(i interface{}) (map[string]interface{}, error) {
|
||||
case map[string]interface{}:
|
||||
return v, nil
|
||||
default:
|
||||
return m, fmt.Errorf("Unable to Cast %#v to map[string]interface{}", i)
|
||||
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToSliceE casts an empty interface to a []interface{}.
|
||||
// ToSliceE casts an interface to a []interface{} type.
|
||||
func ToSliceE(i interface{}) ([]interface{}, error) {
|
||||
|
||||
var s []interface{}
|
||||
|
||||
switch v := i.(type) {
|
||||
case []interface{}:
|
||||
for _, u := range v {
|
||||
s = append(s, u)
|
||||
}
|
||||
return s, nil
|
||||
return append(s, v...), nil
|
||||
case []map[string]interface{}:
|
||||
for _, u := range v {
|
||||
s = append(s, u)
|
||||
}
|
||||
return s, nil
|
||||
default:
|
||||
return s, fmt.Errorf("Unable to Cast %#v of type %v to []interface{}", i, reflect.TypeOf(i))
|
||||
return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToBoolSliceE casts an empty interface to a []bool.
|
||||
// ToBoolSliceE casts an interface to a []bool type.
|
||||
func ToBoolSliceE(i interface{}) ([]bool, error) {
|
||||
|
||||
if i == nil {
|
||||
return []bool{}, fmt.Errorf("Unable to Cast %#v to []bool", i)
|
||||
return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
|
||||
}
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -435,19 +1013,18 @@ func ToBoolSliceE(i interface{}) ([]bool, error) {
|
||||
for j := 0; j < s.Len(); j++ {
|
||||
val, err := ToBoolE(s.Index(j).Interface())
|
||||
if err != nil {
|
||||
return []bool{}, fmt.Errorf("Unable to Cast %#v to []bool", i)
|
||||
return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
|
||||
}
|
||||
a[j] = val
|
||||
}
|
||||
return a, nil
|
||||
default:
|
||||
return []bool{}, fmt.Errorf("Unable to Cast %#v to []bool", i)
|
||||
return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToStringSliceE casts an empty interface to a []string.
|
||||
// ToStringSliceE casts an interface to a []string type.
|
||||
func ToStringSliceE(i interface{}) ([]string, error) {
|
||||
|
||||
var a []string
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -463,19 +1040,18 @@ func ToStringSliceE(i interface{}) ([]string, error) {
|
||||
case interface{}:
|
||||
str, err := ToStringE(v)
|
||||
if err != nil {
|
||||
return a, fmt.Errorf("Unable to Cast %#v to []string", i)
|
||||
return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
|
||||
}
|
||||
return []string{str}, nil
|
||||
default:
|
||||
return a, fmt.Errorf("Unable to Cast %#v to []string", i)
|
||||
return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToIntSliceE casts an empty interface to a []int.
|
||||
// ToIntSliceE casts an interface to a []int type.
|
||||
func ToIntSliceE(i interface{}) ([]int, error) {
|
||||
|
||||
if i == nil {
|
||||
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
|
||||
}
|
||||
|
||||
switch v := i.(type) {
|
||||
@@ -491,17 +1067,19 @@ func ToIntSliceE(i interface{}) ([]int, error) {
|
||||
for j := 0; j < s.Len(); j++ {
|
||||
val, err := ToIntE(s.Index(j).Interface())
|
||||
if err != nil {
|
||||
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
|
||||
}
|
||||
a[j] = val
|
||||
}
|
||||
return a, nil
|
||||
default:
|
||||
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
|
||||
}
|
||||
}
|
||||
|
||||
// StringToDate casts an empty interface to a time.Time.
|
||||
// StringToDate attempts to parse a string into a time.Time type using a
|
||||
// predefined list of formats. If no suitable format is found, an error is
|
||||
// returned.
|
||||
func StringToDate(s string) (time.Time, error) {
|
||||
return parseDateWith(s, []string{
|
||||
time.RFC3339,
|
||||
@@ -519,6 +1097,7 @@ func StringToDate(s string) (time.Time, error) {
|
||||
"02 Jan 2006",
|
||||
"2006-01-02 15:04:05 -07:00",
|
||||
"2006-01-02 15:04:05 -0700",
|
||||
"2006-01-02 15:04:05Z07:00", // RFC3339 without T
|
||||
"2006-01-02 15:04:05",
|
||||
time.Kitchen,
|
||||
time.Stamp,
|
||||
@@ -534,5 +1113,5 @@ func parseDateWith(s string, dates []string) (d time.Time, e error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
return d, fmt.Errorf("Unable to parse date: %s", s)
|
||||
return d, fmt.Errorf("unable to parse date: %s", s)
|
||||
}
|
||||
|
||||
+25
-29
@@ -155,12 +155,12 @@ func (c *Command) SetUsageTemplate(s string) {
|
||||
}
|
||||
|
||||
// SetFlagErrorFunc sets a function to generate an error when flag parsing
|
||||
// fails
|
||||
// fails.
|
||||
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
|
||||
c.flagErrorFunc = f
|
||||
}
|
||||
|
||||
// SetHelpFunc sets help function. Can be defined by Application
|
||||
// SetHelpFunc sets help function. Can be defined by Application.
|
||||
func (c *Command) SetHelpFunc(f func(*Command, []string)) {
|
||||
c.helpFunc = f
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string
|
||||
}
|
||||
}
|
||||
|
||||
// OutOrStdout returns output to stdout
|
||||
// OutOrStdout returns output to stdout.
|
||||
func (c *Command) OutOrStdout() io.Writer {
|
||||
return c.getOut(os.Stdout)
|
||||
}
|
||||
@@ -345,19 +345,19 @@ Aliases:
|
||||
{{end}}{{if .HasExample}}
|
||||
|
||||
Examples:
|
||||
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
|
||||
{{ .Example }}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}
|
||||
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
|
||||
Flags:
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}}
|
||||
|
||||
Global Flags:
|
||||
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
|
||||
|
||||
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
|
||||
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
|
||||
`
|
||||
@@ -384,20 +384,18 @@ func (c *Command) resetChildrensParents() {
|
||||
}
|
||||
}
|
||||
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanFlag(name string, f *flag.FlagSet) bool {
|
||||
func hasNoOptDefVal(name string, f *flag.FlagSet) bool {
|
||||
flag := f.Lookup(name)
|
||||
if flag == nil {
|
||||
return false
|
||||
}
|
||||
return flag.Value.Type() == "bool"
|
||||
return len(flag.NoOptDefVal) > 0
|
||||
}
|
||||
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanShortFlag(name string, f *flag.FlagSet) bool {
|
||||
func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
||||
result := false
|
||||
f.VisitAll(func(f *flag.Flag) {
|
||||
if f.Shorthand == name && f.Value.Type() == "bool" {
|
||||
fs.VisitAll(func(flag *flag.Flag) {
|
||||
if flag.Shorthand == name && len(flag.NoOptDefVal) > 0 {
|
||||
result = true
|
||||
}
|
||||
})
|
||||
@@ -423,8 +421,8 @@ func stripFlags(args []string, c *Command) []string {
|
||||
inQuote = true
|
||||
case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
|
||||
// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
|
||||
inFlag = !isBooleanFlag(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):
|
||||
inFlag = !hasNoOptDefVal(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !shortHasNoOptDefVal(y[1:], c.Flags()):
|
||||
inFlag = true
|
||||
case inFlag:
|
||||
inFlag = false
|
||||
@@ -698,7 +696,6 @@ func (c *Command) Execute() error {
|
||||
|
||||
// ExecuteC executes the command.
|
||||
func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
|
||||
// Regardless of what command execute is called on, run on Root only
|
||||
if c.HasParent() {
|
||||
return c.Root().ExecuteC()
|
||||
@@ -783,7 +780,7 @@ func (c *Command) initHelpCmd() {
|
||||
Run: func(c *Command, args []string) {
|
||||
cmd, _, e := c.Root().Find(args)
|
||||
if cmd == nil || e != nil {
|
||||
c.Printf("Unknown help topic %#q.", args)
|
||||
c.Printf("Unknown help topic %#q\n", args)
|
||||
c.Root().Usage()
|
||||
} else {
|
||||
cmd.Help()
|
||||
@@ -1024,11 +1021,12 @@ func (c *Command) IsAvailableCommand() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// IsHelpCommand determines if a command is a 'help' command; a help command is
|
||||
// determined by the fact that it is NOT runnable/hidden/deprecated, and has no
|
||||
// sub commands that are runnable/hidden/deprecated.
|
||||
func (c *Command) IsHelpCommand() bool {
|
||||
|
||||
// IsAdditionalHelpTopicCommand determines if a command is an additional
|
||||
// help topic command; additional help topic command is determined by the
|
||||
// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
|
||||
// are runnable/hidden/deprecated.
|
||||
// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
|
||||
func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
||||
// if a command is runnable, deprecated, or hidden it is not a 'help' command
|
||||
if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
@@ -1036,7 +1034,7 @@ func (c *Command) IsHelpCommand() bool {
|
||||
|
||||
// if any non-help sub commands are found, the command is not a 'help' command
|
||||
for _, sub := range c.commands {
|
||||
if !sub.IsHelpCommand() {
|
||||
if !sub.IsAdditionalHelpTopicCommand() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -1049,10 +1047,9 @@ func (c *Command) IsHelpCommand() bool {
|
||||
// that need to be shown in the usage/help default template under 'additional help
|
||||
// topics'.
|
||||
func (c *Command) HasHelpSubCommands() bool {
|
||||
|
||||
// return true on the first found available 'help' sub command
|
||||
for _, sub := range c.commands {
|
||||
if sub.IsHelpCommand() {
|
||||
if sub.IsAdditionalHelpTopicCommand() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1064,7 +1061,6 @@ func (c *Command) HasHelpSubCommands() bool {
|
||||
// HasAvailableSubCommands determines if a command has available sub commands that
|
||||
// need to be shown in the usage/help default template under 'available commands'.
|
||||
func (c *Command) HasAvailableSubCommands() bool {
|
||||
|
||||
// return true on the first found available (non deprecated/help/hidden)
|
||||
// sub command
|
||||
for _, sub := range c.commands {
|
||||
|
||||
+8
-2
@@ -1093,9 +1093,15 @@ func (v *Viper) ReadInConfig() error {
|
||||
return err
|
||||
}
|
||||
|
||||
v.config = make(map[string]interface{})
|
||||
config := make(map[string]interface{})
|
||||
|
||||
return v.unmarshalReader(bytes.NewReader(file), v.config)
|
||||
err = v.unmarshalReader(bytes.NewReader(file), config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
v.config = config
|
||||
return nil
|
||||
}
|
||||
|
||||
// MergeInConfig merges a new configuration with an existing config.
|
||||
|
||||
+34
-61
@@ -52,35 +52,24 @@ type implStruct struct {
|
||||
outError error
|
||||
}
|
||||
|
||||
func NewJsonPointer(jsonPointerString string) (JsonPointer, error) {
|
||||
|
||||
var p JsonPointer
|
||||
err := p.parse(jsonPointerString)
|
||||
return p, err
|
||||
|
||||
}
|
||||
|
||||
type JsonPointer struct {
|
||||
referenceTokens []string
|
||||
}
|
||||
|
||||
// "Constructor", parses the given string JSON pointer
|
||||
func (p *JsonPointer) parse(jsonPointerString string) error {
|
||||
// NewJsonPointer parses the given string JSON pointer and returns an object
|
||||
func NewJsonPointer(jsonPointerString string) (p JsonPointer, err error) {
|
||||
|
||||
var err error
|
||||
|
||||
if jsonPointerString != const_empty_pointer {
|
||||
if !strings.HasPrefix(jsonPointerString, const_pointer_separator) {
|
||||
err = errors.New(const_invalid_start)
|
||||
} else {
|
||||
referenceTokens := strings.Split(jsonPointerString, const_pointer_separator)
|
||||
for _, referenceToken := range referenceTokens[1:] {
|
||||
p.referenceTokens = append(p.referenceTokens, referenceToken)
|
||||
}
|
||||
}
|
||||
// Pointer to the root of the document
|
||||
if len(jsonPointerString) == 0 {
|
||||
// Keep referenceTokens nil
|
||||
return
|
||||
}
|
||||
if jsonPointerString[0] != '/' {
|
||||
return p, errors.New(const_invalid_start)
|
||||
}
|
||||
|
||||
return err
|
||||
p.referenceTokens = strings.Split(jsonPointerString[1:], const_pointer_separator)
|
||||
return
|
||||
}
|
||||
|
||||
// Uses the pointer to retrieve a value from a JSON document
|
||||
@@ -119,64 +108,55 @@ func (p *JsonPointer) implementation(i *implStruct) {
|
||||
|
||||
for ti, token := range p.referenceTokens {
|
||||
|
||||
decodedToken := decodeReferenceToken(token)
|
||||
isLastToken := ti == len(p.referenceTokens)-1
|
||||
|
||||
rValue := reflect.ValueOf(node)
|
||||
kind = rValue.Kind()
|
||||
switch v := node.(type) {
|
||||
|
||||
switch kind {
|
||||
|
||||
case reflect.Map:
|
||||
m := node.(map[string]interface{})
|
||||
if _, ok := m[decodedToken]; ok {
|
||||
node = m[decodedToken]
|
||||
case map[string]interface{}:
|
||||
decodedToken := decodeReferenceToken(token)
|
||||
if _, ok := v[decodedToken]; ok {
|
||||
node = v[decodedToken]
|
||||
if isLastToken && i.mode == "SET" {
|
||||
m[decodedToken] = i.setInValue
|
||||
v[decodedToken] = i.setInValue
|
||||
}
|
||||
} else {
|
||||
i.outError = errors.New(fmt.Sprintf("Object has no key '%s'", token))
|
||||
i.getOutKind = kind
|
||||
i.outError = fmt.Errorf("Object has no key '%s'", decodedToken)
|
||||
i.getOutKind = reflect.Map
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
|
||||
case reflect.Slice:
|
||||
s := node.([]interface{})
|
||||
case []interface{}:
|
||||
tokenIndex, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
i.outError = errors.New(fmt.Sprintf("Invalid array index '%s'", token))
|
||||
i.getOutKind = kind
|
||||
i.outError = fmt.Errorf("Invalid array index '%s'", token)
|
||||
i.getOutKind = reflect.Slice
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
sLength := len(s)
|
||||
if tokenIndex < 0 || tokenIndex >= sLength {
|
||||
i.outError = errors.New(fmt.Sprintf("Out of bound array[0,%d] index '%d'", sLength, tokenIndex))
|
||||
i.getOutKind = kind
|
||||
if tokenIndex < 0 || tokenIndex >= len(v) {
|
||||
i.outError = fmt.Errorf("Out of bound array[0,%d] index '%d'", len(v), tokenIndex)
|
||||
i.getOutKind = reflect.Slice
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
|
||||
node = s[tokenIndex]
|
||||
node = v[tokenIndex]
|
||||
if isLastToken && i.mode == "SET" {
|
||||
s[tokenIndex] = i.setInValue
|
||||
v[tokenIndex] = i.setInValue
|
||||
}
|
||||
|
||||
default:
|
||||
i.outError = errors.New(fmt.Sprintf("Invalid token reference '%s'", token))
|
||||
i.getOutKind = kind
|
||||
i.outError = fmt.Errorf("Invalid token reference '%s'", token)
|
||||
i.getOutKind = reflect.ValueOf(node).Kind()
|
||||
i.getOutNode = nil
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
rValue := reflect.ValueOf(node)
|
||||
kind = rValue.Kind()
|
||||
|
||||
i.getOutNode = node
|
||||
i.getOutKind = kind
|
||||
i.getOutKind = reflect.ValueOf(node).Kind()
|
||||
i.outError = nil
|
||||
}
|
||||
|
||||
@@ -197,21 +177,14 @@ func (p *JsonPointer) String() string {
|
||||
// ~1 => /
|
||||
// ... and vice versa
|
||||
|
||||
const (
|
||||
const_encoded_reference_token_0 = `~0`
|
||||
const_encoded_reference_token_1 = `~1`
|
||||
const_decoded_reference_token_0 = `~`
|
||||
const_decoded_reference_token_1 = `/`
|
||||
)
|
||||
|
||||
func decodeReferenceToken(token string) string {
|
||||
step1 := strings.Replace(token, const_encoded_reference_token_1, const_decoded_reference_token_1, -1)
|
||||
step2 := strings.Replace(step1, const_encoded_reference_token_0, const_decoded_reference_token_0, -1)
|
||||
step1 := strings.Replace(token, `~1`, `/`, -1)
|
||||
step2 := strings.Replace(step1, `~0`, `~`, -1)
|
||||
return step2
|
||||
}
|
||||
|
||||
func encodeReferenceToken(token string) string {
|
||||
step1 := strings.Replace(token, const_decoded_reference_token_1, const_encoded_reference_token_1, -1)
|
||||
step2 := strings.Replace(step1, const_decoded_reference_token_0, const_encoded_reference_token_0, -1)
|
||||
step1 := strings.Replace(token, `~`, `~0`, -1)
|
||||
step2 := strings.Replace(step1, `/`, `~1`, -1)
|
||||
return step2
|
||||
}
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import (
|
||||
"text/template"
|
||||
)
|
||||
|
||||
var errorTemplates errorTemplate = errorTemplate{template.New("errors-new"),sync.RWMutex{}}
|
||||
var errorTemplates errorTemplate = errorTemplate{template.New("errors-new"), sync.RWMutex{}}
|
||||
|
||||
// template.Template is not thread-safe for writing, so some locking is done
|
||||
// sync.RWMutex is used for efficiently locking when new templates are created
|
||||
|
||||
+1
-1
@@ -175,7 +175,7 @@ func (l *jsonReferenceLoader) loadFromHTTP(address string) (interface{}, error)
|
||||
|
||||
// must return HTTP Status 200 OK
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, errors.New(formatErrorDescription(Locale.httpBadStatus(), ErrorDetails{"status": resp.Status}))
|
||||
return nil, errors.New(formatErrorDescription(Locale.HttpBadStatus(), ErrorDetails{"status": resp.Status}))
|
||||
}
|
||||
|
||||
bodyBuff, err := ioutil.ReadAll(resp.Body)
|
||||
|
||||
+3
-3
@@ -26,7 +26,7 @@
|
||||
package gojsonschema
|
||||
|
||||
type (
|
||||
// locale is an interface for definining custom error strings
|
||||
// locale is an interface for defining custom error strings
|
||||
locale interface {
|
||||
Required() string
|
||||
InvalidType() string
|
||||
@@ -73,7 +73,7 @@ type (
|
||||
ReferenceMustBeCanonical() string
|
||||
NotAValidType() string
|
||||
Duplicated() string
|
||||
httpBadStatus() string
|
||||
HttpBadStatus() string
|
||||
|
||||
// ErrorFormat
|
||||
ErrorFormat() string
|
||||
@@ -256,7 +256,7 @@ func (l DefaultLocale) Duplicated() string {
|
||||
return `{{.type}} type is duplicated`
|
||||
}
|
||||
|
||||
func (l DefaultLocale) httpBadStatus() string {
|
||||
func (l DefaultLocale) HttpBadStatus() string {
|
||||
return `Could not read schema from HTTP, response status is {{.status}}`
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user