github.com/yaling888/clash@v1.53.0/component/script/rule_providers.go (about)

     1  package script
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"go.starlark.net/starlark"
     8  	"go.starlark.net/starlarkstruct"
     9  
    10  	C "github.com/yaling888/clash/constant"
    11  )
    12  
    13  var (
    14  	_ starlark.Mapping = (*RuleProviders)(nil)
    15  
    16  	ruleProviderModules = make(map[string]*starlarkstruct.Module)
    17  )
    18  
    19  type RuleProviders struct {
    20  	starlark.Value
    21  }
    22  
    23  func (r *RuleProviders) Type() string {
    24  	return "rule_providers"
    25  }
    26  
    27  func (r *RuleProviders) Get(value starlark.Value) (v starlark.Value, found bool, err error) {
    28  	defer func() {
    29  		if err != nil {
    30  			err = fmt.Errorf("call rule_providers error: %w", err)
    31  		}
    32  	}()
    33  
    34  	var name starlark.String
    35  	if name, found = value.(starlark.String); !found {
    36  		err = fmt.Errorf("invalid key type")
    37  		return
    38  	}
    39  
    40  	providerName := name.GoString()
    41  	providerName = strings.TrimPrefix(providerName, "geosite:")
    42  
    43  	if _, found = C.GetScriptRuleProviders()[providerName]; !found {
    44  		err = fmt.Errorf("provider [%s] not found", providerName)
    45  		return
    46  	}
    47  
    48  	module := ruleProviderModules[providerName]
    49  	if module == nil {
    50  		module = &starlarkstruct.Module{
    51  			Name: "match_" + providerName,
    52  			Members: starlark.StringDict{
    53  				"match": starlark.NewBuiltin(providerName, matchRuleProvider),
    54  			},
    55  		}
    56  		ruleProviderModules[providerName] = module
    57  	}
    58  
    59  	v = module
    60  	return
    61  }
    62  
    63  func newRuleProviders() starlark.Value {
    64  	return &RuleProviders{}
    65  }