1
0
mirror of https://github.com/StackExchange/dnscontrol.git synced 2024-05-11 05:55:12 +00:00

New Feature: JS formatter and prettifier (#917)

FYI: This is an experimental feature. It depends on an external module that may not be supported in the long term.

* PoC: JS formatter
* No default value for output file
This commit is contained in:
Jan-Philipp Benecke
2021-03-02 21:51:27 +01:00
committed by GitHub
parent 976fc20190
commit 37b02b6540
3 changed files with 102 additions and 181 deletions

69
commands/fmt.go Normal file
View File

@ -0,0 +1,69 @@
package commands
import (
"fmt"
"github.com/ditashi/jsbeautifier-go/jsbeautifier"
"github.com/urfave/cli/v2"
"io/ioutil"
)
var _ = cmd(catUtils, func() *cli.Command {
var args FmtArgs
return &cli.Command{
Name: "fmt",
Usage: "[BETA] Format and prettify a given file",
Action: func(c *cli.Context) error {
return exit(FmtFile(args))
},
Flags: args.flags(),
}
}())
type FmtArgs struct {
InputFile string
OutputFile string
}
func (args *FmtArgs) flags() []cli.Flag {
var flags []cli.Flag
flags = append(flags, &cli.StringFlag{
Name: "input",
Aliases: []string{"i"},
Value: "dnsconfig.js",
Usage: "Input file",
Destination: &args.InputFile,
})
flags = append(flags, &cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Usage: "Output file",
Destination: &args.OutputFile,
})
return flags
}
func FmtFile(args FmtArgs) error {
fileBytes, readErr := ioutil.ReadFile(args.InputFile)
if readErr != nil {
return readErr
}
opts := jsbeautifier.DefaultOptions()
str := string(fileBytes)
beautified, beautifyErr := jsbeautifier.Beautify(&str, opts)
if beautifyErr != nil {
return beautifyErr
}
if args.OutputFile != "" {
if err := ioutil.WriteFile(args.OutputFile, []byte(beautified), 0744); err != nil {
return err
} else {
fmt.Printf("File %s successfully written\n", args.OutputFile)
}
} else {
fmt.Print(beautified)
}
return nil
}