Skip to content

Commit

Permalink
Enable "RET" linting rule of Ruff and fix newly reported errors (#1034)
Browse files Browse the repository at this point in the history
  • Loading branch information
Borda authored Dec 16, 2023
1 parent 5d60a7a commit dcf42d9
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 49 deletions.
19 changes: 9 additions & 10 deletions loguru/_colorizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,9 @@ def feed(self, text, *, raw=False):
self._tokens.append((TokenType.CLOSING, "\033[0m"))
self._tokens.extend(self._color_tokens)
continue
elif tag in self._tags:
if tag in self._tags:
raise ValueError('Closing tag "%s" violates nesting rules' % markup)
else:
raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup)
raise ValueError('Closing tag "%s" has no corresponding opening tag' % markup)

if tag in {"lvl", "level"}:
token = (TokenType.LEVEL, None)
Expand Down Expand Up @@ -280,29 +279,29 @@ def _get_ansicode(self, tag):
# Substitute on a direct match.
if tag in style:
return style[tag]
elif tag in foreground:
if tag in foreground:
return foreground[tag]
elif tag in background:
if tag in background:
return background[tag]

# An alternative syntax for setting the color (e.g. <fg red>, <bg red>).
elif tag.startswith("fg ") or tag.startswith("bg "):
if tag.startswith("fg ") or tag.startswith("bg "):
st, color = tag[:2], tag[3:]
code = "38" if st == "fg" else "48"

if st == "fg" and color.lower() in foreground:
return foreground[color.lower()]
elif st == "bg" and color.upper() in background:
if st == "bg" and color.upper() in background:
return background[color.upper()]
elif color.isdigit() and int(color) <= 255:
if color.isdigit() and int(color) <= 255:
return "\033[%s;5;%sm" % (code, color)
elif re.match(r"#(?:[a-fA-F0-9]{3}){1,2}$", color):
if re.match(r"#(?:[a-fA-F0-9]{3}){1,2}$", color):
hex_color = color[1:]
if len(hex_color) == 3:
hex_color *= 2
rgb = tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
return "\033[%s;2;%s;%s;%sm" % ((code,) + rgb)
elif color.count(",") == 2:
if color.count(",") == 2:
colors = tuple(color.split(","))
if all(x.isdigit() and int(x) <= 255 for x in colors):
return "\033[%s;2;%s;%s;%sm" % ((code,) + colors)
Expand Down
4 changes: 2 additions & 2 deletions loguru/_ctime_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def set_ctime_windows(filepath, timestamp):

return get_ctime_windows, set_ctime_windows

elif hasattr(os.stat_result, "st_birthtime"):
if hasattr(os.stat_result, "st_birthtime"):

def get_ctime_macos(filepath):
return os.stat(filepath).st_birthtime
Expand All @@ -29,7 +29,7 @@ def set_ctime_macos(filepath, timestamp):

return get_ctime_macos, set_ctime_macos

elif hasattr(os, "getxattr") and hasattr(os, "setxattr"):
if hasattr(os, "getxattr") and hasattr(os, "setxattr"):

def get_ctime_linux(filepath):
try:
Expand Down
5 changes: 3 additions & 2 deletions loguru/_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,22 @@ def env(key, type_, default=None):

if type_ == str:
return val
elif type_ == bool:
if type_ == bool:
if val.lower() in ["1", "true", "yes", "y", "ok", "on"]:
return True
if val.lower() in ["0", "false", "no", "n", "nok", "off"]:
return False
raise ValueError(
"Invalid environment variable '%s' (expected a boolean): '%s'" % (key, val)
)
elif type_ == int:
if type_ == int:
try:
return int(val)
except ValueError:
raise ValueError(
"Invalid environment variable '%s' (expected an integer): '%s'" % (key, val)
) from None
raise ValueError("The requested type '%r' is not supported" % type_)


LOGURU_AUTOINIT = env("LOGURU_AUTOINIT", bool, True)
Expand Down
41 changes: 18 additions & 23 deletions loguru/_file_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ def _make_glob_patterns(path):
def _make_rotation_function(rotation):
if rotation is None:
return None
elif isinstance(rotation, str):
if isinstance(rotation, str):
size = string_parsers.parse_size(rotation)
if size is not None:
return FileSink._make_rotation_function(size)
Expand All @@ -330,45 +330,41 @@ def _make_rotation_function(rotation):
step_forward = partial(Rotation.forward_weekday, weekday=day)
return Rotation.RotationTime(step_forward, time)
raise ValueError("Cannot parse rotation from: '%s'" % rotation)
elif isinstance(rotation, (numbers.Real, decimal.Decimal)):
if isinstance(rotation, (numbers.Real, decimal.Decimal)):
return partial(Rotation.rotation_size, size_limit=rotation)
elif isinstance(rotation, datetime.time):
if isinstance(rotation, datetime.time):
return Rotation.RotationTime(Rotation.forward_day, rotation)
elif isinstance(rotation, datetime.timedelta):
if isinstance(rotation, datetime.timedelta):
step_forward = partial(Rotation.forward_interval, interval=rotation)
return Rotation.RotationTime(step_forward)
elif callable(rotation):
if callable(rotation):
return rotation
else:
raise TypeError(
"Cannot infer rotation for objects of type: '%s'" % type(rotation).__name__
)
raise TypeError("Cannot infer rotation for objects of type: '%s'" % type(rotation).__name__)

@staticmethod
def _make_retention_function(retention):
if retention is None:
return None
elif isinstance(retention, str):
if isinstance(retention, str):
interval = string_parsers.parse_duration(retention)
if interval is None:
raise ValueError("Cannot parse retention from: '%s'" % retention)
return FileSink._make_retention_function(interval)
elif isinstance(retention, int):
if isinstance(retention, int):
return partial(Retention.retention_count, number=retention)
elif isinstance(retention, datetime.timedelta):
if isinstance(retention, datetime.timedelta):
return partial(Retention.retention_age, seconds=retention.total_seconds())
elif callable(retention):
if callable(retention):
return retention
else:
raise TypeError(
"Cannot infer retention for objects of type: '%s'" % type(retention).__name__
)
raise TypeError(
"Cannot infer retention for objects of type: '%s'" % type(retention).__name__
)

@staticmethod
def _make_compression_function(compression):
if compression is None:
return None
elif isinstance(compression, str):
if isinstance(compression, str):
ext = compression.strip().lstrip(".")

if ext == "gz":
Expand Down Expand Up @@ -426,9 +422,8 @@ def _make_compression_function(compression):
raise ValueError("Invalid compression format: '%s'" % ext)

return partial(Compression.compression, ext="." + ext, compress_function=compress)
elif callable(compression):
if callable(compression):
return compression
else:
raise TypeError(
"Cannot infer compression for objects of type: '%s'" % type(compression).__name__
)
raise TypeError(
"Cannot infer compression for objects of type: '%s'" % type(compression).__name__
)
5 changes: 2 additions & 3 deletions loguru/_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -1225,7 +1225,7 @@ def __enter__(self):

def __exit__(self, type_, value, traceback_):
if type_ is None:
return
return None

if not issubclass(type_, exception):
return False
Expand Down Expand Up @@ -1582,8 +1582,7 @@ def level(self, name, no=None, color=None, icon=None):
"Level '%s' does not exist, you have to create it by specifying a level no"
% name
)
else:
old_color, old_icon = "", " "
old_color, old_icon = "", " "
elif no is not None:
raise TypeError("Level '%s' already exists, you can't update its severity no" % name)
else:
Expand Down
6 changes: 2 additions & 4 deletions loguru/_string_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ def parse_size(size):
u = "kmgtpezy".index(u.lower()) + 1 if u else 0
i = 1024 if i else 1000
b = {"b": 8, "B": 1}[b] if b else 1
size = s * i**u / b

return size
return s * i**u / b


def parse_duration(duration):
Expand Down Expand Up @@ -118,7 +116,7 @@ def parse_day(day):
day = day.strip().lower()
if day in days:
return days[day]
elif day.startswith("w") and day[1:].isdigit():
if day.startswith("w") and day[1:].isdigit():
day = int(day[1:])
if not 0 <= day < 7:
raise ValueError("Invalid weekday value while parsing day (expected [0-6]): '%d'" % day)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ testpaths = ["tests"]
exclude = ["tests/exceptions/source/*"]
line-length = 100
# Enforce pyflakes(F), pycodestyle(E, W), isort (I), bugbears (B), and pep8-naming (N) rules.
select = ["F", "E", "W", "I", "B", "N"]
select = ["F", "E", "W", "I", "B", "N", "RET"]

[tool.ruff.pycodestyle]
max-doc-length = 100
Expand Down
3 changes: 1 addition & 2 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ def parse(text, *, strip=False, strict=True):

if strip:
return parser.strip(tokens)
else:
return parser.colorize(tokens, "")
return parser.colorize(tokens, "")


def check_dir(dir, *, files=None, size=None):
Expand Down
3 changes: 1 addition & 2 deletions tests/test_add_option_catch.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,7 @@ def half_broken_sink(m):
nonlocal output
if m.startswith("NOK"):
raise ValueError("Broken!")
else:
output += m
output += m

logger.add(half_broken_sink, format="{message}", enqueue=enqueue, catch=True)
logger.info("A")
Expand Down
8 changes: 8 additions & 0 deletions tests/test_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,11 @@ def test_invalid_bool(value, monkeypatch):
context.setenv(key, value)
with pytest.raises(ValueError):
env(key, bool)


def test_invalid_type(monkeypatch):
with monkeypatch.context() as context:
key = "INVALID_TYPE"
context.setenv(key, 42.0)
with pytest.raises(ValueError):
env(key, float)

0 comments on commit dcf42d9

Please sign in to comment.