From 5ff1d81cfed7bcd00eafa7059db61b91e29e1d9c Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Thu, 14 Aug 2025 23:14:36 +0200 Subject: better typing for edit --- patternutils/commands/targs.py | 2 +- patternutils/utils.py | 41 ++++++++++++++++++++++++++--------------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/patternutils/commands/targs.py b/patternutils/commands/targs.py index a90313a..b6fc509 100644 --- a/patternutils/commands/targs.py +++ b/patternutils/commands/targs.py @@ -154,7 +154,7 @@ def targs( if editor: try: if (new_commands := utils.edit(commands)) is not None: - commands = list(new_commands.values()) + commands = new_commands except RuntimeError: click.secho("Your edit is not parseable!", fg="red", err=True) raise SystemExit(1) diff --git a/patternutils/utils.py b/patternutils/utils.py index 85734db..22d4123 100644 --- a/patternutils/utils.py +++ b/patternutils/utils.py @@ -1,6 +1,6 @@ import json import os -from typing import Any, Generator, Optional +from typing import Any, Generator, Optional, overload import click @@ -11,7 +11,15 @@ def max_procs() -> int: return 1 if cpu_count is None else cpu_count * 2 -def edit(data: dict[str, str] | list[str]) -> Optional[dict[str, str]]: +@overload +def edit(data: dict[str, str]) -> Optional[dict[str, str]]: ... + + +@overload +def edit(data: list[str]) -> Optional[list[str]]: ... + + +def edit(data: dict[str, str] | list[str]) -> Optional[dict[str, str] | list[str]]: """Opens an interactive editor for modifying dictionary or list entries. Args: @@ -21,24 +29,27 @@ def edit(data: dict[str, str] | list[str]) -> Optional[dict[str, str]]: A dictionary of modified entries or None if no changes were made. """ - longest = len(max(data, key=len)) - if isinstance(data, dict): - temporary = [f"{key.ljust(longest)}\t{value}\n" for key, value in data.items()] + longest = len(max(data, key=len)) + temporary = [f"{key.ljust(longest)}\t{value}" for key, value in data.items()] else: - temporary = [f"{value.ljust(longest)}\t{value}\n" for value in data] + temporary = data try: - if (edited := click.edit("".join(temporary))) is not None: - new_data = dict() - for line in edited.split("\n"): - if line and "\t" in line: - old, new = line.split("\t") - new_data[old.strip()] = new - if new_data: - return new_data + if (edited := click.edit("\n".join(temporary))) is not None: + if isinstance(data, dict): + new_data = dict() + for line in edited.split("\n"): + if line and "\t" in line: + old, new = line.split("\t") + new_data[old.strip()] = new + + if new_data: + return new_data + else: + raise RuntimeError else: - raise RuntimeError + return edited.split("\n") else: return None except click.UsageError: -- cgit v1.3.1