sing-box/cmd/sing-box/cmd_format.go

76 lines
1.7 KiB
Go
Raw Normal View History

2022-07-04 08:59:27 +00:00
package main
import (
"bytes"
"os"
"path/filepath"
2022-07-12 07:17:29 +00:00
"github.com/sagernet/sing-box/log"
2022-08-13 10:36:49 +00:00
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
"github.com/sagernet/sing/common/json/badjson"
2022-07-06 07:01:09 +00:00
2022-07-04 08:59:27 +00:00
"github.com/spf13/cobra"
)
var commandFormatFlagWrite bool
var commandFormat = &cobra.Command{
Use: "format",
2022-07-04 09:08:28 +00:00
Short: "Format configuration",
2022-08-13 10:36:49 +00:00
Run: func(cmd *cobra.Command, args []string) {
err := format()
if err != nil {
log.Fatal(err)
}
},
Args: cobra.NoArgs,
2022-07-04 08:59:27 +00:00
}
func init() {
commandFormat.Flags().BoolVarP(&commandFormatFlagWrite, "write", "w", false, "write result to (source) file instead of stdout")
2022-08-13 10:36:49 +00:00
mainCommand.AddCommand(commandFormat)
2022-07-04 08:59:27 +00:00
}
2022-08-13 10:36:49 +00:00
func format() error {
2023-03-18 11:15:28 +00:00
optionsList, err := readConfig()
if err != nil {
return err
}
for _, optionsEntry := range optionsList {
optionsEntry.options, err = badjson.Omitempty(optionsEntry.options)
if err != nil {
return err
}
2023-03-18 11:15:28 +00:00
buffer := new(bytes.Buffer)
encoder := json.NewEncoder(buffer)
encoder.SetIndent("", " ")
err = encoder.Encode(optionsEntry.options)
if err != nil {
return E.Cause(err, "encode config")
}
outputPath, _ := filepath.Abs(optionsEntry.path)
if !commandFormatFlagWrite {
if len(optionsList) > 1 {
os.Stdout.WriteString(outputPath + "\n")
}
os.Stdout.WriteString(buffer.String() + "\n")
continue
}
if bytes.Equal(optionsEntry.content, buffer.Bytes()) {
continue
}
output, err := os.Create(optionsEntry.path)
if err != nil {
return E.Cause(err, "open output")
}
_, err = output.Write(buffer.Bytes())
output.Close()
if err != nil {
return E.Cause(err, "write output")
}
os.Stderr.WriteString(outputPath + "\n")
}
return nil
}