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

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/sagernet/sing-box/log"
    10  	"github.com/sagernet/sing-box/option"
    11  	E "github.com/sagernet/sing/common/exceptions"
    12  	"github.com/sagernet/sing/common/json"
    13  
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  var commandRuleSetFormatFlagWrite bool
    18  
    19  var commandRuleSetFormat = &cobra.Command{
    20  	Use:   "format <source-path>",
    21  	Short: "Format rule-set json",
    22  	Args:  cobra.ExactArgs(1),
    23  	Run: func(cmd *cobra.Command, args []string) {
    24  		err := formatRuleSet(args[0])
    25  		if err != nil {
    26  			log.Fatal(err)
    27  		}
    28  	},
    29  }
    30  
    31  func init() {
    32  	commandRuleSetFormat.Flags().BoolVarP(&commandRuleSetFormatFlagWrite, "write", "w", false, "write result to (source) file instead of stdout")
    33  	commandRuleSet.AddCommand(commandRuleSetFormat)
    34  }
    35  
    36  func formatRuleSet(sourcePath string) error {
    37  	var (
    38  		reader io.Reader
    39  		err    error
    40  	)
    41  	if sourcePath == "stdin" {
    42  		reader = os.Stdin
    43  	} else {
    44  		reader, err = os.Open(sourcePath)
    45  		if err != nil {
    46  			return err
    47  		}
    48  	}
    49  	content, err := io.ReadAll(reader)
    50  	if err != nil {
    51  		return err
    52  	}
    53  	plainRuleSet, err := json.UnmarshalExtended[option.PlainRuleSetCompat](content)
    54  	if err != nil {
    55  		return err
    56  	}
    57  	buffer := new(bytes.Buffer)
    58  	encoder := json.NewEncoder(buffer)
    59  	encoder.SetIndent("", "  ")
    60  	err = encoder.Encode(plainRuleSet)
    61  	if err != nil {
    62  		return E.Cause(err, "encode config")
    63  	}
    64  	outputPath, _ := filepath.Abs(sourcePath)
    65  	if !commandRuleSetFormatFlagWrite || sourcePath == "stdin" {
    66  		os.Stdout.WriteString(buffer.String() + "\n")
    67  		return nil
    68  	}
    69  	if bytes.Equal(content, buffer.Bytes()) {
    70  		return nil
    71  	}
    72  	output, err := os.Create(sourcePath)
    73  	if err != nil {
    74  		return E.Cause(err, "open output")
    75  	}
    76  	_, err = output.Write(buffer.Bytes())
    77  	output.Close()
    78  	if err != nil {
    79  		return E.Cause(err, "write output")
    80  	}
    81  	os.Stderr.WriteString(outputPath + "\n")
    82  	return nil
    83  }