Commit 578c37f3 authored by Nick Yefremov's avatar Nick Yefremov

Debugged and introduced redirects division

parent a5b2b78f
import sys
import yaml
from pprint import pprint as pp
import re
# Constants:
class RedirectorParser:
def __init__(self, logger=None):
self.url_regexp = re.compile(r'\/[\w-:]+)+\/?(\.\w+)?')
self.url_regexp = re.compile(r'(\/[(\w)-:]+)+\/?(\.\w+)?')
self.url_absolute = re.compile(r"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\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:
url_type, options = [], []
if len(line) == 0:
return ["skip"], None, None
elif 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")
......@@ -27,12 +33,18 @@ class RedirectorParser:
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))
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
line[0] = line[0][1:] # cutting out extra '/' at the beginning
url_type.append("root")
elif line[1].startswith("//"):
line[1] = line[1][1:]
url_type.append("root")
elif self.url_absolute.fullmatch(line[1]):
url_type.append("absolute")
# default url
else:
line[0] = prefix + line[0]
......@@ -40,8 +52,8 @@ class RedirectorParser:
url_type.append('plain')
return url_type, line[0], line[1], options
else:
return ["comment"], None, None
return ["skip"], None, None
@staticmethod
def _parse_yaml(file_dir):
return_list = []
......@@ -65,22 +77,39 @@ class RedirectorParser:
print(level.upper() + ":\n" + message)
def _parse_map(self, map_file, yaml_file):
res = [[], [], [], [], [], []]
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):
request_url, redirect_url, options = None, None, []
try:
type_, request_url, redirect_url, *options = self._parse_line(line, prefix, i)
except self.RegexpTestError as e:
self.log(e%map_file)
self.log(e.message % map_file)
except self.ParseLineError as e:
self.log(e%map_file)
if not request_url or not redirect_url or type_[0] == "comment":
self.log(e.message % map_file)
if not request_url or not redirect_url or type_[0] == "skip":
continue
else:
pass
if type_[1] == "plain":
if type_[0] == "no-options":
res[0].append((request_url, redirect_url))
else:
res[1].append((request_url, redirect_url, *options))
elif type_[1] == "regexp":
if type_[0] == "no-options":
res[2].append((request_url, redirect_url))
else:
res[3].append((request_url, redirect_url, *options))
elif type_[1] == "absolute":
if type_[0] == "no-options":
res[4].append((request_url, redirect_url))
else:
res[5].append((request_url, redirect_url, *options))
return res
except yaml.YAMLError as e:
self.log("Error occured while reading %s" % yaml_file + str(e))
......@@ -90,18 +119,25 @@ class RedirectorParser:
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
def main():
parser = RedirectorParser()
pp(parser._parse_map("tests/test.map", "tests/test.yaml"))
if __name__ == "__main__":
main()
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