github.com/sagernet/sing-box@v1.9.0-rc.20/cmd/sing-box/cmd_format.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/sagernet/sing-box/log"
     9  	E "github.com/sagernet/sing/common/exceptions"
    10  	"github.com/sagernet/sing/common/json"
    11  	"github.com/sagernet/sing/common/json/badjson"
    12  
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  var commandFormatFlagWrite bool
    17  
    18  var commandFormat = &cobra.Command{
    19  	Use:   "format",
    20  	Short: "Format configuration",
    21  	Run: func(cmd *cobra.Command, args []string) {
    22  		err := format()
    23  		if err != nil {
    24  			log.Fatal(err)
    25  		}
    26  	},
    27  	Args: cobra.NoArgs,
    28  }
    29  
    30  func init() {
    31  	commandFormat.Flags().BoolVarP(&commandFormatFlagWrite, "write", "w", false, "write result to (source) file instead of stdout")
    32  	mainCommand.AddCommand(commandFormat)
    33  }
    34  
    35  func format() error {
    36  	optionsList, err := readConfig()
    37  	if err != nil {
    38  		return err
    39  	}
    40  	for _, optionsEntry := range optionsList {
    41  		optionsEntry.options, err = badjson.Omitempty(optionsEntry.options)
    42  		if err != nil {
    43  			return err
    44  		}
    45  		buffer := new(bytes.Buffer)
    46  		encoder := json.NewEncoder(buffer)
    47  		encoder.SetIndent("", "  ")
    48  		err = encoder.Encode(optionsEntry.options)
    49  		if err != nil {
    50  			return E.Cause(err, "encode config")
    51  		}
    52  		outputPath, _ := filepath.Abs(optionsEntry.path)
    53  		if !commandFormatFlagWrite {
    54  			if len(optionsList) > 1 {
    55  				os.Stdout.WriteString(outputPath + "\n")
    56  			}
    57  			os.Stdout.WriteString(buffer.String() + "\n")
    58  			continue
    59  		}
    60  		if bytes.Equal(optionsEntry.content, buffer.Bytes()) {
    61  			continue
    62  		}
    63  		output, err := os.Create(optionsEntry.path)
    64  		if err != nil {
    65  			return E.Cause(err, "open output")
    66  		}
    67  		_, err = output.Write(buffer.Bytes())
    68  		output.Close()
    69  		if err != nil {
    70  			return E.Cause(err, "write output")
    71  		}
    72  		os.Stderr.WriteString(outputPath + "\n")
    73  	}
    74  	return nil
    75  }