MCPcopy Create free account
hub / github.com/Cats-Team/AdRules / parse_rule

Function parse_rule

script/compressor.py:202–240  ·  view source on GitHub ↗

Convert raw text to AdblockRule objects.

(rule_text: str)

Source from the content-addressed store, hash-verified

200# --- Compression Logic (Optimized) ---
201
202def parse_rule(rule_text: str) -> List[AdblockRule]:
203 """Convert raw text to AdblockRule objects."""
204 rule_text = rule_text.strip()
205 res = []
206
207 # 1. Domain Lists (DOMAIN, example.com)
208 m_domain = RE_DOMAIN_SUFFIX_LIST.match(rule_text)
209 if m_domain:
210 host = m_domain.group(1)
211 if not RE_IP_LIKE.match(host):
212 res.append(AdblockRule(f"||{host}^", True, host, rule_text))
213 return res
214
215 # 2. /etc/hosts
216 if RE_ETC_HOSTS.match(rule_text):
217 parts = rule_text.split()
218 hosts = [p for p in parts if p and not p.startswith(('#', '!'))][1:]
219 for h in hosts:
220 if not RE_IP_LIKE.match(h):
221 res.append(AdblockRule(f"||{h}^", True, h, rule_text))
222 return res
223
224 # 3. Pure Domain (example.com) - strict check
225 if RE_VALID_DOMAIN_CHARS.match(rule_text) and '.' in rule_text and not rule_text.startswith('/') and not rule_text.startswith('||'):
226 if not RE_IP_LIKE.match(rule_text):
227 res.append(AdblockRule(f"||{rule_text}^", True, rule_text, rule_text))
228 return res
229
230 # 4. Standard Adblock matches ||...^
231 if rule_text.startswith("||") and rule_text.endswith("^"):
232 inner = rule_text[2:-1]
233 # Only allow plain domains to be "Compressible", wildcards fall to fallback
234 if not RE_IP_LIKE.match(inner) and '*' not in inner:
235 res.append(AdblockRule(rule_text, True, inner, rule_text))
236 return res
237
238 # Fallback: Uncompressible (includes Wildcards, RegEx, or Invalid Formats)
239 res.append(AdblockRule(rule_text, False, None, rule_text))
240 return res
241
242def compress_rules(rules: List[str], include_wildcards: bool) -> Tuple[List[str], List[str]]:
243 """Compress validated rules."""

Callers 1

compress_rulesFunction · 0.85

Calls 1

AdblockRuleClass · 0.85

Tested by

no test coverage detected