emissary/internal/command/agent/openwrt/uci/transform.go

108 lines
2.0 KiB
Go
Raw Normal View History

2023-02-02 10:55:24 +01:00
package uci
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"forge.cadoles.com/Cadoles/emissary/internal/command/common"
"forge.cadoles.com/Cadoles/emissary/internal/openwrt/uci"
"github.com/pkg/errors"
_ "github.com/santhosh-tekuri/jsonschema/v5/httploader"
"github.com/urfave/cli/v2"
)
const (
FormatJSON = "json"
FormatUCI = "uci"
)
func TransformCommand() *cli.Command {
flags := common.Flags()
flags = append(flags,
&cli.StringFlag{
Name: "format",
Aliases: []string{"f"},
Usage: "Define the source format ('uci' or 'json')",
Value: "uci",
},
&cli.StringFlag{
Name: "input",
Usage: "File to use as input (or '-' for STDIN)",
Aliases: []string{"i"},
TakesFile: true,
Value: "-",
},
)
return &cli.Command{
Name: "transform",
Usage: "Transform UCI configuration from/to JSON",
Flags: flags,
Action: func(ctx *cli.Context) error {
input := ctx.String("input")
format := ctx.String("format")
var reader io.Reader
switch input {
case "-":
reader = os.Stdin
default:
file, err := os.Open(input)
if err != nil {
return errors.WithStack(err)
}
defer func() {
if err := file.Close(); err != nil {
panic(errors.WithStack(err))
}
}()
reader = file
}
var conf *uci.UCI
switch format {
case FormatJSON:
decoder := json.NewDecoder(reader)
conf = uci.NewUCI()
if err := decoder.Decode(conf); err != nil {
return errors.WithStack(err)
}
fmt.Print(conf.Export())
case FormatUCI:
data, err := ioutil.ReadAll(reader)
if err != nil {
return errors.WithStack(err)
}
conf, err = uci.Parse(data)
if err != nil {
return errors.WithStack(err)
}
jsonData, err := json.MarshalIndent(conf, "", " ")
if err != nil {
return errors.WithStack(err)
}
fmt.Print(string(jsonData))
default:
return errors.Errorf("unexpected format '%s'", format)
}
return nil
},
}
}