git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/toml/_example/example.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"reflect"
     7  	"sort"
     8  	"strings"
     9  	"time"
    10  
    11  	"git.sr.ht/~pingoo/stdx/toml"
    12  )
    13  
    14  type (
    15  	example struct {
    16  		Title      string
    17  		Desc       string
    18  		Integers   []int
    19  		Floats     []float64
    20  		Times      []fmtTime
    21  		Duration   []time.Duration
    22  		Distros    []distro
    23  		Servers    map[string]server
    24  		Characters map[string][]struct {
    25  			Name string
    26  			Rank string
    27  		}
    28  	}
    29  
    30  	server struct {
    31  		IP       string
    32  		Hostname string
    33  		Enabled  bool
    34  	}
    35  
    36  	distro struct {
    37  		Name     string
    38  		Packages string
    39  	}
    40  
    41  	fmtTime struct{ time.Time }
    42  )
    43  
    44  func (t fmtTime) String() string {
    45  	f := "2006-01-02 15:04:05.999999999"
    46  	if t.Time.Hour() == 0 {
    47  		f = "2006-01-02"
    48  	}
    49  	if t.Time.Year() == 0 {
    50  		f = "15:04:05.999999999"
    51  	}
    52  	if t.Time.Location() == time.UTC {
    53  		f += " UTC"
    54  	} else {
    55  		f += " -0700"
    56  	}
    57  	return t.Time.Format(`"` + f + `"`)
    58  }
    59  
    60  func main() {
    61  	f := "example.toml"
    62  	if _, err := os.Stat(f); err != nil {
    63  		f = "_example/example.toml"
    64  	}
    65  
    66  	var config example
    67  	meta, err := toml.DecodeFile(f, &config)
    68  	if err != nil {
    69  		fmt.Fprintln(os.Stderr, err)
    70  		os.Exit(1)
    71  	}
    72  
    73  	indent := strings.Repeat(" ", 14)
    74  
    75  	fmt.Print("Decoded")
    76  	typ, val := reflect.TypeOf(config), reflect.ValueOf(config)
    77  	for i := 0; i < typ.NumField(); i++ {
    78  		indent := indent
    79  		if i == 0 {
    80  			indent = strings.Repeat(" ", 7)
    81  		}
    82  		fmt.Printf("%s%-11s → %v\n", indent, typ.Field(i).Name, val.Field(i).Interface())
    83  	}
    84  
    85  	fmt.Print("\nKeys")
    86  	keys := meta.Keys()
    87  	sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
    88  	for i, k := range keys {
    89  		indent := indent
    90  		if i == 0 {
    91  			indent = strings.Repeat(" ", 10)
    92  		}
    93  		fmt.Printf("%s%-10s %s\n", indent, meta.Type(k...), k)
    94  	}
    95  
    96  	fmt.Print("\nUndecoded")
    97  	keys = meta.Undecoded()
    98  	sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
    99  	for i, k := range keys {
   100  		indent := indent
   101  		if i == 0 {
   102  			indent = strings.Repeat(" ", 5)
   103  		}
   104  		fmt.Printf("%s%-10s %s\n", indent, meta.Type(k...), k)
   105  	}
   106  }