<s> import time <EOL> import re <EOL> from os . path import exists , getmtime <EOL> from twisted . internet . task import LoopingCall <EOL> from carbon import log <EOL> class RewriteRuleManager : <EOL> def __init__ ( self ) : <EOL> self . preRules = [ ] <EOL> self . postRules = [ ] <EOL> self . read_task = LoopingCall ( self . read_rules ) <EOL> self . rules_last_read = <NUM_LIT:0.0> <EOL> def clear ( self ) : <EOL> self . preRules = [ ] <EOL> self . postRules = [ ] <EOL> def read_from ( self , rules_file ) : <EOL> self . rules_file = rules_file <EOL> self . read_rules ( ) <EOL> self . read_task . start ( <NUM_LIT:10> , now = False ) <EOL> def read_rules ( self ) : <EOL> if not exists ( self . rules_file ) : <EOL> self . clear ( ) <EOL> return <EOL> try : <EOL> mtime = getmtime ( self . rules_file ) <EOL> except : <EOL> log . err ( "<STR_LIT>" % self . rules_file ) <EOL> return <EOL> if mtime <= self . rules_last_read : <EOL> return <EOL> pre = [ ] <EOL> post = [ ] <EOL> section = None <EOL> for line in open ( self . rules_file ) : <EOL> line = line . strip ( ) <EOL> if line . startswith ( '<STR_LIT:#>' ) or not line : <EOL> continue <EOL> if line . startswith ( '<STR_LIT:[>' ) and line . endswith ( '<STR_LIT:]>' ) : <EOL> section = line [ <NUM_LIT:1> : - <NUM_LIT:1> ] . lower ( ) <EOL> else : <EOL> pattern , replacement = line . split ( '<STR_LIT:=>' , <NUM_LIT:1> ) <EOL> pattern , replacement = pattern . strip ( ) , replacement . strip ( ) <EOL> rule = RewriteRule ( pattern , replacement ) <EOL> if section == '<STR_LIT>' : <EOL> pre . append ( rule ) <EOL> elif section == '<STR_LIT>' : <EOL> post . append ( rule ) <EOL> self . preRules = pre <EOL> self . postRules = post <EOL> self . rules_last_read = mtime <EOL> class RewriteRule : <EOL> def __init__ ( self , pattern , replacement ) : <EOL> self . pattern = pattern <EOL> self . replacement = replacement <EOL> self . regex = re . compile ( pattern ) <EOL> def apply ( self , metric ) : <EOL> return self . regex . sub ( self . replacement , metric ) <EOL> RewriteRuleManager = RewriteRuleManager ( ) </s>
