2022-05-14 00:58:55 +00:00
|
|
|
package argh
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
2022-05-19 00:15:31 +00:00
|
|
|
type Querier interface {
|
2022-05-23 00:49:11 +00:00
|
|
|
Program() (Command, bool)
|
2022-05-19 00:15:31 +00:00
|
|
|
TypedAST() []TypedNode
|
|
|
|
AST() []Node
|
2022-05-14 00:58:55 +00:00
|
|
|
}
|
|
|
|
|
2022-05-23 00:49:11 +00:00
|
|
|
func NewQuerier(nodes []Node) Querier {
|
|
|
|
return &defaultQuerier{nodes: nodes}
|
2022-05-19 00:15:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type defaultQuerier struct {
|
2022-05-23 00:49:11 +00:00
|
|
|
nodes []Node
|
2022-05-19 00:15:31 +00:00
|
|
|
}
|
|
|
|
|
2022-05-23 00:49:11 +00:00
|
|
|
func (dq *defaultQuerier) Program() (Command, bool) {
|
|
|
|
if len(dq.nodes) == 0 {
|
|
|
|
return Command{}, false
|
2022-05-19 00:15:31 +00:00
|
|
|
}
|
|
|
|
|
2022-05-23 00:49:11 +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{}
|
|
|
|
|
2022-05-23 00:49:11 +00:00
|
|
|
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 {
|
2022-05-15 00:58:09 +00:00
|
|
|
ret := []Node{}
|
|
|
|
|
2022-05-23 00:49:11 +00:00
|
|
|
for _, node := range dq.nodes {
|
2022-05-15 00:58:09 +00:00
|
|
|
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 {
|
2022-05-23 00:49:11 +00:00
|
|
|
ret = append(ret, NewQuerier(v.Nodes).AST()...)
|
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if v, ok := node.(Command); ok {
|
|
|
|
ret = append(ret, NewQuerier(v.Nodes).AST()...)
|
2022-05-15 00:58:09 +00:00
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
ret = append(ret, node)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret
|
|
|
|
}
|