bear-utils 0.8.22__py3-none-any.whl → 0.8.24__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,11 @@ from bear_utils.constants._exceptions import UserCancelledError
10
10
  from bear_utils.constants._lazy_typing import OptBool, OptFloat, OptInt, OptStr
11
11
  from bear_utils.logger_manager import get_console
12
12
 
13
- # TODO: ehhhhhhhh, it is okay
13
+
14
+ def _parse_exit(value: str) -> bool:
15
+ """Parse a string into a boolean indicating if the user wants to exit."""
16
+ lower_value: str = value.lower().strip()
17
+ return lower_value in ("exit", "quit", "q")
14
18
 
15
19
 
16
20
  def _parse_bool(value: str) -> bool:
@@ -70,7 +74,7 @@ def ask_question(question: str, expected_type: type, default: Any = None) -> Any
70
74
  UserCancelledError: If the user cancels input with Ctrl+C
71
75
  ValueError: If an unsupported type is specified
72
76
  """
73
- console, sub = get_console("prompt_helpers.py")
77
+ console, _ = get_console("prompt_helpers.py")
74
78
 
75
79
  try:
76
80
  while True:
@@ -80,14 +84,14 @@ def ask_question(question: str, expected_type: type, default: Any = None) -> Any
80
84
  if not response:
81
85
  if default is not None:
82
86
  return default
83
- sub.error("Input required. Please enter a value.")
87
+ console.error("Input required. Please enter a value.")
84
88
  continue
85
89
  try:
86
90
  result: str | int | float | bool = _convert_value(response, expected_type)
87
- sub.verbose(f"{expected_type.__name__} detected")
91
+ console.verbose(f"{expected_type.__name__} detected")
88
92
  return result
89
93
  except ValueError as e:
90
- sub.error(f"Invalid input: {e}. Please enter a valid {expected_type.__name__}.")
94
+ console.error(f"Invalid input: {e}. Please enter a valid {expected_type.__name__}.")
91
95
 
92
96
  except KeyboardInterrupt:
93
97
  raise UserCancelledError("User cancelled input") from None
@@ -108,15 +112,13 @@ def ask_yes_no(question: str, default: bool | None = None) -> bool | None:
108
112
  try:
109
113
  while True:
110
114
  console.print(question)
111
- response = prompt("> ").strip().lower()
112
-
115
+ response: str = prompt("> ").strip().lower()
113
116
  if not response:
114
117
  if default is not None:
115
118
  return default
116
119
  sub.error("Please enter 'yes', 'no', or 'exit'.")
117
120
  continue
118
-
119
- if response in ("exit", "quit"):
121
+ if _parse_exit(response):
120
122
  return None
121
123
  try:
122
124
  return _parse_bool(response)
@@ -128,7 +130,10 @@ def ask_yes_no(question: str, default: bool | None = None) -> bool | None:
128
130
 
129
131
 
130
132
  def restricted_prompt(
131
- question: str, valid_options: list[str], exit_command: str = "exit", case_sensitive: bool = False
133
+ question: str,
134
+ valid_options: list[str],
135
+ exit_command: str = "exit",
136
+ case_sensitive: bool = False,
132
137
  ) -> str | None:
133
138
  """Continuously prompt the user until they provide a valid response or exit.
134
139
 
@@ -141,12 +146,12 @@ def restricted_prompt(
141
146
  Returns:
142
147
  The user's response or None if they chose to exit
143
148
  """
144
- console, sub = get_console("prompt_helpers.py")
145
- completer_options = [*valid_options, exit_command]
149
+ console, _ = get_console("prompt_helpers.py")
150
+ completer_options: list[str] = [*valid_options, exit_command]
146
151
  completer = WordCompleter(completer_options)
147
152
 
148
- comparison_options = valid_options if case_sensitive else [opt.lower() for opt in valid_options]
149
- comparison_exit = exit_command if case_sensitive else exit_command.lower()
153
+ comparison_options: list[str] = valid_options if case_sensitive else [opt.lower() for opt in valid_options]
154
+ comparison_exit: str = exit_command if case_sensitive else exit_command.lower()
150
155
 
151
156
  class OptionValidator(Validator):
152
157
  def validate(self, document: Any) -> None:
@@ -162,11 +167,14 @@ def restricted_prompt(
162
167
  while True:
163
168
  console.print(question)
164
169
  response: str = prompt(
165
- "> ", completer=completer, validator=OptionValidator(), complete_while_typing=True
170
+ "> ",
171
+ completer=completer,
172
+ validator=OptionValidator(),
173
+ complete_while_typing=True,
166
174
  ).strip()
167
175
  comparison_response: str = response if case_sensitive else response.lower()
168
176
  if not response:
169
- sub.error("Please enter a valid option or 'exit'.")
177
+ console.error("Please enter a valid option or 'exit'.")
170
178
  continue
171
179
  if comparison_response == comparison_exit:
172
180
  return None
@@ -175,7 +183,6 @@ def restricted_prompt(
175
183
  idx: int = comparison_options.index(comparison_response)
176
184
  return valid_options[idx]
177
185
  return response
178
-
179
186
  except KeyboardInterrupt:
180
- sub.warning("KeyboardInterrupt: Exiting the prompt.")
187
+ console.warning("KeyboardInterrupt: Exiting the prompt.")
181
188
  return None
@@ -0,0 +1,90 @@
1
+ """A simple bridge for augmenting Typer with alias support and command execution for interactive use."""
2
+
3
+ from collections.abc import Callable
4
+ import shlex
5
+ from typing import Any, TypedDict
6
+
7
+ from rich.console import Console
8
+ from singleton_base import SingletonBase
9
+ from typer import Exit, Typer
10
+ from typer.models import CommandInfo
11
+
12
+ from bear_utils.logger_manager import AsyncLoggerProtocol, LoggerProtocol
13
+
14
+
15
+ class CommandMeta(TypedDict):
16
+ """Metadata for a Typer command."""
17
+
18
+ name: str
19
+ help: str
20
+ hidden: bool
21
+
22
+
23
+ def get_command_meta(command: CommandInfo) -> CommandMeta:
24
+ """Extract metadata from a Typer command."""
25
+ return {
26
+ "name": command.name or (command.callback.__name__ if command.callback else "unknown"),
27
+ "help": (command.callback.__doc__ if command.callback else None) or "No description available",
28
+ "hidden": command.hidden,
29
+ }
30
+
31
+
32
+ # TODO: Add support for usage statements for a more robust help system
33
+
34
+
35
+ class TyperBridge(SingletonBase):
36
+ """Simple bridge for Typer command execution."""
37
+
38
+ def __init__(self, typer_app: Typer, console: AsyncLoggerProtocol | LoggerProtocol | Console) -> None:
39
+ """Initialize the TyperBridge with a Typer app instance."""
40
+ self.app: Typer = typer_app
41
+ self.console: AsyncLoggerProtocol | LoggerProtocol | Console = console or Console()
42
+ self.command_meta: dict[str, CommandMeta] = {}
43
+
44
+ def metadata(self, *alias_names: str) -> Callable[..., Callable[..., Any]]:
45
+ """Register aliases as hidden Typer commands."""
46
+
47
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
48
+ for alias in alias_names:
49
+ self.app.command(name=alias, hidden=True)(func)
50
+ return func
51
+
52
+ return decorator
53
+
54
+ def execute_command(self, command_string: str) -> bool:
55
+ """Execute command via Typer. Return True if successful."""
56
+ try:
57
+ parts: list[str] = shlex.split(command_string.strip())
58
+ if not parts:
59
+ return False
60
+ self.app(parts, standalone_mode=False)
61
+ return True
62
+ except Exit:
63
+ return True
64
+ except Exception as e:
65
+ if isinstance(self.console, Console):
66
+ self.console.print(f"[red]Error executing command: {e}[/red]")
67
+ else:
68
+ self.console.error(f"Error executing command: {e}", exc_info=True)
69
+ return False
70
+
71
+ def bootstrap_command_meta(self) -> None:
72
+ """Bootstrap command metadata from the Typer app."""
73
+ if not self.command_meta:
74
+ for cmd in self.app.registered_commands:
75
+ cmd_meta: CommandMeta = get_command_meta(command=cmd)
76
+ self.command_meta[cmd_meta["name"]] = cmd_meta
77
+
78
+ def get_all_command_info(self, show_hidden: bool = False) -> dict[str, CommandMeta]:
79
+ """Get all command information from the Typer app."""
80
+ if not self.command_meta:
81
+ self.bootstrap_command_meta()
82
+ if not show_hidden:
83
+ return {name: meta for name, meta in self.command_meta.items() if not meta["hidden"]}
84
+ return self.command_meta
85
+
86
+ def get_command_info(self, command_name: str) -> CommandMeta | None:
87
+ """Get metadata for a specific command."""
88
+ if not self.command_meta:
89
+ self.bootstrap_command_meta()
90
+ return self.command_meta.get(command_name)
@@ -32,42 +32,35 @@ class DatabaseManager:
32
32
  raise ValueError("Base class is not set, failed to set base.")
33
33
  return cls._base
34
34
 
35
- def __init__(self, db_url: str | Path | None = None):
35
+ def __init__(self, db_url: str | Path | None = None, default_schema: str = "sqlite:///"):
36
36
  if db_url is None or db_url == "":
37
37
  raise ValueError("Database URL cannot be None or empty.")
38
- if isinstance(db_url, str) and not db_url.startswith("sqlite://"):
39
- db_url = f"sqlite:///{db_url}"
38
+ if isinstance(db_url, str) and not db_url.startswith(default_schema):
39
+ db_url = f"{default_schema}{db_url}"
40
40
  self.db_url: str = str(db_url)
41
41
  self.engine: Engine = create_engine(self.db_url, echo=False)
42
42
  base: DeclarativeMeta = DatabaseManager.get_base()
43
43
  self.metadata: MetaData = base.metadata
44
- self.SessionFactory = sessionmaker(bind=self.engine)
45
- self.session = scoped_session(self.SessionFactory)
44
+ self.SessionFactory: sessionmaker[Session] = sessionmaker(bind=self.engine)
45
+ self.session: scoped_session[Session] = scoped_session(self.SessionFactory)
46
46
  atexit.register(self.close_all)
47
47
  self.create_tables()
48
48
 
49
49
  def get_all_records(self, table_obj: type[TableType]) -> list[TableType]:
50
50
  """Get all records from a table."""
51
- with self.open_session() as session:
52
- return session.query(table_obj).all()
51
+ return self.session().query(table_obj).all()
53
52
 
54
53
  def count_records(self, table_obj: type[TableType]) -> int:
55
54
  """Count the number of records in a table."""
56
- with self.open_session() as session:
57
- count: int = session.query(table_obj).count()
58
- return count
55
+ return self.session().query(table_obj).count()
59
56
 
60
57
  def get_records_by_var(self, table_obj: type[TableType], variable: str, value: str) -> list[TableType]:
61
58
  """Get records from a table by a specific variable."""
62
- with self.open_session() as session:
63
- records: list[TableType] = session.query(table_obj).filter(getattr(table_obj, variable) == value).all()
64
- return records
59
+ return self.session().query(table_obj).filter(getattr(table_obj, variable) == value).all()
65
60
 
66
61
  def count_records_by_var(self, table_obj: type[TableType], variable: str, value: str) -> int:
67
62
  """Count the number of records in a table by a specific variable."""
68
- with self.open_session() as session:
69
- count: int = session.query(table_obj).filter(getattr(table_obj, variable) == value).count()
70
- return count
63
+ return self.session().query(table_obj).filter(getattr(table_obj, variable) == value).count()
71
64
 
72
65
  @contextmanager
73
66
  def open_session(self) -> Generator[Session, Any]:
@@ -14,13 +14,14 @@ from bear_utils.extras._async_helpers import AsyncResponseModel, create_async_ta
14
14
  # Pydantic will yell if we put this into a TYPE_CHECKING block.
15
15
  from bear_utils.logger_manager import AsyncLoggerProtocol, LoggerProtocol # noqa: TC001
16
16
 
17
- SUCCESS: list[str] = ["name", "success"]
18
- FAILURE: list[str] = ["name"]
19
-
20
17
  if TYPE_CHECKING:
21
18
  from collections.abc import Callable
22
19
 
23
20
 
21
+ SUCCESS: list[str] = ["name", "success", "number_of_tasks"]
22
+ FAILURE: list[str] = ["name", "number_of_tasks"]
23
+
24
+
24
25
  class FunctionResponse(BaseModel):
25
26
  """A class to represent the response of a function call, including success status, content, and error messages."""
26
27
 
@@ -337,10 +338,8 @@ class FunctionResponse(BaseModel):
337
338
  content = []
338
339
  if not isinstance(error, (list | str)):
339
340
  error = []
340
-
341
341
  if not content and not error:
342
342
  return
343
-
344
343
  res: AsyncResponseModel = create_async_task(
345
344
  _log_messages,
346
345
  content=content,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bear-utils
3
- Version: 0.8.22
3
+ Version: 0.8.24
4
4
  Summary: Various utilities for Bear programmers, including a rich logging utility, a disk cache, and a SQLite database wrapper amongst other things.
5
5
  Author-email: chaz <bright.lid5647@fastmail.com>
6
6
  Requires-Python: >=3.12
@@ -19,12 +19,13 @@ Requires-Dist: singleton-base>=1.0.5
19
19
  Requires-Dist: sqlalchemy<3.0.0,>=2.0.40
20
20
  Requires-Dist: tinydb>=4.8.2
21
21
  Requires-Dist: toml>=0.10.2
22
+ Requires-Dist: typer>=0.16.0
22
23
  Requires-Dist: uvicorn>=0.35.0
23
24
  Provides-Extra: gui
24
25
  Requires-Dist: pyqt6>=6.9.0; extra == 'gui'
25
26
  Description-Content-Type: text/markdown
26
27
 
27
- # Bear Utils v# Bear Utils v0.8.22
28
+ # Bear Utils v# Bear Utils v0.8.24
28
29
 
29
30
  Personal set of tools and utilities for Python projects, focusing on modularity and ease of use. This library includes components for caching, database management, logging, time handling, file operations, CLI prompts, image processing, clipboard interaction, gradient utilities, event systems, and async helpers.
30
31
 
@@ -12,7 +12,8 @@ bear_utils/ai/ai_helpers/_types.py,sha256=rmnl8mTlUj0LyL9USzTb-EN_31TtXY6qzhkOEu
12
12
  bear_utils/cache/__init__.py,sha256=c9z1mLhWpZJHZdXRlviYQXl8tc9KTJCM8vin3moDO3I,4578
13
13
  bear_utils/cli/__init__.py,sha256=H2QpLyHpQS_Yn3sF2px7n4KqT97LEe7Oyzafg2iHcpc,503
14
14
  bear_utils/cli/commands.py,sha256=5ppEjvVV_g28WLaIFtKgz-ctzwoo-g-KpHTXNx9xBzo,3161
15
- bear_utils/cli/prompt_helpers.py,sha256=wxOz8IkL_fP7q1Fbiy1cv1r74qVOG2nl2QKUueZ2MjE,6535
15
+ bear_utils/cli/prompt_helpers.py,sha256=0Cwa5bk_7xgLBeLuJje9LwNtrRYlTCAW__mpFpFD1gw,6814
16
+ bear_utils/cli/typer_bridge.py,sha256=ah2dCJ_LJFRy3hDF5Dd8rYqq70H6ko4KTuCuVcUmRAw,3408
16
17
  bear_utils/cli/shell/__init__.py,sha256=2s3oR6CqLKj1iyERy7YafWT3t3KzTr70Z1yaLKa6IiQ,42
17
18
  bear_utils/cli/shell/_base_command.py,sha256=T1bwY9UX355Mv2u7JjSgI4U7VoWCTibszG8WvC3IEo4,2789
18
19
  bear_utils/cli/shell/_base_shell.py,sha256=cjpgwf8R6iP9T8HZDy_MKIirW5qM0btXLmmCce1Ll58,16702
@@ -28,7 +29,7 @@ bear_utils/constants/date_related.py,sha256=vwgPPGamVJ8p12iRFu3IzTksmGfhqYULwrk-
28
29
  bear_utils/constants/server.py,sha256=1gWA3h1HH12uk5nqX3r5EFkffPKVDTo3he51teHSDbk,271
29
30
  bear_utils/constants/time_related.py,sha256=Mykb27THqC-K0HFrbbrdkTNJUKhzBEOfmPJ0rx2-L6E,705
30
31
  bear_utils/database/__init__.py,sha256=dS_HHJKESpsI6BFDLVx055o0GCJV9CMYOQVuHs7EfgY,192
31
- bear_utils/database/_db_manager.py,sha256=rW4yq6arMF7UbgKrA7C2Wi37O-byqzae39tIZixfRZk,3977
32
+ bear_utils/database/_db_manager.py,sha256=bbg5zG06DcOvd37oafLIqc480BwF9ZW9qWF3ldZHR8o,3805
32
33
  bear_utils/events/__init__.py,sha256=EFqmuzhaEYK9kjkGlrM7bjdjPwFEDbKn6RjJKfIBEJY,414
33
34
  bear_utils/events/events_class.py,sha256=vPDjWrbut8L3TFn7byyYFZpWYM5ADIqtW2Aeh-qtKfQ,1632
34
35
  bear_utils/events/events_module.py,sha256=DkQsDZ5WzM1MH1Msg7mRny40a17Jl31CXbpw4-pICxc,2349
@@ -37,7 +38,7 @@ bear_utils/extras/_async_helpers.py,sha256=4buULZZkR0n2z13Q8_FK59dMchj0Mup03YBaq
37
38
  bear_utils/extras/_tools.py,sha256=-rOH_-0pRd7_-o_l2QqByYBB2yhbXcTC8fuQf4Sx-eg,7671
38
39
  bear_utils/extras/platform_utils.py,sha256=Ai7ow7S-_cKb5zFwFh8dkC8xmbMJFy-0_-w3NCERdEw,1362
39
40
  bear_utils/extras/responses/__init__.py,sha256=XbE4VKemrKRwx9E5jqy__OiM_AAjA58ebnqQ2hytnT0,225
40
- bear_utils/extras/responses/function_response.py,sha256=VFhYGoSXbqdkgeBWYdmHcHcJ2Z0BFg_Y8EmdkaF442Y,16220
41
+ bear_utils/extras/responses/function_response.py,sha256=aGUhxfliaqE2tXKGtVPDeOy5JJRjHN5M9gRgI1IsopY,16257
41
42
  bear_utils/extras/wrappers/__init__.py,sha256=crh4sKOLvuhNMVX5bJYjCFWtXtH7G47UgNPOHq3HXTk,43
42
43
  bear_utils/extras/wrappers/add_methods.py,sha256=z2XZG2ZoYOB1MaGiLli4NRyyTeRgBy7tuYsiy8mTa9s,4422
43
44
  bear_utils/files/__init__.py,sha256=mIdnFSXoDE64ElM43bN2m6KuafURnN82ki0pdqN8q2o,201
@@ -86,6 +87,6 @@ bear_utils/monitoring/__init__.py,sha256=9DKNIWTp_voLnaWgiP-wJ-o_N0hYixo-MzjUmg8
86
87
  bear_utils/monitoring/_common.py,sha256=LYQFxgTP9fk0cH71IQTuGwBYYPWCqHP_mMRNecoD76M,657
87
88
  bear_utils/monitoring/host_monitor.py,sha256=e0TYRJw9iDj5Ga6y3ck1TBFEeH42Cax5mQYaNU8yams,13241
88
89
  bear_utils/time/__init__.py,sha256=VctjJG17SyEHAFXytI1sZrOrq7zm3hVenIDOJFdaMN0,1424
89
- bear_utils-0.8.22.dist-info/METADATA,sha256=bI6HOJaPlDs8ml0B_n-if7qmczI67TKOllT-6JkXXhY,8763
90
- bear_utils-0.8.22.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
91
- bear_utils-0.8.22.dist-info/RECORD,,
90
+ bear_utils-0.8.24.dist-info/METADATA,sha256=6nRLOfttz27oKf-N_I-gCBeLmjX7tpSnlOvUc228JyA,8792
91
+ bear_utils-0.8.24.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
92
+ bear_utils-0.8.24.dist-info/RECORD,,