2022-05-14 00:58:55 +00:00
|
|
|
package argh
|
|
|
|
|
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
|
|
|
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) AST() []Node {
|
2022-05-15 00:58:09 +00:00
|
|
|
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 {
|
2022-05-15 00:58:09 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-05-23 01:43:02 +00:00
|
|
|
if _, ok := node.(*StopFlag); ok {
|
2022-05-15 00:58:09 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-05-23 01:43:02 +00:00
|
|
|
if v, ok := node.(*CompoundShortFlag); ok {
|
2022-05-26 01:55:16 +00:00
|
|
|
if v.Nodes != nil {
|
|
|
|
ret = append(ret, NewQuerier(v.Nodes).AST()...)
|
|
|
|
}
|
2022-05-23 00:49:11 +00:00
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-05-23 01:43:02 +00:00
|
|
|
if v, ok := node.(*Command); ok {
|
2022-05-26 01:55:16 +00:00
|
|
|
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,
|
2022-05-26 01:55:16 +00:00
|
|
|
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
|
|
|
})
|
2022-05-15 00:58:09 +00:00
|
|
|
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
ret = append(ret, node)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret
|
|
|
|
}
|