-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitem.go
74 lines (66 loc) · 1.5 KB
/
item.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package narg
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/nochso/narg/token"
)
// ItemSlice is a list of items.
type ItemSlice []Item
// Item represents a single block consisting of at least the name.
//
// narg input showing what part of an Item it's parsed into:
//
// Name Args[0] Args[1] {
// Children[0].Name Children[0].Args[0]
// }
type Item struct {
Name string
Args []string
Children ItemSlice
}
// String returns an indented string representation.
func (s ItemSlice) String() string {
buf := &bytes.Buffer{}
for i, item := range s {
if i > 0 {
buf.WriteByte('\n')
}
item.writeString(buf, 0)
}
return buf.String()
}
// Filter returns all items filtered by name.
// The comparison is case-insensitive.
func (s ItemSlice) Filter(key string) ItemSlice {
out := ItemSlice{}
key = strings.ToLower(key)
for _, itm := range s {
if strings.ToLower(itm.Name) == key {
out = append(out, itm)
}
}
return out
}
// String returns the string representation of an Item and its Children.
func (i Item) String() string {
buf := &bytes.Buffer{}
i.writeString(buf, 0)
return buf.String()
}
func (i Item) writeString(w io.Writer, indent int) {
prefix := strings.Repeat("\t", indent)
fmt.Fprintf(w, "%s%s", prefix, token.Quote(i.Name))
for _, arg := range i.Args {
fmt.Fprintf(w, " %s", token.Quote(arg))
}
if len(i.Children) > 0 {
fmt.Fprint(w, " {\n")
for _, child := range i.Children {
child.writeString(w, indent+1)
fmt.Fprintln(w)
}
fmt.Fprintf(w, "%s}", prefix)
}
}