Skip to content

Commit

Permalink
Switch to ruff formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
luqasz committed Nov 14, 2024
1 parent 8640fce commit 07f5b5a
Show file tree
Hide file tree
Showing 22 changed files with 304 additions and 337 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ jobs:

- name: Format
run: >
poetry run yapf -dr
poetry run ruff format --diff
librouteros
tests
Expand Down
2 changes: 1 addition & 1 deletion librouteros/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from librouteros.protocol import ApiProtocol
from librouteros.login import (
plain,
token, # noqa: F401 BACK_COMP
token, # noqa: F401 BACK_COMP
)
from librouteros.api import Api

Expand Down
41 changes: 22 additions & 19 deletions librouteros/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@


class Api:

def __init__(self, protocol: ApiProtocol):
self.protocol = protocol

Expand Down Expand Up @@ -63,11 +62,11 @@ def readResponse(self) -> Response:
traps = []
reply_word = None
response = []
while reply_word != '!done':
while reply_word != "!done":
reply_word, words = self.readSentence()
if reply_word == '!trap':
if reply_word == "!trap":
traps.append(TrapError(**words))
elif reply_word in ('!re', '!done') and words:
elif reply_word in ("!re", "!done") and words:
response.append(words)

if len(traps) > 1:
Expand All @@ -81,7 +80,7 @@ def close(self) -> None:

def path(self, *path: str):
return Path(
path='',
path="",
api=self,
).join(*path)

Expand All @@ -94,7 +93,7 @@ def __init__(self, path: str, api: Api):
self.api = api

def select(self, key: query.Key, *other: query.Key) -> query.Query:
keys = (key, ) + other
keys = (key,) + other
return query.Query(path=self, keys=keys, api=self.api)

def __str__(self) -> str:
Expand All @@ -104,7 +103,7 @@ def __repr__(self) -> str:
return f"<{self.__class__.__name__} {self}>"

def __iter__(self) -> ResponseIter:
yield from self('print')
yield from self("print")

def __call__(self, cmd: str, **kwargs: typing.Any) -> ResponseIter:
yield from self.api(
Expand All @@ -116,25 +115,29 @@ def join(self, *path: str):
"""Join current path with one or more path strings."""
return Path(
api=self.api,
path=pjoin('/', self.path, *path).rstrip('/'),
path=pjoin("/", self.path, *path).rstrip("/"),
)

def remove(self, *ids: str) -> None:
joined = ','.join(ids)
tuple(self(
'remove',
**{'.id': joined},
))
joined = ",".join(ids)
tuple(
self(
"remove",
**{".id": joined},
)
)

def add(self, **kwargs: typing.Any) -> str:
ret = self(
'add',
"add",
**kwargs,
)
return tuple(ret)[0]['ret']
return tuple(ret)[0]["ret"]

def update(self, **kwargs: typing.Any) -> None:
tuple(self(
'set',
**kwargs,
))
tuple(
self(
"set",
**kwargs,
)
)
3 changes: 1 addition & 2 deletions librouteros/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@


class SocketTransport:

def __init__(self, sock: socket):
self.sock = sock

Expand All @@ -24,7 +23,7 @@ def read(self, length: int) -> bytes:
while len(data) != length:
data += self.sock.recv((length - len(data)))
if not data:
raise ConnectionClosed('Connection unexpectedly closed.')
raise ConnectionClosed("Connection unexpectedly closed.")
return data

def close(self) -> None:
Expand Down
6 changes: 3 additions & 3 deletions librouteros/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ def __init__(self, message: str, category: typing.Union[None, int] = None):
super().__init__()

def __str__(self) -> str:
return str(self.message.replace('\r\n', ','))
return str(self.message.replace("\r\n", ","))

def __repr__(self) -> str:
return f'{self.__class__.__name__}({self})'
return f"{self.__class__.__name__}({self})"


class MultiTrapError(ProtocolError):
Expand All @@ -50,4 +50,4 @@ def __init__(self, *traps: TrapError):
super().__init__()

def __str__(self) -> str:
return ', '.join(str(trap) for trap in self.traps)
return ", ".join(str(trap) for trap in self.traps)
20 changes: 10 additions & 10 deletions librouteros/login.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
# -*- coding: UTF-8 -*-

import typing
from binascii import unhexlify, hexlify #pylint: disable=no-name-in-module
from binascii import unhexlify, hexlify # pylint: disable=no-name-in-module
from hashlib import md5


def encode_password(token: str, password: str) -> str:
#pylint: disable=redefined-outer-name
token_bytes = token.encode('ascii', 'strict')
# pylint: disable=redefined-outer-name
token_bytes = token.encode("ascii", "strict")
token_bytes = unhexlify(token)
password_bytes = password.encode('ascii', 'strict')
password_bytes = password.encode("ascii", "strict")
hasher = md5()
hasher.update(b'\x00' + password_bytes + token_bytes)
hasher.update(b"\x00" + password_bytes + token_bytes)
password_bytes = hexlify(hasher.digest())
return '00' + password_bytes.decode('ascii', 'strict')
return "00" + password_bytes.decode("ascii", "strict")


def token(api: typing.Any, username: str, password: str) -> None:
"""Login using pre routeros 6.43 authorization method."""
sentence = api('/login')
tok = tuple(sentence)[0]['ret']
sentence = api("/login")
tok = tuple(sentence)[0]["ret"]
encoded = encode_password(tok, password)
tuple(api('/login', **{'name': username, 'response': encoded}))
tuple(api("/login", **{"name": username, "response": encoded}))


def plain(api: typing.Any, username: str, password: str) -> None:
"""Login using post routeros 6.43 authorization method."""
tuple(api('/login', **{'name': username, 'password': password}))
tuple(api("/login", **{"name": username, "password": password}))
11 changes: 4 additions & 7 deletions librouteros/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ def parse_word(word: str) -> typing.Tuple[str, typing.Any]:
mapping = {"yes": True, "true": True, "no": False, "false": False}
_, key, value = word.split("=", 2)
try:
value = int(value) # type: ignore
value = int(value) # type: ignore
except ValueError:
value = mapping.get(value, value) # type: ignore
value = mapping.get(value, value) # type: ignore
return (key, value)


def cast_to_api(value: typing.Any) -> str:
"""Cast python equivalent to API."""
mapping = {True: "yes", False: "no"}
# this is necesary because 1 == True, 0 == False
if type(value) == int: # noqa: E721
if type(value) == int: # noqa: E721
return str(value)
return mapping.get(value, str(value))

Expand All @@ -50,7 +50,6 @@ def compose_word(key: str, value: typing.Any) -> str:


class Encoder:

def encodeSentence(self, *words: str) -> bytes:
"""
Encode given sentence in API format.
Expand All @@ -71,7 +70,7 @@ def encodeWord(self, word: str) -> bytes:
:returns: Encoded word.
"""
# pylint: disable=no-member
encoded_word = word.encode(encoding=self.encoding, errors="strict") # type: ignore
encoded_word = word.encode(encoding=self.encoding, errors="strict") # type: ignore
return Encoder.encodeLength(len(encoded_word)) + encoded_word

@staticmethod
Expand Down Expand Up @@ -101,7 +100,6 @@ def encodeLength(length: int) -> bytes:


class Decoder:

@staticmethod
def determineLength(length: bytes) -> int:
"""
Expand Down Expand Up @@ -156,7 +154,6 @@ def decodeLength(length: bytes) -> int:


class ApiProtocol(Encoder, Decoder):

def __init__(self, transport: SocketTransport, encoding: str):
self.transport = transport
self.encoding = encoding
Expand Down
30 changes: 14 additions & 16 deletions librouteros/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,21 @@


class Key:

def __init__(self, name: str):
self.name = name

def __eq__(self, other):
yield f'?={self}={cast_to_api(other)}'
yield f"?={self}={cast_to_api(other)}"

def __ne__(self, other):
yield from self == other
yield '?#!'
yield "?#!"

def __lt__(self, other):
yield f'?<{self}={cast_to_api(other)}'
yield f"?<{self}={cast_to_api(other)}"

def __gt__(self, other):
yield f'?>{self}={cast_to_api(other)}'
yield f"?>{self}={cast_to_api(other)}"

def __str__(self) -> str:
return str(self.name)
Expand All @@ -35,11 +34,10 @@ def __str__(self) -> str:
def In(self, one, *elems):
yield from self == one
yield from chain.from_iterable(self == str(elem) for elem in elems)
yield from ('?#|', ) * len(elems)
yield from ("?#|",) * len(elems)


class Query:

def __init__(self, path, keys: typing.Sequence[Key], api):
self.path = path
self.keys = keys
Expand All @@ -51,25 +49,25 @@ def where(self, *args: str):
return self

def __iter__(self) -> ResponseIter:
keys = ','.join(str(key) for key in self.keys)
keys = f'=.proplist={keys}'
cmd = str(self.path.join('print'))
keys = ",".join(str(key) for key in self.keys)
keys = f"=.proplist={keys}"
cmd = str(self.path.join("print"))
return iter(self.api.rawCmd(cmd, keys, *self.query))


def And(left: QueryGen, right: QueryGen, *rest: QueryGen) -> QueryGen:
#pylint: disable=invalid-name
# pylint: disable=invalid-name
yield from left
yield from right
yield from chain.from_iterable(rest)
yield '?#&'
yield from ('?#&', ) * len(rest)
yield "?#&"
yield from ("?#&",) * len(rest)


def Or(left: QueryGen, right: QueryGen, *rest: QueryGen) -> QueryGen:
#pylint: disable=invalid-name
# pylint: disable=invalid-name
yield from left
yield from right
yield from chain.from_iterable(rest)
yield '?#|'
yield from ('?#|', ) * len(rest)
yield "?#|"
yield from ("?#|",) * len(rest)
49 changes: 9 additions & 40 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 07f5b5a

Please sign in to comment.