argh/querier.go

81 lines
1.2 KiB
Go
Raw Normal View History

2022-05-14 00:58:55 +00:00
package argh
import "fmt"
2022-05-19 00:15:31 +00:00
type Querier interface {
Program() (Command, bool)
2022-05-19 00:15:31 +00:00
TypedAST() []TypedNode
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) TypedAST() []TypedNode {
2022-05-14 00:58:55 +00:00
ret := []TypedNode{}
for _, node := range dq.nodes {
2022-05-14 00:58:55 +00:00
if _, ok := node.(ArgDelimiter); ok {
continue
}
if _, ok := node.(StopFlag); ok {
continue
}
ret = append(
ret,
TypedNode{
Type: fmt.Sprintf("%T", node),
Node: node,
},
)
}
return ret
}
2022-05-19 00:15:31 +00:00
func (dq *defaultQuerier) AST() []Node {
ret := []Node{}
for _, node := range dq.nodes {
if _, ok := node.(ArgDelimiter); ok {
continue
}
if _, ok := node.(StopFlag); ok {
continue
}
2022-05-15 18:22:56 +00:00
if v, ok := node.(CompoundShortFlag); ok {
ret = append(ret, NewQuerier(v.Nodes).AST()...)
continue
}
if v, ok := node.(Command); ok {
ret = append(ret, NewQuerier(v.Nodes).AST()...)
continue
}
ret = append(ret, node)
}
return ret
}