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

     1  package main
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  
     7  	"github.com/sagernet/sing-box/common/geosite"
     8  	C "github.com/sagernet/sing-box/constant"
     9  	"github.com/sagernet/sing-box/log"
    10  	"github.com/sagernet/sing-box/option"
    11  	"github.com/sagernet/sing/common/json"
    12  
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  var commandGeositeExportOutput string
    17  
    18  const commandGeositeExportDefaultOutput = "geosite-<category>.json"
    19  
    20  var commandGeositeExport = &cobra.Command{
    21  	Use:   "export <category>",
    22  	Short: "Export geosite category as rule-set",
    23  	Args:  cobra.ExactArgs(1),
    24  	Run: func(cmd *cobra.Command, args []string) {
    25  		err := geositeExport(args[0])
    26  		if err != nil {
    27  			log.Fatal(err)
    28  		}
    29  	},
    30  }
    31  
    32  func init() {
    33  	commandGeositeExport.Flags().StringVarP(&commandGeositeExportOutput, "output", "o", commandGeositeExportDefaultOutput, "Output path")
    34  	commandGeoSite.AddCommand(commandGeositeExport)
    35  }
    36  
    37  func geositeExport(category string) error {
    38  	sourceSet, err := geositeReader.Read(category)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	var (
    43  		outputFile   *os.File
    44  		outputWriter io.Writer
    45  	)
    46  	if commandGeositeExportOutput == "stdout" {
    47  		outputWriter = os.Stdout
    48  	} else if commandGeositeExportOutput == commandGeositeExportDefaultOutput {
    49  		outputFile, err = os.Create("geosite-" + category + ".json")
    50  		if err != nil {
    51  			return err
    52  		}
    53  		defer outputFile.Close()
    54  		outputWriter = outputFile
    55  	} else {
    56  		outputFile, err = os.Create(commandGeositeExportOutput)
    57  		if err != nil {
    58  			return err
    59  		}
    60  		defer outputFile.Close()
    61  		outputWriter = outputFile
    62  	}
    63  
    64  	encoder := json.NewEncoder(outputWriter)
    65  	encoder.SetIndent("", "  ")
    66  	var headlessRule option.DefaultHeadlessRule
    67  	defaultRule := geosite.Compile(sourceSet)
    68  	headlessRule.Domain = defaultRule.Domain
    69  	headlessRule.DomainSuffix = defaultRule.DomainSuffix
    70  	headlessRule.DomainKeyword = defaultRule.DomainKeyword
    71  	headlessRule.DomainRegex = defaultRule.DomainRegex
    72  	var plainRuleSet option.PlainRuleSetCompat
    73  	plainRuleSet.Version = C.RuleSetVersion1
    74  	plainRuleSet.Options.Rules = []option.HeadlessRule{
    75  		{
    76  			Type:           C.RuleTypeDefault,
    77  			DefaultOptions: headlessRule,
    78  		},
    79  	}
    80  	return encoder.Encode(plainRuleSet)
    81  }