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/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 }, } }