pyhivelms-core 3.10.1__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.
Files changed (67) hide show
  1. pyhive/__init__.py +16 -0
  2. pyhive/cli/__init__.py +0 -0
  3. pyhive/cli/assignments.py +87 -0
  4. pyhive/cli/auth.py +162 -0
  5. pyhive/cli/backends.py +216 -0
  6. pyhive/cli/base.py +160 -0
  7. pyhive/cli/classes.py +193 -0
  8. pyhive/cli/cli.py +261 -0
  9. pyhive/cli/client_factory.py +192 -0
  10. pyhive/cli/docs.py +111 -0
  11. pyhive/cli/examples.py +87 -0
  12. pyhive/cli/exercises.py +110 -0
  13. pyhive/cli/formatter.py +101 -0
  14. pyhive/cli/lessons.py +56 -0
  15. pyhive/cli/modules.py +108 -0
  16. pyhive/cli/programs.py +110 -0
  17. pyhive/cli/queues.py +418 -0
  18. pyhive/cli/state.py +39 -0
  19. pyhive/cli/subjects.py +110 -0
  20. pyhive/cli/users.py +297 -0
  21. pyhive/core/__init__.py +22 -0
  22. pyhive/core/aliases.py +110 -0
  23. pyhive/core/backends.py +159 -0
  24. pyhive/core/generations.py +166 -0
  25. pyhive/core/shell.py +352 -0
  26. pyhive/core/sso_utils.py +276 -0
  27. pyhive/core/transport.py +78 -0
  28. pyhive/docs/SKILL.md +193 -0
  29. pyhive/docs/cli.md +320 -0
  30. pyhive/docs/examples.md +86 -0
  31. pyhive/docs/index.md +77 -0
  32. pyhive/docs/sdk.md +609 -0
  33. pyhive/examples/__init__.py +45 -0
  34. pyhive/examples/__main__.py +5 -0
  35. pyhive/examples/assignments_csv.py +47 -0
  36. pyhive/examples/build_module.py +56 -0
  37. pyhive/examples/class_roster.py +25 -0
  38. pyhive/examples/connect.py +36 -0
  39. pyhive/examples/find_student.py +45 -0
  40. pyhive/examples/open_help_requests.py +31 -0
  41. pyhive/examples/program_tree.py +44 -0
  42. pyhive/examples/weekly_schedule.py +39 -0
  43. pyhive/hive/__init__.py +6 -0
  44. pyhive/hive/v5_11_1.pyi +6 -0
  45. pyhive/hive/v5_12_0.pyi +6 -0
  46. pyhive/hive/v6_0_1.pyi +6 -0
  47. pyhive/hive/v6_1_1.pyi +6 -0
  48. pyhive/hive/v6_2_0.pyi +6 -0
  49. pyhive/hive/v6_3_0.pyi +6 -0
  50. pyhive/hive/v6_4_0.pyi +6 -0
  51. pyhive/hive/v7_0_1.pyi +6 -0
  52. pyhive/hive/v7_1_0.pyi +6 -0
  53. pyhive/hive/v7_2_0.pyi +6 -0
  54. pyhive/hive/v7_3_0.pyi +6 -0
  55. pyhive/hive/v8_0_4.pyi +6 -0
  56. pyhive/locate.py +74 -0
  57. pyhive/py.typed +0 -0
  58. pyhive/src/__init__.py +0 -0
  59. pyhive/src/_generated_versions.py +5 -0
  60. pyhive/src/access_tokens.py +49 -0
  61. pyhive/src/api_versions.py +65 -0
  62. pyhive/src/authenticated_hive_client.py +506 -0
  63. pyhive/types.pyi +5 -0
  64. pyhivelms_core-3.10.1.dist-info/METADATA +143 -0
  65. pyhivelms_core-3.10.1.dist-info/RECORD +67 -0
  66. pyhivelms_core-3.10.1.dist-info/WHEEL +4 -0
  67. pyhivelms_core-3.10.1.dist-info/entry_points.txt +2 -0
pyhive/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Public package for the pyhive distribution."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from .core.aliases import install as _install_aliases
8
+
9
+ _install_aliases()
10
+
11
+ if TYPE_CHECKING:
12
+ from pyhive_backend_gen4.client import HiveClient
13
+ else:
14
+ from .core.shell import HiveClient
15
+
16
+ __all__ = ["HiveClient"]
pyhive/cli/__init__.py ADDED
File without changes
@@ -0,0 +1,87 @@
1
+ """Assignments CLI subcommand group."""
2
+
3
+ from typing import Any
4
+
5
+ import typer
6
+
7
+ from pyhive.cli.base import PyHiveTyper
8
+ from pyhive.cli.client_factory import (
9
+ HIVE_URL_OPTION,
10
+ VERIFY_OPTION,
11
+ get_hive_client,
12
+ )
13
+ from pyhive.cli.formatter import (
14
+ print_error_and_exit,
15
+ print_formatted_list,
16
+ print_info,
17
+ print_result,
18
+ )
19
+
20
+ assignment_app = PyHiveTyper(help="Manage Hive assignments.")
21
+
22
+
23
+ @assignment_app.callback(invoke_without_command=True)
24
+ def assignment_callback(
25
+ ctx: typer.Context,
26
+ hive_url: str = HIVE_URL_OPTION,
27
+ verify: bool = VERIFY_OPTION,
28
+ ) -> None:
29
+ if ctx.invoked_subcommand is None:
30
+ list_assignments(hive_url=hive_url, verify=verify)
31
+
32
+
33
+ @assignment_app.command(name="list")
34
+ def list_assignments(
35
+ hive_url: str = HIVE_URL_OPTION,
36
+ verify: bool = VERIFY_OPTION,
37
+ ) -> None:
38
+ """List all assignments."""
39
+ try:
40
+ print_info(f"Fetching assignments from {hive_url}...")
41
+ client = get_hive_client(hive_url=hive_url, verify=verify)
42
+ assignments = sorted(
43
+ [x.to_dict() for x in client.get_assignments()], key=lambda x: x["id"]
44
+ )
45
+
46
+ def text_output() -> None:
47
+ typer.secho(
48
+ f"\nFound {len(assignments)} assignments:", fg=typer.colors.GREEN
49
+ )
50
+ print_formatted_list(
51
+ data=assignments,
52
+ template="- [{id}] user:{user} ex:{exercise} {assignment_status}",
53
+ keys=["id", "user", "exercise", "assignment_status"],
54
+ )
55
+
56
+ print_result({"assignments": assignments}, text_output)
57
+
58
+ except Exception as e: # pylint: disable=broad-exception-caught
59
+ print_error_and_exit(
60
+ message=f"Failed to fetch assignments: {e}",
61
+ error_data={"error": "Assignment fetch failed", "details": str(e)},
62
+ )
63
+
64
+
65
+ @assignment_app.command(name="get")
66
+ def get_assignment(
67
+ assignment_id: int = typer.Argument(..., help="ID of the assignment"),
68
+ hive_url: str = HIVE_URL_OPTION,
69
+ verify: bool = VERIFY_OPTION,
70
+ ) -> None:
71
+ """Get an assignment by ID."""
72
+ try:
73
+ client = get_hive_client(hive_url=hive_url, verify=verify)
74
+ assignment = client.get_assignment(assignment_id)
75
+ data: dict[str, Any] = assignment.to_dict()
76
+
77
+ def text_output() -> None:
78
+ for key, value in data.items():
79
+ typer.echo(f"{key}: {value}")
80
+
81
+ print_result({"assignment": data}, text_output)
82
+
83
+ except Exception as e: # pylint: disable=broad-exception-caught
84
+ print_error_and_exit(
85
+ message=f"Failed to get assignment {assignment_id}: {e}",
86
+ error_data={"error": "Assignment get failed", "details": str(e)},
87
+ )
pyhive/cli/auth.py ADDED
@@ -0,0 +1,162 @@
1
+ """Auth CLI subcommand group: sign in once and reuse the cached Hive URL and token."""
2
+
3
+ import os
4
+ from datetime import datetime
5
+ from typing import Any
6
+
7
+ import typer
8
+
9
+ from pyhive import HiveClient
10
+ from pyhive.cli.base import PyHiveTyper
11
+ from pyhive.cli.client_factory import (
12
+ VERIFY_OPTION,
13
+ clear_credentials,
14
+ default_hive_url,
15
+ get_cached_hive_url,
16
+ get_cached_tokens,
17
+ save_credentials,
18
+ )
19
+ from pyhive.cli.formatter import print_error_and_exit, print_info, print_result
20
+ from pyhive.cli.state import state
21
+ from pyhive.core.sso_utils import get_sso_token
22
+ from pyhive.src.access_tokens import looks_like_personal_access_token
23
+
24
+ auth_app = PyHiveTyper(
25
+ help="Sign in once; later commands reuse the Hive URL and token."
26
+ )
27
+
28
+
29
+ @auth_app.command(name="login")
30
+ def login(
31
+ hive_url: str | None = typer.Option(
32
+ None, help="Hive server URL. Asked for when omitted, unless --json is set."
33
+ ),
34
+ verify: bool = VERIFY_OPTION,
35
+ ) -> None:
36
+ """Sign in with SSO (or check a personal access token given with --token) and cache it in the OS keyring."""
37
+ hive_url = hive_url or state.hive_url
38
+ if hive_url is None:
39
+ hive_url = (
40
+ default_hive_url()
41
+ if state.use_json
42
+ else typer.prompt("Hive URL", default=default_hive_url())
43
+ )
44
+ hive_url = hive_url.rstrip("/")
45
+
46
+ if state.access_token:
47
+ _login_with_access_token(hive_url, verify, state.access_token)
48
+ return
49
+
50
+ try:
51
+ print_info(f"Opening your browser to sign in to {hive_url}...")
52
+ access_token: str
53
+ refresh_token: str
54
+ expires_at: datetime
55
+ access_token, refresh_token, expires_at = get_sso_token(
56
+ hive_url=hive_url, verify=verify
57
+ )
58
+ except Exception as e: # pylint: disable=broad-exception-caught
59
+ print_error_and_exit(
60
+ message=f"Sign-in failed: {e}",
61
+ error_data={"error": "Sign-in failed", "details": str(e)},
62
+ )
63
+
64
+ try:
65
+ save_credentials(hive_url, access_token, refresh_token)
66
+ except Exception as e: # pylint: disable=broad-exception-caught
67
+ print_error_and_exit(
68
+ message=f"Signed in, but could not save to the OS keyring: {e}",
69
+ error_data={"error": "Keyring write failed", "details": str(e)},
70
+ )
71
+
72
+ def text_output() -> None:
73
+ typer.secho(f"Signed in to {hive_url}.", fg=typer.colors.GREEN)
74
+ typer.echo("Later commands use this server and token without signing in again.")
75
+
76
+ print_result({"hive_url": hive_url, "expires_at": expires_at}, text_output)
77
+
78
+
79
+ def _login_with_access_token(hive_url: str, verify: bool, token: str) -> None:
80
+ token = token.strip()
81
+ if not looks_like_personal_access_token(token):
82
+ print_error_and_exit(
83
+ message="auth login --token only accepts personal access tokens (hive_pat_...).",
84
+ error_data={"error": "Not a personal access token"},
85
+ )
86
+
87
+ try:
88
+ client = HiveClient.from_access_token(token, hive_url, verify=verify)
89
+ me = client.get("/api/core/management/users/me/")
90
+ except Exception as e: # pylint: disable=broad-exception-caught
91
+ print_error_and_exit(
92
+ message=f"Sign-in failed: {e}",
93
+ error_data={"error": "Sign-in failed", "details": str(e)},
94
+ )
95
+
96
+ try:
97
+ save_credentials(hive_url, token, None)
98
+ except Exception as e: # pylint: disable=broad-exception-caught
99
+ print_error_and_exit(
100
+ message=f"Token works, but could not save it to the OS keyring: {e}",
101
+ error_data={"error": "Keyring write failed", "details": str(e)},
102
+ )
103
+
104
+ username = me.get("username") if isinstance(me, dict) else None
105
+
106
+ def text_output() -> None:
107
+ typer.secho(
108
+ f"Signed in to {hive_url} as {username} with a personal access token.",
109
+ fg=typer.colors.GREEN,
110
+ )
111
+ typer.echo("Later commands use this server and token until it expires or is revoked.")
112
+
113
+ print_result(
114
+ {"hive_url": hive_url, "username": username, "token_type": "personal_access_token"},
115
+ text_output,
116
+ )
117
+
118
+
119
+ def _token_type(access_token: str | None, refresh_token: str | None) -> str | None:
120
+ if access_token and looks_like_personal_access_token(access_token):
121
+ return "personal_access_token"
122
+ if access_token and refresh_token:
123
+ return "sso"
124
+ return None
125
+
126
+
127
+ @auth_app.command(name="status")
128
+ def status() -> None:
129
+ """Show the cached Hive URL and whether a token is cached; makes no network calls."""
130
+ access_token, refresh_token = get_cached_tokens()
131
+ token_type = _token_type(access_token, refresh_token)
132
+ payload: dict[str, Any] = {
133
+ "hive_url": get_cached_hive_url(),
134
+ "token_cached": token_type is not None,
135
+ "token_type": token_type,
136
+ "env_token_set": bool(os.environ.get("HIVE_ACCESS_TOKEN")),
137
+ }
138
+
139
+ def text_output() -> None:
140
+ typer.echo(f"Hive URL: {payload['hive_url'] or '(none cached)'}")
141
+ cached = {"personal_access_token": "yes (personal access token)", "sso": "yes (SSO)"}
142
+ typer.echo(f"Cached token: {cached.get(token_type or '', 'no')}")
143
+ if payload["env_token_set"]:
144
+ typer.echo("HIVE_ACCESS_TOKEN is set and takes priority over the cache.")
145
+
146
+ print_result(payload, text_output)
147
+
148
+
149
+ @auth_app.command(name="logout")
150
+ def logout() -> None:
151
+ """Remove the cached Hive URL and tokens from the OS keyring."""
152
+ try:
153
+ clear_credentials()
154
+ except Exception as e: # pylint: disable=broad-exception-caught
155
+ print_error_and_exit(
156
+ message=f"Could not clear the OS keyring: {e}",
157
+ error_data={"error": "Keyring delete failed", "details": str(e)},
158
+ )
159
+ print_result(
160
+ {"logged_out": True},
161
+ lambda: typer.echo("Removed the cached Hive URL and token."),
162
+ )
pyhive/cli/backends.py ADDED
@@ -0,0 +1,216 @@
1
+ """
2
+ Name: backends.py
3
+ Purpose: ``pyhive backends``: list, add, remove and pick the Hive API backends,
4
+ plus the first-run picker (#42 phase 5).
5
+ Created: 2026-11-25
6
+
7
+ Backends are shown by the Hive versions they serve, never by generation. The
8
+ newest one is always installed and cannot be removed. Installing runs pip (or
9
+ ``pipx inject``) once; where PyHive must not (uv tool, PEP 668), it prints the
10
+ command instead.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Annotated
19
+
20
+ import typer
21
+
22
+ from pyhive.cli.base import PyHiveTyper
23
+ from pyhive.cli.formatter import print_error_and_exit, print_info, print_result
24
+ from pyhive.cli.state import state
25
+ from pyhive.core.backends import (
26
+ NO_PROMPT_ENV,
27
+ BackendStatus,
28
+ plan,
29
+ run,
30
+ status_for,
31
+ statuses,
32
+ )
33
+ from pyhive.src.api_versions import UnverifiedHiveVersionError
34
+
35
+ backends_app = PyHiveTyper(
36
+ help="Choose which Hive versions this PyHive can talk to (one backend per API family)."
37
+ )
38
+
39
+ MARKER_NAME = "backends.toml"
40
+
41
+
42
+ def marker_path() -> Path:
43
+ """Where the first-run picker records that it ran."""
44
+ import platformdirs # pylint: disable=import-outside-toplevel
45
+
46
+ return Path(platformdirs.user_config_dir("pyhive")) / MARKER_NAME
47
+
48
+
49
+ def _as_dict(status: BackendStatus) -> dict[str, object]:
50
+ return {
51
+ "hive_versions": list(status.versions),
52
+ "installed": status.installed,
53
+ "newest": status.newest,
54
+ "distribution": status.distribution,
55
+ }
56
+
57
+
58
+ def _resolve(hive_versions: list[str]) -> list[BackendStatus]:
59
+ found: dict[str, BackendStatus] = {}
60
+ for hive_version in hive_versions:
61
+ try:
62
+ status = status_for(hive_version)
63
+ except UnverifiedHiveVersionError as exc:
64
+ print_error_and_exit(str(exc))
65
+ found[status.generation] = status
66
+ return list(found.values())
67
+
68
+
69
+ def _apply(to_add: list[BackendStatus], to_remove: list[BackendStatus]) -> None:
70
+ for distributions, remove in (
71
+ ([s.distribution for s in to_add], False),
72
+ ([s.distribution for s in to_remove], True),
73
+ ):
74
+ if not distributions:
75
+ continue
76
+ step = plan(distributions, remove=remove)
77
+ if not step.runnable:
78
+ print_info(f"{step.reason}. Run this yourself:")
79
+ typer.echo(f" {step.shell}")
80
+ continue
81
+ print_info(f"Running: {step.shell}")
82
+ if run(step) != 0:
83
+ print_error_and_exit(
84
+ "The command failed (PyHive does not retry). Run it yourself, "
85
+ f"for example when back online:\n {step.shell}",
86
+ {"command": list(step.command)},
87
+ )
88
+
89
+
90
+ @backends_app.command(name="list")
91
+ def list_backends() -> None:
92
+ """List the Hive versions PyHive supports and whether each is installed."""
93
+ found = statuses()
94
+
95
+ def text_output() -> None:
96
+ for status in found:
97
+ mark = "installed" if status.installed else "not installed"
98
+ newest = " (newest, always installed)" if status.newest else ""
99
+ typer.echo(f"Hive {status.label}: {mark}{newest}")
100
+
101
+ print_result({"backends": [_as_dict(s) for s in found]}, text_output)
102
+
103
+
104
+ @backends_app.command(name="add")
105
+ def add_backends(
106
+ hive_versions: Annotated[
107
+ list[str], typer.Argument(help="Hive versions to support, e.g. 7.3.0")
108
+ ],
109
+ ) -> None:
110
+ """Install the backends serving the given Hive versions."""
111
+ wanted = [s for s in _resolve(hive_versions) if not s.installed]
112
+ if not wanted:
113
+ print_result({"added": []}, lambda: typer.echo("Already installed."))
114
+ return
115
+ _apply(wanted, [])
116
+ print_result(
117
+ {"added": [s.distribution for s in wanted]},
118
+ lambda: typer.echo(
119
+ "Added support for Hive " + "; ".join(s.label for s in wanted)
120
+ ),
121
+ )
122
+
123
+
124
+ @backends_app.command(name="remove")
125
+ def remove_backends(
126
+ hive_versions: Annotated[
127
+ list[str], typer.Argument(help="Hive versions to stop supporting")
128
+ ],
129
+ ) -> None:
130
+ """Uninstall the backends serving the given Hive versions (never the newest)."""
131
+ chosen = _resolve(hive_versions)
132
+ if any(s.newest for s in chosen):
133
+ print_error_and_exit("The newest Hive version's backend cannot be removed.")
134
+ doomed = [s for s in chosen if s.installed]
135
+ _apply([], doomed)
136
+ print_result(
137
+ {"removed": [s.distribution for s in doomed]},
138
+ lambda: typer.echo(
139
+ "Removed support for Hive " + "; ".join(s.label for s in doomed)
140
+ if doomed
141
+ else "Nothing to remove."
142
+ ),
143
+ )
144
+
145
+
146
+ def pick(found: list[BackendStatus]) -> tuple[list[BackendStatus], list[BackendStatus]]:
147
+ """Ask which backends to keep; return (to add, to remove). Needs a terminal."""
148
+ import questionary # pylint: disable=import-outside-toplevel
149
+
150
+ choices = [
151
+ questionary.Choice(
152
+ f"Hive {s.label}",
153
+ value=s.generation,
154
+ checked=s.installed or s.newest,
155
+ disabled="newest, always installed" if s.newest else None,
156
+ )
157
+ for s in found
158
+ ]
159
+ answer = questionary.checkbox(
160
+ "Which Hive versions should PyHive support?", choices=choices
161
+ ).ask()
162
+ if answer is None:
163
+ raise typer.Abort()
164
+ keep = set(answer) | {s.generation for s in found if s.newest}
165
+ to_add = [s for s in found if s.generation in keep and not s.installed]
166
+ to_remove = [s for s in found if s.generation not in keep and s.installed]
167
+ return to_add, to_remove
168
+
169
+
170
+ def _write_marker(found: list[BackendStatus]) -> None:
171
+ path = marker_path()
172
+ path.parent.mkdir(parents=True, exist_ok=True)
173
+ chosen = ", ".join(f'"{s.generation}"' for s in found if s.installed)
174
+ path.write_text(
175
+ "# Written by PyHive's first-run backend picker. Delete it to be asked again.\n"
176
+ f"prompted = true\ninstalled = [{chosen}]\n",
177
+ encoding="utf-8",
178
+ )
179
+
180
+
181
+ @backends_app.command(name="pick")
182
+ def pick_backends() -> None:
183
+ """Choose interactively which Hive versions to support."""
184
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
185
+ print_error_and_exit(
186
+ "`pyhive backends pick` needs a terminal; use `pyhive backends add/remove`."
187
+ )
188
+ to_add, to_remove = pick(statuses())
189
+ _apply(to_add, to_remove)
190
+ _write_marker(statuses())
191
+
192
+
193
+ def should_prompt_first_run(argv: list[str]) -> bool:
194
+ """Whether this CLI run shows the first-run picker."""
195
+ if os.environ.get(NO_PROMPT_ENV) == "1" or state.use_json or "--json" in argv:
196
+ return False
197
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
198
+ return False
199
+ if any(arg in {"backends", "--help", "-h", "version", "docs"} for arg in argv):
200
+ return False
201
+ if marker_path().exists():
202
+ return False
203
+ return not all(s.installed for s in statuses())
204
+
205
+
206
+ def first_run_picker(argv: list[str]) -> None:
207
+ """Offer the picker once, the first time the interactive CLI runs with backends missing."""
208
+ if not should_prompt_first_run(argv):
209
+ return
210
+ print_info(
211
+ f"PyHive can support more Hive versions. Choose now (set {NO_PROMPT_ENV}=1 "
212
+ "to never ask; `pyhive backends pick` to change later)."
213
+ )
214
+ to_add, to_remove = pick(statuses())
215
+ _apply(to_add, to_remove)
216
+ _write_marker(statuses())
pyhive/cli/base.py ADDED
@@ -0,0 +1,160 @@
1
+ """
2
+ Name: base.py
3
+ Purpose: Enterprise Typer subclass with non-destructive global option injection.
4
+ Created: 2026-04-07
5
+ Author: Michael K. Steinberg
6
+ """
7
+
8
+ import functools
9
+ import inspect
10
+ from collections.abc import Callable
11
+ from typing import Any, TypeVar, cast
12
+
13
+ import typer
14
+ from typer.core import TyperGroup
15
+
16
+ from pyhive.cli.state import state
17
+
18
+ F = TypeVar("F", bound=Callable[..., Any])
19
+
20
+ # Define options with defaults.
21
+ GLOBAL_OPTIONS = {
22
+ "use_json": typer.Option(False, "--json", help="Format output as JSON"),
23
+ "cache_token": typer.Option(
24
+ False,
25
+ "--cache-token",
26
+ help="Cache token in OS Keyring. [red]WARNING: Security risk.[/red]",
27
+ ),
28
+ }
29
+
30
+
31
+ # Every command also declares these, so a command's own copy never shadows
32
+ # the root's: they are always hoisted.
33
+ ALWAYS_HOISTED = {"use_json", "cache_token", "hive_url", "verify"}
34
+
35
+
36
+ def _option_names(command: Any, skip: set[str]) -> dict[str, Any]:
37
+ return {
38
+ name: param
39
+ for param in command.params
40
+ if getattr(param, "param_type_name", "") == "option" and param.name not in skip
41
+ for name in (*param.opts, *param.secondary_opts)
42
+ }
43
+
44
+
45
+ def _hoist_root_options(root: Any, args: list[str]) -> list[str]:
46
+ """Move the root command's options to the front, wherever they were typed."""
47
+ root_options = _option_names(root, skip=set())
48
+
49
+ def width(token: str) -> int:
50
+ """Tokens taken by a root option at this position (it and its value), else 0."""
51
+ option = root_options.get(token.split("=", 1)[0])
52
+ if option is None:
53
+ return 0
54
+ return 1 if option.is_flag or "=" in token else 2
55
+
56
+ # Find the command the line ends up running, so its own options win.
57
+ command = root
58
+ i = 0
59
+ while i < len(args) and args[i] != "--":
60
+ if taken := width(args[i]):
61
+ i += taken
62
+ continue
63
+ subcommands = getattr(command, "commands", None)
64
+ if not subcommands or args[i] not in subcommands:
65
+ break
66
+ command = subcommands[args[i]]
67
+ i += 1
68
+ own_options = (
69
+ set() if command is root else set(_option_names(command, ALWAYS_HOISTED))
70
+ )
71
+
72
+ hoisted: list[str] = []
73
+ rest: list[str] = []
74
+ i = 0
75
+ while i < len(args):
76
+ token = args[i]
77
+ if token == "--":
78
+ rest.extend(args[i:])
79
+ break
80
+ taken = width(token)
81
+ if not taken or token.split("=", 1)[0] in own_options:
82
+ rest.append(token)
83
+ i += 1
84
+ continue
85
+ hoisted.extend(args[i : i + taken])
86
+ i += taken
87
+ return hoisted + rest
88
+
89
+
90
+ class GlobalOptionsGroup(TyperGroup):
91
+ """Root group whose options (-u/-p/-t, --json, --hive-url, ...) work anywhere on the line."""
92
+
93
+ def parse_args(self, ctx: Any, args: list[str]) -> list[str]:
94
+ return super().parse_args(ctx, _hoist_root_options(self, args))
95
+
96
+
97
+ class PyHiveTyper(typer.Typer):
98
+ """
99
+ Custom Typer subclass that prevents subcommand defaults from overwriting
100
+ global state flags set at the root level.
101
+ """
102
+
103
+ def _inject_global_options(self, f: F, base_decorator: Callable[[F], Any]) -> F:
104
+ """
105
+ Injects global options into the function signature.
106
+
107
+ Args:
108
+ f (F): The original command function.
109
+ base_decorator (Callable[[F], Any]): The Typer decorator to apply.
110
+
111
+ Returns:
112
+ F: The wrapped and decorated function.
113
+ """
114
+ original_sig = inspect.signature(f)
115
+ original_params: set[str] = set(original_sig.parameters.keys())
116
+
117
+ new_params = list(original_sig.parameters.values())
118
+ for name, option in reversed(list(GLOBAL_OPTIONS.items())):
119
+ if name not in original_params:
120
+ new_params.append(
121
+ inspect.Parameter(
122
+ name,
123
+ inspect.Parameter.KEYWORD_ONLY,
124
+ annotation=bool,
125
+ default=option,
126
+ )
127
+ )
128
+
129
+ # Typer reads __signature__ to build the command's options. F is a
130
+ # TypeVar bound to Callable, which doesn't declare that dunder, so the
131
+ # assignment is invisible to the type system either way.
132
+ f.__signature__ = original_sig.replace( # type: ignore[attr-defined]
133
+ parameters=new_params
134
+ )
135
+
136
+ @functools.wraps(f)
137
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
138
+ if kwargs.get("use_json"):
139
+ state.use_json = True
140
+ if kwargs.get("cache_token"):
141
+ state.cache_token = True
142
+
143
+ filtered_kwargs = {k: v for k, v in kwargs.items() if k in original_params}
144
+
145
+ if any(p.kind == p.VAR_KEYWORD for p in original_sig.parameters.values()):
146
+ return f(*args, **kwargs)
147
+
148
+ return f(*args, **filtered_kwargs)
149
+
150
+ # This tells the type checker that the Typer-decorated wrapper
151
+ # satisfies the signature contract of the original function.
152
+ return cast(F, base_decorator(cast(F, wrapper)))
153
+
154
+ def command(self, *args: Any, **kwargs: Any) -> Callable[[F], F]:
155
+ decorator = super().command(*args, **kwargs)
156
+ return lambda f: self._inject_global_options(f, decorator)
157
+
158
+ def callback(self, *args: Any, **kwargs: Any) -> Callable[[F], F]:
159
+ decorator = super().callback(*args, **kwargs)
160
+ return lambda f: self._inject_global_options(f, decorator)