Skip to content

Commit

Permalink
feat: no prefix is required to get format option
Browse files Browse the repository at this point in the history
  • Loading branch information
JinnLynn committed Jun 13, 2024
1 parent 8135f76 commit fb043c3
Show file tree
Hide file tree
Showing 11 changed files with 59 additions and 45 deletions.
8 changes: 4 additions & 4 deletions example/config.ini
Original file line number Diff line number Diff line change
Expand Up @@ -168,19 +168,19 @@ ip-family = 6
_order = 100

[job:copy]
copy-from = https://github.com/gaoyifan/china-operator-ip/raw/ip-lists/china6.txt
copy-source = https://github.com/gaoyifan/china-operator-ip/raw/ip-lists/china6.txt
output = ./asn-china-ipv6.txt

[job:copy]
copy-from = https://github.com/gaoyifan/china-operator-ip/raw/ip-lists/china.txt
copy-source = https://github.com/gaoyifan/china-operator-ip/raw/ip-lists/china.txt
output = ./asn-china-ipv4.txt

[job:copy]
copy-from = https://github.com/sapics/ip-location-db/raw/main/geolite2-country/geolite2-country-ipv6.csv
copy-source = https://github.com/sapics/ip-location-db/raw/main/geolite2-country/geolite2-country-ipv6.csv
output = ./geolite2-country-ipv6.csv

[job:copy]
copy-from = https://github.com/sapics/ip-location-db/raw/main/geolite2-country/geolite2-country-ipv4.csv
copy-source = https://github.com/sapics/ip-location-db/raw/main/geolite2-country/geolite2-country-ipv4.csv
output = ./geolite2-country-ipv4.csv

[job:qtx]
Expand Down
28 changes: 21 additions & 7 deletions src/genpac/format/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ def decorator(fmt_cls):
return decorator


class _FmtOption(Namespace):
def __init__(self, original, prefix):
self._prefix = prefix
self._original = original
for k, v in original.dict().items():
if not k.startswith(f'{prefix}_'):
continue
setattr(self, k.replace(f'{prefix}_', '', 1), v)

def __getattr__(self, name):
raise AttributeError(f'格式\'{self._prefix}\'没有自有设置\'{name}({self._prefix}_{name})\'')


class FmtBase(object):
_name = ''
_desc = None
Expand All @@ -22,12 +35,13 @@ class FmtBase(object):

def __init__(self, *args, **kwargs):
super(FmtBase, self).__init__()
self.options = kwargs.get('options') or Namespace()
self.generator = kwargs.get('generator')
self.generator = kwargs.pop('generator', None)

options = kwargs.pop('options', Namespace())
self.options = _FmtOption(options, self._name)

self._update_orginal_rules(
kwargs.get('user_rules') or [],
kwargs.get('gfwlist_rules') or [])
self._update_orginal_rules(kwargs.pop('user_rules', []),
kwargs.pop('gfwlist_rules', []))

@classmethod
def prepare(cls, parser):
Expand All @@ -51,8 +65,8 @@ def post_generate(self):

@property
def tpl(self):
tpl = TemplateFile(self.options.template) if self.options.template else \
self._default_tpl
template = self.options._original.template
tpl = TemplateFile(template) if template else self._default_tpl
return str(tpl).strip('\n') + '\n'

def error(self, msg):
Expand Down
10 changes: 5 additions & 5 deletions src/genpac/format/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@ def __init__(self, *args, **kwargs):
@classmethod
def prepare(cls, parser):
super().prepare(parser)
cls.register_option('from', metavar='SRC', help='来源, 网址或文件路径')
cls.register_option('source', metavar='SRC', help='来源, 网址或文件路径')

def generate(self, replacements):
content = ''
try:
if path.isfile(self.options.copy_from):
with open_file(self.options.copy_from) as fp:
if path.isfile(self.options.source):
with open_file(self.options.source) as fp:
content = fp.read()
else:
content = self.fetch(self.options.copy_from)
content = self.fetch(self.options.source)
if content is None:
raise Exception
except Exception:
raise FatalError(f'copy: 无法读取或下载文件 {self.options.copy_from}')
raise FatalError(f'copy: 无法读取或下载文件 {self.options.source}')
return content
4 changes: 2 additions & 2 deletions src/genpac/format/deprecated.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def generate(self, replacements):

replacements.update({
'__ADAPTER__': adapter,
'__RULE_ADAPTER_ID__': self.options.wingy_rule_adapter_id,
'__RULE_ADAPTER_ID__': self.options.rule_adapter_id,
'__CRITERIA__': '\n'.join(domains)})
return self.replace(self.tpl, replacements)

Expand Down Expand Up @@ -90,7 +90,7 @@ def ss_uri(aid, uri):
opts.setdefault('protocol', 'verify_sha1')
return opts

adapter_opts = self.options.wingy_adapter_opts
adapter_opts = self.options.adapter_opts
if not adapter_opts:
return
opts = []
Expand Down
6 changes: 3 additions & 3 deletions src/genpac/format/dnsmasq.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ def prepare(cls, parser):
'如: 4#GFWLIST,6#GFWLIST6')

def generate(self, replacements):
dns = self.options.dnsmasq_dns
ipset = ','.join(self.options.dnsmasq_ipset)
nftset = ','.join(self.options.dnsmasq_nftset)
dns = self.options.dns
ipset = ','.join(self.options.ipset)
nftset = ','.join(self.options.nftset)

result = [
[f'server=/{s}/{dns}' for s in self.gfwed_domains]
Expand Down
6 changes: 3 additions & 3 deletions src/genpac/format/ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def prepare(cls, parser):
help=f'IP类型 可选: {families} 默认: 4')

def generate(self, replacements):
cc = self.options.ip_cc
cc = self.options.cc

ip4s, ip6s = self._generate_by_cc(cc)

Expand All @@ -70,11 +70,11 @@ def generate(self, replacements):

@property
def _ipv4(self):
return self.options.ip_family in [4, '4', 'all']
return self.options.family in [4, '4', 'all']

@property
def _ipv6(self):
return self.options.ip_family in [6, '6', 'all']
return self.options.family in [6, '6', 'all']

def _ip_network(self, data):
try:
Expand Down
2 changes: 1 addition & 1 deletion src/genpac/format/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ def generate(self, replacements):
gfwed = [f'||{s}' for s in self.gfwed_domains]
replacements.update({'__GFWED_DOMAINS__': '\n'.join(ignored + gfwed).strip()})
content = self.replace(self.tpl, replacements)
return b64encode(content) if not self.options.list_raw else content
return b64encode(content) if not self.options.raw else content
16 changes: 8 additions & 8 deletions src/genpac/format/pac.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ class FmtPAC(FmtBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

if self.options.pac_precise:
if self.options.precise:
self._default_tpl = _TPL_PAC_PRECISE
if self.options.pac_compress:
if self.options.compress:
self._default_tpl = _TPL_PAC_MIN
if self.options.pac_precise:
if self.options.precise:
self._default_tpl = _TPL_PAC_PRECISE_MIN

@classmethod
Expand All @@ -36,16 +36,16 @@ def prepare(cls, parser):
action='store_true', help='压缩输出')

def pre_generate(self):
if not self.options.pac_proxy:
if not self.options.proxy:
self.error('代理信息不存在,检查参数--pac-proxy或配置pac-proxy')
return False
return super().pre_generate()

def generate(self, replacements):
rules = json.dumps(
self.precise_rules if self.options.pac_precise else self.rules,
indent=None if self.options.pac_compress else 4,
separators=(',', ':') if self.options.pac_compress else None)
replacements.update({'__PROXY__': self.options.pac_proxy,
self.precise_rules if self.options.precise else self.rules,
indent=None if self.options.compress else 4,
separators=(',', ':') if self.options.compress else None)
replacements.update({'__PROXY__': self.options.proxy,
'__RULES__': rules})
return self.replace(self.tpl, replacements)
6 changes: 3 additions & 3 deletions src/genpac/format/shadowsocks_acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class FmtSSACL(FmtBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

if self.options.ssacl_geocn:
if self.options.geocn:
self.options.gfwlist_disabled = True

@classmethod
Expand All @@ -40,10 +40,10 @@ def prepare(cls, parser):

@property
def tpl(self):
return _TPL_GEOCN if self.options.ssacl_geocn else _TPL_DEF
return _TPL_GEOCN if self.options.geocn else _TPL_DEF

def generate(self, replacements):
return self.gen_by_geoip(replacements) if self.options.ssacl_geocn else \
return self.gen_by_geoip(replacements) if self.options.geocn else \
self.gen_by_gfwlist(replacements)

def gen_by_gfwlist(self, replacements):
Expand Down
6 changes: 3 additions & 3 deletions src/genpac/format/surge.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,16 @@ def prepare(cls, parser):
def generate(self, replacements):
rules = []

if self.options.surge_direct:
if self.options.direct:
rules.append(_DEF_DIRECT.strip())
for d in self.ignored_domains:
rules.append(f'DOMAIN-SUFFIX,{d},DIRECT')

for d in self.gfwed_domains:
rules.append(f'DOMAIN-SUFFIX,{d},{self.options.surge_policy}')
rules.append(f'DOMAIN-SUFFIX,{d},{self.options.policy}')

replacements.update({'__RULES__': '\n'.join(rules)})
tpl = _TPL_SET if self.options.surge_set else _TPL
tpl = _TPL_SET if self.options.set else _TPL
tpl = tpl.lstrip()

return self.replace(tpl, replacements)
12 changes: 6 additions & 6 deletions src/genpac/format/v2ray.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,19 @@ def prepare(cls, parser):
help=f'输出格式,默认: {_DEF_FORMAT}')

def pre_generate(self):
if self.options.v2ray_format not in V2RAY_DUMPER.keys():
if self.options.format not in V2RAY_DUMPER.keys():
self.error(f'输出的格式错误,只能是: {list(V2RAY_DUMPER.keys())}')
return False
return super().pre_generate()

def generate(self, replacements):
rules = []
if self.options.v2ray_proxy_tag:
rules.append(dict(outboundTag=self.options.v2ray_proxy_tag,
if self.options.proxy_tag:
rules.append(dict(outboundTag=self.options.proxy_tag,
type='field',
domains=[f'domain:{d}' for d in self.gfwed_domains if d]))
if self.options.v2ray_direct_tag:
rules.append(dict(outboundTag=self.options.v2ray_direct_tag,
if self.options.direct_tag:
rules.append(dict(outboundTag=self.options.direct_tag,
type='field',
port='0-65535'))
data = {
Expand All @@ -58,4 +58,4 @@ def generate(self, replacements):
'rules': rules
}
}
return V2RAY_DUMPER[self.options.v2ray_format](data)
return V2RAY_DUMPER[self.options.format](data)

0 comments on commit fb043c3

Please sign in to comment.