feat: support convert mrs format back to text format

This commit is contained in:
wwqgtxx
2024-07-28 10:07:37 +08:00
parent 1db3e4583b
commit c830b8aaf7
10 changed files with 137 additions and 12 deletions

View File

@@ -9,6 +9,8 @@ import (
C "github.com/metacubex/mihomo/constant"
P "github.com/metacubex/mihomo/constant/provider"
"github.com/metacubex/mihomo/log"
"golang.org/x/exp/slices"
)
type domainStrategy struct {
@@ -78,6 +80,26 @@ func (d *domainStrategy) WriteMrs(w io.Writer) error {
return d.domainSet.WriteBin(w)
}
func (d *domainStrategy) DumpMrs(f func(key string) bool) {
if d.domainSet != nil {
var keys []string
d.domainSet.Foreach(func(key string) bool {
keys = append(keys, key)
return true
})
slices.Sort(keys)
for _, key := range keys {
if _, ok := slices.BinarySearch(keys, "+."+key); ok {
continue // ignore the rules added by trie internal processing
}
if !f(key) {
return
}
}
}
}
var _ mrsRuleStrategy = (*domainStrategy)(nil)
func NewDomainStrategy() *domainStrategy {

View File

@@ -3,6 +3,7 @@ package provider
import (
"errors"
"io"
"net/netip"
"github.com/metacubex/mihomo/component/cidr"
C "github.com/metacubex/mihomo/constant"
@@ -82,6 +83,14 @@ func (i *ipcidrStrategy) WriteMrs(w io.Writer) error {
return i.cidrSet.WriteBin(w)
}
func (i *ipcidrStrategy) DumpMrs(f func(key string) bool) {
if i.cidrSet != nil {
i.cidrSet.Foreach(func(prefix netip.Prefix) bool {
return f(prefix.String())
})
}
}
func (i *ipcidrStrategy) ToIpCidr() *netipx.IPSet {
return i.cidrSet.ToIPSet()
}

View File

@@ -3,6 +3,7 @@ package provider
import (
"encoding/binary"
"errors"
"fmt"
"io"
"os"
@@ -21,6 +22,17 @@ func ConvertToMrs(buf []byte, behavior P.RuleBehavior, format P.RuleFormat, w io
return errors.New("empty rule")
}
if _strategy, ok := strategy.(mrsRuleStrategy); ok {
if format == P.MrsRule { // export to TextRule
_strategy.DumpMrs(func(key string) bool {
_, err = fmt.Fprintln(w, key)
if err != nil {
return false
}
return true
})
return nil
}
var encoder *zstd.Encoder
encoder, err = zstd.NewWriter(w)
if err != nil {

View File

@@ -58,6 +58,7 @@ type mrsRuleStrategy interface {
ruleStrategy
FromMrs(r io.Reader, count int) error
WriteMrs(w io.Writer) error
DumpMrs(f func(key string) bool)
}
func (rp *ruleSetProvider) Type() P.ProviderType {