Fix -pm <value> parsing and add comma-separated multi-fact -F (#14)
Two related query-ergonomics fixes surfaced while using the tool interactively.
## 1. `-pm <value>` failed with `unknown command "k8s"`
pflag does not attach a space-separated value to a string flag (`-m`) grouped with a bool flag (`-p`), so `k8s` was left as a stray positional. Only `-pm=k8s` or the un-grouped `-p -m k8s` worked.
- Allow one positional argument (`cobra.MaximumNArgs(1)`) and fall back to it for the match value when `-m` is empty (`matchValue()`). `-pm/-im/-ipm <value>` and a bare `-p <value>` now all work; `-m` still wins when both are given.
## 2. `-F a,b` (multiple facts) returned `{}`
`-jF ipaddress,enc_role` queried a single fact literally named `ipaddress,enc_role`.
- Split `-F` on commas (`splitFactNames`) and match any of them via an `or` over `["=","name",<n>]` clauses (`nameFilter`); a single name keeps the plain `=` form.
- Key JSON output by each result's real fact name so all requested facts appear under the host.
Both paths have unit tests; verified live: `node-lookup -R -pm externaldns | node-lookup -jF ipaddress,enc_role` returns both facts per host. AGENTS.md updated.
Reviewed-on: #14
Co-authored-by: Ben Vincent <ben@unkin.net>
Co-committed-by: Ben Vincent <ben@unkin.net>
This commit was merged in pull request #14.
This commit is contained in:
@@ -110,6 +110,31 @@ type fact struct {
|
||||
Value json.RawMessage `json:"value"`
|
||||
}
|
||||
|
||||
// splitFactNames splits a comma-separated -F value into trimmed, non-empty
|
||||
// names, so `-F ipaddress,enc_role` queries both facts.
|
||||
func splitFactNames(factName string) []string {
|
||||
var names []string
|
||||
for _, n := range strings.Split(factName, ",") {
|
||||
if n = strings.TrimSpace(n); n != "" {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// nameFilter returns a PQL filter matching any of the given fact names: a plain
|
||||
// equality for one name, an "or" over per-name equalities for several.
|
||||
func nameFilter(names []string) []interface{} {
|
||||
if len(names) == 1 {
|
||||
return []interface{}{"=", "name", names[0]}
|
||||
}
|
||||
or := []interface{}{"or"}
|
||||
for _, n := range names {
|
||||
or = append(or, []interface{}{"=", "name", n})
|
||||
}
|
||||
return or
|
||||
}
|
||||
|
||||
func buildQuery(node, factName, match, roleFact string, showRole, partial, inverse bool) string {
|
||||
type filter = []interface{}
|
||||
var filters []filter
|
||||
@@ -117,8 +142,8 @@ func buildQuery(node, factName, match, roleFact string, showRole, partial, inver
|
||||
if node != "" {
|
||||
filters = append(filters, filter{"=", "certname", node})
|
||||
}
|
||||
if factName != "" {
|
||||
filters = append(filters, filter{"=", "name", factName})
|
||||
if names := splitFactNames(factName); len(names) > 0 {
|
||||
filters = append(filters, nameFilter(names))
|
||||
} else if showRole {
|
||||
filters = append(filters, filter{"=", "name", roleFact})
|
||||
}
|
||||
@@ -236,6 +261,46 @@ func stdinReader(f *os.File) (*bufio.Reader, bool) {
|
||||
return r, true
|
||||
}
|
||||
|
||||
// matchValue resolves the value to match against. The -m/--match flag wins; if
|
||||
// it is empty, the (optional) positional argument is used instead. The
|
||||
// positional fallback exists so combined shorthands like `-pm k8s` work — pflag
|
||||
// leaves the space-separated `k8s` as a positional rather than attaching it to
|
||||
// the grouped -m flag.
|
||||
func matchValue(flagMatch string, args []string) string {
|
||||
if flagMatch != "" {
|
||||
return flagMatch
|
||||
}
|
||||
if len(args) > 0 {
|
||||
return args[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// factsByHost groups collected facts into {certname: {factname: value}}. Each
|
||||
// value is keyed by the fact's real name, so multiple -F facts each appear
|
||||
// under the host; it falls back to the -F string, the role fact (with -R), or
|
||||
// "value" only when a result carries no name. Shared by the -j and -A outputs.
|
||||
func factsByHost(collected []fact, factName, roleFact string, showRole bool) map[string]map[string]interface{} {
|
||||
out := map[string]map[string]interface{}{}
|
||||
for _, f := range collected {
|
||||
if _, ok := out[f.Certname]; !ok {
|
||||
out[f.Certname] = map[string]interface{}{}
|
||||
}
|
||||
key := f.Name
|
||||
if key == "" {
|
||||
if key = factName; key == "" {
|
||||
if showRole {
|
||||
key = roleFact
|
||||
} else {
|
||||
key = "value"
|
||||
}
|
||||
}
|
||||
}
|
||||
out[f.Certname][key] = valueAny(f.Value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func allFactsForNode(puppetDBURL, node string) ([]fact, error) {
|
||||
query, _ := json.Marshal([]interface{}{"=", "certname", node})
|
||||
return queryPuppetDB(puppetDBURL, string(query))
|
||||
@@ -306,25 +371,10 @@ func run(cfg config, nodeName, factName, match string, showRole, partial, invers
|
||||
|
||||
switch {
|
||||
case jsonMode:
|
||||
hostFactMap := map[string]map[string]interface{}{}
|
||||
for _, f := range collected {
|
||||
if _, ok := hostFactMap[f.Certname]; !ok {
|
||||
hostFactMap[f.Certname] = map[string]interface{}{}
|
||||
}
|
||||
key := factName
|
||||
if key == "" {
|
||||
if showRole {
|
||||
key = cfg.RoleFact
|
||||
} else {
|
||||
key = "value"
|
||||
}
|
||||
}
|
||||
hostFactMap[f.Certname][key] = valueAny(f.Value)
|
||||
}
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(hostFactMap)
|
||||
_ = enc.Encode(factsByHost(collected, factName, cfg.RoleFact, showRole))
|
||||
|
||||
case count:
|
||||
values := stdinLines
|
||||
@@ -334,10 +384,11 @@ func run(cfg config, nodeName, factName, match string, showRole, partial, invers
|
||||
fmt.Println(strings.Join(countResults(values), "\n"))
|
||||
|
||||
case ansible:
|
||||
// Attach each host's queried fact(s) as inventory host vars, e.g.
|
||||
// `-F ipaddress,enc_role -A` yields hosts with ipaddress + enc_role set.
|
||||
hosts := map[string]interface{}{}
|
||||
for _, line := range returnData {
|
||||
host := strings.Fields(line)[0]
|
||||
hosts[host] = map[string]interface{}{}
|
||||
for host, vars := range factsByHost(collected, factName, cfg.RoleFact, showRole) {
|
||||
hosts[host] = vars
|
||||
}
|
||||
inventory := map[string]interface{}{
|
||||
"all": map[string]interface{}{"hosts": hosts},
|
||||
@@ -389,8 +440,14 @@ func main() {
|
||||
)
|
||||
|
||||
rootCmd := &cobra.Command{
|
||||
Use: appName,
|
||||
Use: appName + " [value]",
|
||||
Short: "Query PuppetDB for nodes.",
|
||||
// Accept an optional positional match value in addition to -m. This makes
|
||||
// combined shorthands like `-pm k8s` work: pflag does not attach a
|
||||
// space-separated value to a string flag grouped with a bool flag (only
|
||||
// `-pm=k8s` or `-p -m k8s` do), so `k8s` arrives here as a positional
|
||||
// argument instead. Falling back to it keeps the ergonomic form working.
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
|
||||
if cmd.Flags().Changed("url") {
|
||||
cfg.PuppetDBURL = puppetDBURL
|
||||
@@ -398,14 +455,14 @@ func main() {
|
||||
return nil
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return run(cfg, nodeName, factName, match, showRole, partial, inverse, nodeOnly, valueOnly, count, ansible, jsonMode, allFacts)
|
||||
return run(cfg, nodeName, factName, matchValue(match, args), showRole, partial, inverse, nodeOnly, valueOnly, count, ansible, jsonMode, allFacts)
|
||||
},
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
f := rootCmd.Flags()
|
||||
f.StringVarP(&nodeName, "node", "n", "", "Node name")
|
||||
f.StringVarP(&factName, "fact", "F", "", "Fact name")
|
||||
f.StringVarP(&factName, "fact", "F", "", "Fact name (comma-separated for several, e.g. -F ipaddress,enc_role)")
|
||||
f.BoolVarP(&showRole, "role", "R", false, "Show role fact ("+defaultRoleFact+" by default)")
|
||||
f.StringVarP(&match, "match", "m", "", "Value to match (use with -p and/or -i)")
|
||||
f.BoolVarP(&partial, "partial", "p", false, "Partial/regex match modifier (combine with -m)")
|
||||
|
||||
Reference in New Issue
Block a user