@@ 2,6 2,7 @@ package facts
import (
"bytes"
+ "encoding/json"
"fmt"
"io"
"io/fs"
@@ 156,3 157,7 @@ func (f *Fact) Name() string {
func (f *Fact) Remote() bool {
return f.network != "" && f.addr != ""
}
+
+func (f *Fact) MarshalJSON() ([]byte, error) {
+ return json.Marshal(f.String())
+}
@@ 2,6 2,7 @@ package facts
import (
"context"
+ "encoding/json"
"fmt"
"io"
"io/fs"
@@ 185,3 186,10 @@ func (f *Facts) Names() []string {
return names
}
+
+func (f *Facts) MarshalJSON() ([]byte, error) {
+ f.mu.RLock()
+ defer f.mu.RUnlock()
+
+ return json.Marshal(f.facts)
+}
@@ 17,9 17,9 @@ import (
"git.sr.ht/~nesv/govern/internal/state"
"git.sr.ht/~nesv/govern/internal/template"
+ "github.com/hashicorp/go-multierror"
"github.com/nesv/cmndr"
"github.com/pkg/errors"
- kerrors "k8s.io/apimachinery/pkg/util/errors"
)
func main() {
@@ 42,6 42,7 @@ func main() {
root.Flags.BoolVar(&cmd.withSignals, "with-signals", false, "resources: Show the signals a resource can send")
root.Flags.BoolVar(&cmd.withAttributes, "with-attributes", false, "resources: Show resource attributes with --pretend, -n")
root.Flags.BoolVarP(&cmd.pretend, "pretend", "n", false, "apply: Do not apply any states")
+ root.Flags.StringVar(&cmd.format, "format", "table", "facts: Set the output format [table, json]")
facts := cmndr.New("facts", cmd.showFacts)
facts.Description = "Collect facts for the current host"
@@ 86,6 87,7 @@ type command struct {
configPath string
factsDirs []string
factsIgnore []string
+ format string
stateDirs []string
statesIgnore []string
templateDirs []string
@@ 124,11 126,24 @@ func (c *command) showFacts(cmd *cmndr.Cmd, args []string) error {
return errors.Wrap(err, "collect facts")
}
- if _, err := f.WriteTo(os.Stdout); err != nil {
- return errors.Wrap(err, "write to stdout")
+ switch c.format {
+ case "json":
+ p, err := f.MarshalJSON()
+ if err != nil {
+ return errors.Wrap(err, "marshal json")
+ }
+
+ fmt.Fprintf(os.Stdout, "%s\n", p)
+ return nil
+
+ case "table":
+ if _, err := f.WriteTo(os.Stdout); err != nil {
+ return errors.Wrap(err, "write to stdout")
+ }
+ return nil
}
- return nil
+ return fmt.Errorf("unsupported format: %s", c.format)
}
func (c *command) collectFacts() (*facts.Facts, error) {
@@ 273,7 288,7 @@ func (c *command) applyStates(cmd *cmndr.Cmd, args []string) error {
errs = append(errs, fmt.Errorf("flush tabwriter: %w", err))
}
- return kerrors.NewAggregate(errs)
+ return multierror.Append(nil, errs...)
}
func (c *command) showResources(cmd *cmndr.Cmd, args []string) error {