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

Debugged and introduced redirects division

parent a5b2b78f
import sys import sys
import yaml import yaml
from pprint import pprint as pp
import re import re
# Constants: # Constants:
class RedirectorParser: class RedirectorParser:
def __init__(self, logger=None): 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 self.logger = logger
def _parse_line(self, line, prefix, i): def _parse_line(self, line, prefix, i):
if not line.startswith("#"): if not line.startswith("#"):
line = line.split() line = line.split()
url_type = [] url_type, options = [], []
if len(line) < 2: 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)) raise self.ParseLineError("Error on %s:{line};\nNot enough arguments to parse!".format(line=i))
elif len(line) > 2: elif len(line) > 2:
url_type.append("options") url_type.append("options")
...@@ -27,12 +33,18 @@ class RedirectorParser: ...@@ -27,12 +33,18 @@ class RedirectorParser:
re.compile(line[1]) re.compile(line[1])
url_type.append("regexp") url_type.append("regexp")
except re.error: except re.error:
raise self.RegexpTestError("Can\'t compile regular expressions {expression1} {expression2} in %s{line_num}".format( raise self.RegexpTestError("Can\'t compile regular expressions {expression1} {expression2} in "
expression1=line[0], expression2=line[1], line_num=i)) "%s:{line_num}".format(expression1=line[0], expression2=line[1],
line_num=i))
# if new URI relative to the root # if new URI relative to the root
elif line[0].startswith("//"): 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") url_type.append("root")
elif self.url_absolute.fullmatch(line[1]):
url_type.append("absolute")
# default url # default url
else: else:
line[0] = prefix + line[0] line[0] = prefix + line[0]
...@@ -40,8 +52,8 @@ class RedirectorParser: ...@@ -40,8 +52,8 @@ class RedirectorParser:
url_type.append('plain') url_type.append('plain')
return url_type, line[0], line[1], options return url_type, line[0], line[1], options
else: else:
return ["comment"], None, None return ["skip"], None, None
@staticmethod @staticmethod
def _parse_yaml(file_dir): def _parse_yaml(file_dir):
return_list = [] return_list = []
...@@ -65,22 +77,39 @@ class RedirectorParser: ...@@ -65,22 +77,39 @@ class RedirectorParser:
print(level.upper() + ":\n" + message) print(level.upper() + ":\n" + message)
def _parse_map(self, map_file, yaml_file): def _parse_map(self, map_file, yaml_file):
res = [[], [], [], [], [], []]
try: try:
for map_path, prefix in self._parse_yaml(yaml_file): for map_path, prefix in self._parse_yaml(yaml_file):
if map_path == map_file: if map_path == map_file:
with open(map_file, "r") as file: with open(map_file, "r") as file:
for i, line in enumerate(file): for i, line in enumerate(file):
request_url, redirect_url, options = None, None, []
try: try:
type_, request_url, redirect_url, *options = self._parse_line(line, prefix, i) type_, request_url, redirect_url, *options = self._parse_line(line, prefix, i)
except self.RegexpTestError as e: except self.RegexpTestError as e:
self.log(e%map_file) self.log(e.message % map_file)
except self.ParseLineError as e: except self.ParseLineError as e:
self.log(e%map_file) self.log(e.message % map_file)
if not request_url or not redirect_url or type_[0] == "comment": if not request_url or not redirect_url or type_[0] == "skip":
continue continue
else: 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: except yaml.YAMLError as e:
self.log("Error occured while reading %s" % yaml_file + str(e)) self.log("Error occured while reading %s" % yaml_file + str(e))
...@@ -90,18 +119,25 @@ class RedirectorParser: ...@@ -90,18 +119,25 @@ class RedirectorParser:
Attributes: Attributes:
message -- expanation where in .yaml config file aprser didn't find enough arguments message -- expanation where in .yaml config file aprser didn't find enough arguments
""" """
def __init__(self, message): def __init__(self, message):
self.message = message self.message = message
class RegexpTestError(Exception): class RegexpTestError(Exception):
"""Raised when parser fails to compile url containing regular expression """Raised when parser fails to compile url containing regular expression
Attributes: Attributes:
message -- explanation what regexp failed to compile and where message -- explanation what regexp failed to compile and where
""" """
def __init__(self, message): def __init__(self, message):
self.message = 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