Skip to content

Commit

Permalink
refactor: Simplify return logic
Browse files Browse the repository at this point in the history
* Don't return `None` if it's the only thing returned
  https://docs.astral.sh/ruff/rules/unnecessary-return-none/
* Don't implicitly return `None`
  https://docs.astral.sh/ruff/rules/implicit-return/
* Don't assign to a variable immediately before returning it
  https://docs.astral.sh/ruff/rules/unnecessary-assign/
* Remove unnecessary `else` clauses
  https://docs.astral.sh/ruff/rules/superfluous-else-return/
  • Loading branch information
jmgate committed Apr 24, 2024
1 parent ae2e630 commit 298d05c
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 46 deletions.
30 changes: 14 additions & 16 deletions shell_logger/html_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,17 @@ def nested_simplenamespace_to_dict(
if "_asdict" in dir(namespace):
# noinspection PyProtectedMember
return nested_simplenamespace_to_dict(namespace._asdict())
elif isinstance(namespace, (str, bytes, tuple)):
if isinstance(namespace, (str, bytes, tuple)):
return namespace
elif isinstance(namespace, Mapping):
if isinstance(namespace, Mapping):
return {
k: nested_simplenamespace_to_dict(v) for k, v in namespace.items()
}
elif isinstance(namespace, Iterable):
if isinstance(namespace, Iterable):
return [nested_simplenamespace_to_dict(x) for x in namespace]
elif isinstance(namespace, SimpleNamespace):
if isinstance(namespace, SimpleNamespace):
return nested_simplenamespace_to_dict(namespace.__dict__)
else:
return namespace
return namespace


def get_human_time(milliseconds: float) -> str:
Expand Down Expand Up @@ -399,8 +398,7 @@ def command_detail(
return hidden_command_detail_template.format(
cmd_id=cmd_id, name=name, value=value
)
else:
return command_detail_template.format(name=name, value=value)
return command_detail_template.format(name=name, value=value)


def command_card(log: dict, stream_dir: Path) -> Iterator[str]:
Expand Down Expand Up @@ -882,19 +880,20 @@ def sgr_8bit_color_to_html(sgr_params: List[str]) -> str: # noqa: PLR0911
green = str(51 * green_6cube)
blue = str(51 * blue_6cube)
return sgr_24bit_color_to_html([sgr_params[0], "2", red, green, blue])
elif 231 < sgr_256 < 256:
if 231 < sgr_256 < 256:
gray = str(8 + (sgr_256 - 232) * 10)
return sgr_24bit_color_to_html([sgr_params[0], "2", gray, gray, gray])
elif sgr_params[0] == "38":
if sgr_params[0] == "38":
if sgr_256 < 8:
return sgr_4bit_color_and_style_to_html(str(30 + sgr_256))
elif sgr_256 < 16:
if sgr_256 < 16:
return sgr_4bit_color_and_style_to_html(str(82 + sgr_256))
elif sgr_params[0] == "48":
if sgr_params[0] == "48":
if sgr_256 < 8:
return sgr_4bit_color_and_style_to_html(str(40 + sgr_256))
elif sgr_256 < 16:
if sgr_256 < 16:
return sgr_4bit_color_and_style_to_html(str(92 + sgr_256))
return "THIS SHOULD NEVER HAPPEN"


def sgr_24bit_color_to_html(sgr_params: List[str]) -> str:
Expand All @@ -913,10 +912,9 @@ def sgr_24bit_color_to_html(sgr_params: List[str]) -> str:
r, g, b = sgr_params[2:5] if len(sgr_params) == 5 else ("0", "0", "0")
if len(sgr_params) > 1 and sgr_params[:2] == ["38", "2"]:
return f'<span style="color: rgb({r}, {g}, {b})">'
elif len(sgr_params) > 1 and sgr_params[:2] == ["48", "2"]:
if len(sgr_params) > 1 and sgr_params[:2] == ["48", "2"]:
return f'<span style="background-color: rgb({r}, {g}, {b})">'
else:
return "<span>"
return "<span>"


def html_header() -> str:
Expand Down
41 changes: 18 additions & 23 deletions shell_logger/shell_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ def append(path: Path) -> ShellLogger:

# Deserialize the corresponding JSON object into a ShellLogger.
with path.open("r") as jf:
loaded_logger = json.load(jf, cls=ShellLoggerDecoder)
return loaded_logger
return json.load(jf, cls=ShellLoggerDecoder)

def __init__( # noqa: PLR0913
self,
Expand Down Expand Up @@ -444,8 +443,7 @@ def to_html(self) -> Union[Iterator[str], List[Iterator[str]]]:
html.append(command_card(log, self.stream_dir))
if self.is_parent():
return parent_logger_card_html(self.name, html)
else:
return html
return html

def finalize(self) -> None:
"""
Expand Down Expand Up @@ -741,32 +739,31 @@ def default(self, obj: object) -> object: # noqa: PLR0911
**{"__type__": "ShellLogger"},
**{k: self.default(v) for k, v in obj.__dict__.items()},
}
elif isinstance(obj, (int, float, str, bytes)):
if isinstance(obj, (int, float, str, bytes)):
return obj
elif isinstance(obj, Mapping):
if isinstance(obj, Mapping):
return {k: self.default(v) for k, v in obj.items()}
elif isinstance(obj, tuple):
if isinstance(obj, tuple):
return {"__type__": "tuple", "items": obj}
elif isinstance(obj, Iterable):
if isinstance(obj, Iterable):
return [self.default(x) for x in obj]
elif isinstance(obj, datetime):
if isinstance(obj, datetime):
return {
"__type__": "datetime",
"value": obj.strftime("%Y-%m-%d_%H:%M:%S:%f"),
"format": "%Y-%m-%d_%H:%M:%S:%f",
}
elif isinstance(obj, Path):
if isinstance(obj, Path):
return {"__type__": "Path", "value": str(obj)}
elif obj is None:
if obj is None:
return None
elif isinstance(obj, Shell):
if isinstance(obj, Shell):
return {
"__type__": "Shell",
"pwd": obj.pwd(),
"login_shell": obj.login_shell,
}
else:
return json.JSONEncoder.default(self, obj)
return json.JSONEncoder.default(self, obj)


class ShellLoggerDecoder(json.JSONDecoder):
Expand Down Expand Up @@ -804,8 +801,8 @@ def dict_to_object(obj: dict) -> object: # noqa: PLR0911
"""
if "__type__" not in obj:
return obj
elif obj["__type__"] == "ShellLogger":
logger = ShellLogger(
if obj["__type__"] == "ShellLogger":
return ShellLogger(
obj["name"],
log_dir=obj["log_dir"],
stream_dir=obj["stream_dir"],
Expand All @@ -817,14 +814,12 @@ def dict_to_object(obj: dict) -> object: # noqa: PLR0911
done_time=obj["done_time"],
duration=obj["duration"],
)
return logger
elif obj["__type__"] == "datetime":
if obj["__type__"] == "datetime":
return datetime.strptime(obj["value"], obj["format"])
elif obj["__type__"] == "Path":
if obj["__type__"] == "Path":
return Path(obj["value"])
elif obj["__type__"] == "tuple":
if obj["__type__"] == "tuple":
return tuple(obj["items"])
elif obj["__type__"] == "Shell":
if obj["__type__"] == "Shell":
return Shell(Path(obj["pwd"]), login_shell=obj["login_shell"])
else:
return None
return None
6 changes: 3 additions & 3 deletions shell_logger/stats_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ def unproxied_stats(self) -> None:
Returns:
None
"""
return None
return

@StatsCollector.subclass
class CPUStatsCollector(StatsCollector):
Expand Down Expand Up @@ -359,7 +359,7 @@ def unproxied_stats(self) -> None:
Returns:
None
"""
return None
return

@StatsCollector.subclass
class MemoryStatsCollector(StatsCollector):
Expand Down Expand Up @@ -394,4 +394,4 @@ def unproxied_stats(self) -> None:
Returns:
None
"""
return None
return
7 changes: 3 additions & 4 deletions shell_logger/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,11 @@ def trace_collector(**kwargs) -> Trace:
if len(collectors) == 1:
collector = collectors[0]
return collector(**kwargs)
elif len(collectors) == 0:
if len(collectors) == 0:
message = f"Unsupported trace type: {trace_name}"
raise RuntimeError(message)
else:
message = f"Multiple trace types match '{trace_name}'."
raise RuntimeError(message)
message = f"Multiple trace types match '{trace_name}'."
raise RuntimeError(message)


class Trace:
Expand Down

0 comments on commit 298d05c

Please sign in to comment.