parse durations

master
Jordan Orelli 10 years ago
parent 480bffc761
commit 134442343c

@ -8,6 +8,7 @@ import (
"sort"
"strconv"
"strings"
"time"
)
type nodeType int
@ -23,6 +24,7 @@ const (
n_object
n_variable
n_bool
n_duration
)
var indent = " "
@ -508,3 +510,32 @@ func (b *boolNode) pretty(w io.Writer, prefix string) error {
func (b *boolNode) eval(ctx *context) (interface{}, error) {
return bool(*b), nil
}
type durationNode time.Duration
func (d *durationNode) Type() nodeType {
return n_duration
}
func (d *durationNode) parse(p *parser) error {
t := p.next()
if t.t != t_duration {
return fmt.Errorf("unexpected %s token while parsing duration", t.t)
}
v, err := time.ParseDuration(t.s)
if err != nil {
return fmt.Errorf("unable to parse duration: %s", err)
}
*d = durationNode(v)
return nil
}
func (d *durationNode) pretty(w io.Writer, prefix string) error {
fmt.Fprintf(w, "%sdur:\n", prefix)
fmt.Fprintf(w, "%s%s\n", prefix+indent, time.Duration(*d).String())
return nil
}
func (d *durationNode) eval(ctx *context) (interface{}, error) {
return *d, nil
}

@ -17,6 +17,7 @@ var nodes = map[tokenType]func(p *parser) node{
t_object_start: func(p *parser) node { p.next(); return &objectNode{} },
t_variable: func(p *parser) node { return new(variableNode) },
t_bool: func(p *parser) node { return new(boolNode) },
t_duration: func(p *parser) node { return new(durationNode) },
}
var DefaultPath = "./config.moon"

@ -0,0 +1,11 @@
dur_1: 30s
dur_2: 300ms
dur_3: -1.5h
dur_4: 2h45m
dur_5: 9ns
dur_6: 18us
dur_7: 45µs
dur_8: 900ms
dur_9: 275s
dur_10: 89m
dur_11: 927h

@ -0,0 +1,67 @@
root:
assign:
name:
dur_1
value:
dur:
30s
assign:
name:
dur_2
value:
dur:
300ms
assign:
name:
dur_3
value:
dur:
-1h30m0s
assign:
name:
dur_4
value:
dur:
2h45m0s
assign:
name:
dur_5
value:
dur:
9ns
assign:
name:
dur_6
value:
dur:
18us
assign:
name:
dur_7
value:
dur:
45us
assign:
name:
dur_8
value:
dur:
900ms
assign:
name:
dur_9
value:
dur:
4m35s
assign:
name:
dur_10
value:
dur:
1h29m0s
assign:
name:
dur_11
value:
dur:
927h0m0s
Loading…
Cancel
Save