Initial Commit

parents
import sys
import yaml
import re
# Constants:
class RedirectorParser:
def __init__(self, logger=None):
self.url_regexp = re.compile(r'\/[\w-:]+)+\/?(\.\w+)?')
self.logger = logger
def _parse_line(self, line, prefix, i):
if not line.startswith("#"):
line = line.split()
url_type = []
if len(line) < 2:
raise self.ParseLineError("Error on %s:{line};\nNot enough arguments to parse!".format(line=i))
elif len(line) > 2:
url_type.append("options")
options = [option[1:-1] for option in line[2:]]
else:
url_type.append("no-options")
# not url - regexp
if not self.url_regexp.fullmatch(line[0]):
try:
re.compile(line[0])
re.compile(line[1])
url_type.append("regexp")
except re.error:
raise self.RegexpTestError("Can\'t compile regular expressions {expression1} {expression2} in %s{line_num}".format(
expression1=line[0], expression2=line[1], line_num=i))
# if new URI relative to the root
elif line[0].startswith("//"):
line[0] = line[0][1:] # cutting out extra '/' at the beginning
url_type.append("root")
# default url
else:
line[0] = prefix + line[0]
line[1] = prefix + line[1]
url_type.append('plain')
return url_type, line[0], line[1], options
else:
return ["comment"], None, None
@staticmethod
def _parse_yaml(file_dir):
return_list = []
with open(file_dir, 'r') as stream:
data = yaml.safe_load(stream)
for project in data.get("projects"):
map_path = project.get("map")
project_prefix = project.get("prefix")
return_list.append((map_path, project_prefix))
return return_list
def log(self, message, level="critical"):
if self.logger:
if level == "critical":
self.logger.critical(message)
elif level == "debug":
self.logger.debug(message)
elif level == "info":
self.logger.info(message)
else:
print(level.upper() + ":\n" + message)
def _parse_map(self, map_file, yaml_file):
try:
for map_path, prefix in self._parse_yaml(yaml_file):
if map_path == map_file:
with open(map_file, "r") as file:
for i, line in enumerate(file):
try:
type_, request_url, redirect_url, *options = self._parse_line(line, prefix, i)
except self.RegexpTestError as e:
self.log(e%map_file)
except self.ParseLineError as e:
self.log(e%map_file)
if not request_url or not redirect_url or type_[0] == "comment":
continue
else:
pass
except yaml.YAMLError as e:
self.log("Error occured while reading %s" % yaml_file + str(e))
class ParseLineError(Exception):
"""Raised when line contains not enough arguments
Attributes:
message -- expanation where in .yaml config file aprser didn't find enough arguments
"""
def __init__(self, message):
self.message = message
class RegexpTestError(Exception):
"""Raised when parser fails to compile url containing regular expression
Attributes:
message -- explanation what regexp failed to compile and where
"""
def __init__(self, message):
self.message = message
from setuptools import setup, find_packages
from core import const
setup(
name=const.NAME,
version="0.1",
packages=find_packages(),
entry_points="""
[redirector]
redirector = core.parser:main
"""
)
\ No newline at end of file
projects:
- map: ./test.map
prefix: /test
- map: ./test2.map
prefix: /test2
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment