go-toml/ast/string.go

56 lines
1.5 KiB
Go

package ast
import (
"fmt"
"sort"
"strings"
"time"
)
// String() produces a JSON-like (but not JSON) string representation of the TOML Document.
// This string version is mainly useful for testing and debugging purposes.
func (t Table) String() string {
return NewValue(TypeTable, t).String()
}
// String() produces a JSON-like (but not JSON) string representation of the value.
// This string version is mainly useful for testing and debugging purposes.
func (value Value) String() string {
switch value.Type {
case TypeString:
return fmt.Sprintf("%q", value.Data[0])
case TypeOffsetDateTime:
return value.Data[0].(time.Time).Format(time.RFC3339Nano)
case TypeLocalDateTime:
return value.Data[0].(time.Time).Format("2006-01-02 15:04:05.999999999")
case TypeLocalDate:
return value.Data[0].(time.Time).Format("2006-01-02")
case TypeLocalTime:
return value.Data[0].(time.Time).Format("15:04:05.999999999")
case TypeArrayOfTables:
fallthrough
case TypeArray:
values := make(Key, len(value.Data))
for i, value := range value.Data {
values[i] = value.(*Value).String()
}
return fmt.Sprintf("[%s]", strings.Join(values, ", "))
case TypeTable:
pairs := value.Data[0].(Table)
keys := make([]string, len(pairs))
i := 0
for k := range pairs {
keys[i] = k
i++
}
sort.Strings(keys)
values := make([]string, len(pairs))
for i, k := range keys {
values[i] = fmt.Sprintf("%q: %s", k, pairs[k].String())
}
return fmt.Sprintf("{%s}", strings.Join(values, ", "))
default:
return fmt.Sprintf("%v", value.Data[0])
}
}