You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

81 lines
1.5 KiB

package main
import (
"bytes"
"encoding/json"
"io"
"os"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
// Encoder represents an object that encodes another internally
type Encoder interface {
Encode(any) error
}
// Encoding represents a type of [Encoder]
type Encoding int
const (
// UndefinedEncoding implies the default encoding
UndefinedEncoding Encoding = iota
// JSONEncoding represents JSON encoding
JSONEncoding
// YAMLEncoding represents YAML encoding
YAMLEncoding
)
// NewJSONEncoder returns a JSON [Encoder] to work on the given [io.Writer]
func NewJSONEncoder(w io.Writer) Encoder {
enc := json.NewEncoder(w)
enc.SetIndent(``, ` `)
return enc
}
// NewYAMLEncoder returns a YAML [Encoder] to work on the given [io.Writer]
func NewYAMLEncoder(w io.Writer) Encoder {
enc := yaml.NewEncoder(w)
enc.SetIndent(2)
return enc
}
const encoding = YAMLEncoding
// Command
var dumpCmd = &cobra.Command{
Use: "dump",
Short: "generates a text representation of the config",
PreRun: setVerbosity,
RunE: func(_ *cobra.Command, _ []string) error {
var buf bytes.Buffer
var enc Encoder
m, err := cfg.LoadZones(true)
if err != nil {
return err
}
switch encoding {
case JSONEncoding:
enc = NewJSONEncoder(&buf)
default:
enc = NewYAMLEncoder(&buf)
}
if err = enc.Encode(m); err != nil {
return err
}
if _, err = buf.WriteTo(os.Stdout); err != nil {
return err
}
return nil
},
}
func init() {
rootCmd.AddCommand(dumpCmd)
}