Skip to content

Commit b59fd9e

Browse files
authored
added S, RET, RUF ruff checks (#129)
Making life easier =) Signed-off-by: Alexander Piskun <[email protected]>
1 parent d643a59 commit b59fd9e

File tree

11 files changed

+42
-40
lines changed

11 files changed

+42
-40
lines changed

benchmarks/aa_overhead_common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,6 @@ def measure_overhead(measure, title: str):
6969
def os_id():
7070
if sys.platform.lower() == "darwin":
7171
return "macOS"
72-
elif sys.platform.lower() == "win32":
72+
if sys.platform.lower() == "win32":
7373
return "Windows"
7474
return "Linux"

examples/as_app/talk_bot/src/main.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def convert_currency(amount, from_currency, to_currency):
2020
base_url = "https://api.exchangerate-api.com/v4/latest/"
2121

2222
# Fetch latest exchange rates
23-
response = requests.get(base_url + from_currency)
23+
response = requests.get(base_url + from_currency, timeout=60)
2424
data = response.json()
2525

2626
if "rates" in data:
@@ -30,12 +30,9 @@ def convert_currency(amount, from_currency, to_currency):
3030

3131
if from_currency in rates and to_currency in rates:
3232
conversion_rate = rates[to_currency] / rates[from_currency]
33-
converted_amount = amount * conversion_rate
34-
return converted_amount
35-
else:
36-
raise ValueError("Invalid currency!")
37-
else:
38-
raise ValueError("Unable to fetch exchange rates!")
33+
return amount * conversion_rate
34+
raise ValueError("Invalid currency!")
35+
raise ValueError("Unable to fetch exchange rates!")
3936

4037

4138
def currency_talk_bot_process_request(message: talk_bot.TalkBotMessage):
@@ -55,7 +52,7 @@ def currency_talk_bot_process_request(message: talk_bot.TalkBotMessage):
5552
CURRENCY_BOT.send_message(f"{r.group(2)} {r.group(3)} is equal to {converted_amount} {r.group(4)}", message)
5653
except Exception as e:
5754
# In production, it is better to write to log, than in the chat ;)
58-
CURRENCY_BOT.send_message(f"Exception: {str(e)}", message)
55+
CURRENCY_BOT.send_message(f"Exception: {e}", message)
5956

6057

6158
@APP.post("/currency_talk_bot")

examples/as_app/talk_bot_multi/src/main.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,21 @@
2020
@APP.post("/bot1")
2121
async def bot1(message: Annotated[talk_bot.TalkBotMessage, Depends(talk_bot_app)]):
2222
if message.object_name != "message":
23-
return
23+
return None
2424
r = re.search(r"@bot\sone.*", message.object_content["message"], re.IGNORECASE)
2525
if r is None and re.search(r"@bots!", message.object_content["message"], re.IGNORECASE) is None:
26-
return
26+
return None
2727
BOT1.send_message("I am here, my Lord!", message)
2828
return requests.Response()
2929

3030

3131
@APP.post("/bot2")
3232
async def bot2(message: Annotated[talk_bot.TalkBotMessage, Depends(talk_bot_app)]):
3333
if message.object_name != "message":
34-
return
34+
return None
3535
r = re.search(r"@bot\stwo.*", message.object_content["message"], re.IGNORECASE)
3636
if r is None and re.search(r"@bots!", message.object_content["message"], re.IGNORECASE) is None:
37-
return
37+
return None
3838
BOT2.send_message("I am here, my Lord!", message)
3939
return requests.Response()
4040

nc_py_api/_misc.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
33
For internal use, prototypes can change between versions.
44
"""
5+
import secrets
56
from base64 import b64decode
67
from datetime import datetime, timezone
7-
from random import choice
8-
from string import ascii_lowercase, ascii_uppercase, digits
8+
from string import ascii_letters, digits
99
from typing import Callable, Union
1010

1111
from ._exceptions import NextcloudMissingCapabilities
@@ -65,8 +65,8 @@ def check_capabilities(capabilities: Union[str, list[str]], srv_capabilities: di
6565

6666
def random_string(size: int) -> str:
6767
"""Generates a random ASCII string of the given size."""
68-
letters = ascii_lowercase + ascii_uppercase + digits
69-
return "".join(choice(letters) for _ in range(size))
68+
char_string = ascii_letters + digits
69+
return "".join(secrets.choice(char_string) for _ in range(size))
7070

7171

7272
def nc_iso_time_to_datetime(iso8601_time: str) -> datetime:

nc_py_api/files/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,11 +129,11 @@ def __str__(self):
129129
if self.info.is_version:
130130
return (
131131
f"File version: `{self.name}` for FileID={self.file_id}"
132-
f" last modified at {str(self.info.last_modified)} with {self.info.content_length} bytes size."
132+
f" last modified at {self.info.last_modified} with {self.info.content_length} bytes size."
133133
)
134134
return (
135135
f"{'Dir' if self.is_dir else 'File'}: `{self.name}` with id={self.file_id}"
136-
f" last modified at {str(self.info.last_modified)} and {self.info.permissions} permissions."
136+
f" last modified at {self.info.last_modified} and {self.info.permissions} permissions."
137137
)
138138

139139
def __eq__(self, other):

nc_py_api/files/files.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
from io import BytesIO
77
from json import dumps, loads
88
from pathlib import Path
9-
from random import choice
10-
from string import ascii_lowercase, digits
119
from typing import Optional, Union
1210
from urllib.parse import unquote
1311
from xml.etree import ElementTree
@@ -16,7 +14,7 @@
1614
from httpx import Response
1715

1816
from .._exceptions import NextcloudException, NextcloudExceptionNotFound, check_error
19-
from .._misc import clear_from_params_empty, require_capabilities
17+
from .._misc import clear_from_params_empty, random_string, require_capabilities
2018
from .._session import NcSessionBasic
2119
from . import FsNode, SystemTag
2220
from .sharing import _FilesSharingAPI
@@ -694,8 +692,7 @@ def __download2stream(self, path: str, fp, **kwargs) -> None:
694692
fp.write(data_chunk)
695693

696694
def __upload_stream(self, path: str, fp, **kwargs) -> FsNode:
697-
_rnd_folder = "".join(choice(digits + ascii_lowercase) for _ in range(64))
698-
_dav_path = self._dav_get_obj_path(self._session.user, _rnd_folder, root_path="/uploads")
695+
_dav_path = self._dav_get_obj_path(self._session.user, random_string(64), root_path="/uploads")
699696
response = self._session.dav("MKCOL", _dav_path)
700697
check_error(response.status_code)
701698
try:

nc_py_api/talk_bot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def _sign_send_request(self, method: str, url_suffix: str, data: dict, data_to_s
202202

203203
def get_bot_secret(callback_url: str) -> typing.Union[bytes, None]:
204204
"""Returns the bot's secret from an environment variable or from the application's configuration on the server."""
205-
sha_1 = hashlib.sha1()
205+
sha_1 = hashlib.sha1(usedforsecurity=False)
206206
string_to_hash = os.environ["APP_ID"] + "_" + callback_url
207207
sha_1.update(string_to_hash.encode("UTF-8"))
208208
secret_key = sha_1.hexdigest()

nc_py_api/weather_status.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ def set_location(
6767
) -> bool:
6868
"""Sets the user's location on the Nextcloud server.
6969
70-
:param latitude: northsouth position of a point on the surface of the Earth.
71-
:param longitude: eastwest position of a point on the surface of the Earth.
70+
:param latitude: north-south position of a point on the surface of the Earth.
71+
:param longitude: east-west position of a point on the surface of the Earth.
7272
:param address: city, index(*optional*) and country, e.g. "Paris, 75007, France"
7373
"""
7474
require_capabilities("weather_status.enabled", self._session.capabilities)

pyproject.toml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,8 +104,8 @@ preview = true
104104
[tool.ruff]
105105
line-length = 120
106106
target-version = "py39"
107-
select = ["A", "B", "C", "D", "E", "F", "G", "I", "UP", "SIM", "Q", "W"]
108-
extend-ignore = ["D107", "D105", "D203", "D213", "D401", "I001"]
107+
select = ["A", "B", "C", "D", "E", "F", "G", "I", "S", "SIM", "Q", "RET", "RUF", "UP" , "W"]
108+
extend-ignore = ["D107", "D105", "D203", "D213", "D401", "I001", "RUF100"]
109109

110110
[tool.ruff.per-file-ignores]
111111
"nc_py_api/__init__.py" = ["F401"]
@@ -114,8 +114,8 @@ extend-ignore = ["D107", "D105", "D203", "D213", "D401", "I001"]
114114
[tool.ruff.extend-per-file-ignores]
115115
"benchmarks/**/*.py" = ["D"]
116116
"docs/**/*.py" = ["D"]
117-
"examples/**/*.py" = ["D"]
118-
"tests/**/*.py" = ["D", "E402", "UP"]
117+
"examples/**/*.py" = ["D", "S106"]
118+
"tests/**/*.py" = ["D", "E402", "S", "UP"]
119119

120120
[tool.ruff.mccabe]
121121
max-complexity = 16

tests/actual_tests/files_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def test_list_user_root_self_exclude(nc):
4848
user_root = nc.files.listdir()
4949
user_root_with_self = nc.files.listdir(exclude_self=False)
5050
assert len(user_root_with_self) == 1 + len(user_root)
51-
self_res = [i for i in user_root_with_self if not i.user_path][0]
51+
self_res = next(i for i in user_root_with_self if not i.user_path)
5252
for i in user_root:
5353
assert self_res != i
5454
assert self_res.has_extra

0 commit comments

Comments
 (0)