doggo/cmd/parse.go

56 lines
1.6 KiB
Go
Raw Normal View History

2020-12-10 10:39:05 +01:00
package main
2020-12-10 17:14:04 +01:00
import (
"strings"
2020-12-10 10:39:05 +01:00
2020-12-10 17:14:04 +01:00
"github.com/miekg/dns"
"github.com/urfave/cli/v2"
)
2020-12-10 10:39:05 +01:00
2020-12-10 17:14:04 +01:00
func (hub *Hub) loadQueryArgs(c *cli.Context) error {
2020-12-12 07:16:13 +01:00
err := hub.loadFreeArgs(c)
2020-12-10 17:14:04 +01:00
if err != nil {
cli.Exit("Error parsing arguments", -1)
}
2020-12-12 11:57:13 +01:00
err = hub.initResolver(c)
2020-12-10 17:14:04 +01:00
if err != nil {
cli.Exit("Error parsing nameservers", -1)
}
hub.loadFallbacks(c)
return err
}
2020-12-10 10:39:05 +01:00
2020-12-12 07:16:13 +01:00
// loadFreeArgs tries to parse all the arguments
2020-12-10 17:14:04 +01:00
// given to the CLI. These arguments don't have any specific
// order so we have to deduce based on the pattern of argument.
// For eg, a nameserver must always begin with `@`. In this
// pattern we deduce the arguments and map it to internal query
// options. In case an argument isn't able to fit in any of the existing
// pattern it is considered to be a "query name".
2020-12-12 07:16:13 +01:00
func (hub *Hub) loadFreeArgs(c *cli.Context) error {
2020-12-10 17:14:04 +01:00
for _, arg := range c.Args().Slice() {
if strings.HasPrefix(arg, "@") {
2020-12-11 11:35:16 +01:00
hub.QueryFlags.Nameservers.Set(strings.Trim(arg, "@"))
2020-12-10 17:14:04 +01:00
} else if _, ok := dns.StringToType[strings.ToUpper(arg)]; ok {
hub.QueryFlags.QTypes.Set(arg)
} else if _, ok := dns.StringToClass[strings.ToUpper(arg)]; ok {
hub.QueryFlags.QClasses.Set(arg)
} else {
// if nothing matches, consider it's a query name.
hub.QueryFlags.QNames.Set(arg)
}
}
return nil
2020-12-10 10:39:05 +01:00
}
2020-12-10 17:14:04 +01:00
// loadFallbacks sets fallbacks for options
// that are not specified by the user.
func (hub *Hub) loadFallbacks(c *cli.Context) {
if len(hub.QueryFlags.QTypes.Value()) == 0 {
hub.QueryFlags.QTypes.Set("A")
}
if len(hub.QueryFlags.QClasses.Value()) == 0 {
hub.QueryFlags.QClasses.Set("IN")
}
}