box-o-sand/argh/querier.go

88 lines
1.3 KiB
Go
Raw Normal View History

2022-05-14 00:58:55 +00:00
package argh
2022-05-19 00:15:31 +00:00
type Querier interface {
Program() (Command, bool)
2022-05-19 00:15:31 +00:00
AST() []Node
2022-05-14 00:58:55 +00:00
}
func NewQuerier(nodes []Node) Querier {
return &defaultQuerier{nodes: nodes}
2022-05-19 00:15:31 +00:00
}
type defaultQuerier struct {
nodes []Node
2022-05-19 00:15:31 +00:00
}
func (dq *defaultQuerier) Program() (Command, bool) {
if len(dq.nodes) == 0 {
return Command{}, false
2022-05-19 00:15:31 +00:00
}
v, ok := dq.nodes[0].(Command)
2022-05-19 00:15:31 +00:00
return v, ok
}
func (dq *defaultQuerier) AST() []Node {
ret := []Node{}
2022-05-23 01:43:02 +00:00
for i, node := range dq.nodes {
tracef("AST i=%d node type=%T", i, node)
if _, ok := node.(*ArgDelimiter); ok {
continue
}
2022-05-23 01:43:02 +00:00
if _, ok := node.(*StopFlag); ok {
continue
}
2022-05-23 01:43:02 +00:00
if v, ok := node.(*CompoundShortFlag); ok {
if v.Nodes != nil {
ret = append(ret, NewQuerier(v.Nodes).AST()...)
}
continue
}
2022-05-23 01:43:02 +00:00
if v, ok := node.(*Command); ok {
astNodes := NewQuerier(v.Nodes).AST()
if len(astNodes) == 0 {
astNodes = nil
}
2022-05-23 01:43:02 +00:00
ret = append(
ret,
&Command{
Name: v.Name,
Values: v.Values,
Nodes: astNodes,
})
continue
}
if v, ok := node.(*Flag); ok {
astNodes := NewQuerier(v.Nodes).AST()
if len(astNodes) == 0 {
astNodes = nil
}
ret = append(
ret,
&Flag{
Name: v.Name,
Values: v.Values,
Nodes: astNodes,
2022-05-23 01:43:02 +00:00
})
continue
}
ret = append(ret, node)
}
return ret
}