mirror of https://github.com/jesopo/irctokens
add code to serialise/format Line objects
This commit is contained in:
parent
c1c6bcaef6
commit
07836f98d4
|
@ -3,16 +3,51 @@ import typing
|
|||
TAG_ESCAPE = ["\\", " ", ";", "\r", "\n"]
|
||||
TAG_UNESCAPE = ["\\\\", "\s", "\:", r"\r", r"\n"]
|
||||
|
||||
class Line(object):
|
||||
tags: typing.Optional[typing.Dict[str, typing.Optional[str]]] = None
|
||||
source: typing.Optional[str] = None
|
||||
command: str = ""
|
||||
params: typing.List[str] = []
|
||||
|
||||
def _escape_tag(value: str):
|
||||
def _unescape_tag(value: str):
|
||||
for i, char in enumerate(TAG_UNESCAPE):
|
||||
value = value.replace(char, TAG_ESCAPE[i])
|
||||
return value
|
||||
def _escape_tag(value: str):
|
||||
for i, char in enumerate(TAG_ESCAPE):
|
||||
value = value.replace(char, TAG_UNESCAPE[i])
|
||||
return value
|
||||
|
||||
class Line(object):
|
||||
def __init__(self,
|
||||
tags:
|
||||
typing.Optional[typing.Dict[str, typing.Optional[str]]]=None,
|
||||
source: typing.Optional[str]=None,
|
||||
command: str="",
|
||||
params: typing.List[str]=[]):
|
||||
self.tags = tags
|
||||
self.source = source
|
||||
self.command = command
|
||||
self.params = params
|
||||
|
||||
def format(self) -> str:
|
||||
outs: typing.List[str] = []
|
||||
if self.tags:
|
||||
tags_str = []
|
||||
for key in sorted(self.tags.keys()):
|
||||
if self.tags[key]:
|
||||
tags_str.append(
|
||||
"%s=%s" % (key, _escape_tag(self.tags[key])))
|
||||
else:
|
||||
tags_str.append(key)
|
||||
outs.append("@%s" % ";".join(tags_str))
|
||||
|
||||
if self.source:
|
||||
outs.append(":%s" % self.source)
|
||||
outs.append(self.command.upper())
|
||||
|
||||
params = self.params.copy()
|
||||
if self.params:
|
||||
last = params.pop(-1)
|
||||
outs.extend(params)
|
||||
if " " in last:
|
||||
last = ":%s" % last
|
||||
outs.append(last)
|
||||
return " ".join(outs)
|
||||
|
||||
def tokenise(line: str) -> Line:
|
||||
line_obj = Line()
|
||||
|
@ -23,7 +58,7 @@ def tokenise(line: str) -> Line:
|
|||
for part in message_tags[1:].split(";"):
|
||||
key, _, value = part.partition("=")
|
||||
if value:
|
||||
tags[key] = _escape_tag(value)
|
||||
tags[key] = _unescape_tag(value)
|
||||
else:
|
||||
tags[key] = None
|
||||
line_obj.tags = tags
|
||||
|
@ -41,3 +76,11 @@ def tokenise(line: str) -> Line:
|
|||
line_obj.params = params
|
||||
|
||||
return line_obj
|
||||
|
||||
def format(
|
||||
command: str,
|
||||
params: typing.List[str]=[],
|
||||
source: typing.Optional[str]=None,
|
||||
tags: typing.Optional[typing.Dict[str, typing.Optional[str]]]=None
|
||||
) -> str:
|
||||
return Line(tags, source, command, params).format()
|
||||
|
|
Loading…
Reference in New Issue