Skip to content

Commit 2a331fc

Browse files
committed
refactor(prek): enhance type handling and improve workspace resolution
- Updated `run_main` function to utilize a generic type parameter for better type inference. - Refactored workspace resolution functions to improve clarity and maintainability, including renaming `require_absolute_workspace_dir` to `resolve_absolute_workspace_path`. - Enhanced CLI invocation handling by integrating new utility functions for workspace detection and command processing. - Cleaned up various functions to streamline argument handling and improve overall code readability. This update improves type safety and enhances the clarity of workspace management within the CLI, contributing to a more robust and maintainable codebase.
1 parent f8ba090 commit 2a331fc

52 files changed

Lines changed: 1246 additions & 692 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/cyt/cli/exit.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,10 @@
55
import sys
66
from collections.abc import Callable
77
from pathlib import Path
8-
from typing import TypeVar
98

109
INTERRUPTED_EXIT_CODE = 130
1110
QUIET_STOP_EXIT_CODE = 1
1211

13-
_T = TypeVar("_T")
14-
1512

1613
def parse_quiet_cli_flags(argv: list[str]) -> tuple[bool, Path | None]:
1714
"""Parse ``--verbose`` and ``--config PATH`` from trailing stop flags."""
@@ -32,7 +29,7 @@ def parse_quiet_cli_flags(argv: list[str]) -> tuple[bool, Path | None]:
3229
return verbose, config_path
3330

3431

35-
def run_main(main_fn: Callable[..., _T], /, *args: object, **kwargs: object) -> _T:
32+
def run_main[T](main_fn: Callable[..., T], /, *args: object, **kwargs: object) -> T:
3633
"""Run *main_fn* and exit silently on ``KeyboardInterrupt``."""
3734
try:
3835
return main_fn(*args, **kwargs)

‎src/cyt/cloudflare/runtime.py‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,23 +91,35 @@ def tools_hook_cloudflare_cache_settings(config: dict[str, Any] | None = None) -
9191

9292
def tools_hook_cloudflare_url(config: dict[str, Any] | None = None) -> str:
9393
if _tools_hook_cloudflare_url is None:
94-
return ""
94+
from cyt.config import tools_hook_cloudflare_url as config_tools_hook_cloudflare_url
95+
96+
return config_tools_hook_cloudflare_url(config)
9597
return _tools_hook_cloudflare_url(config)
9698

9799

98100
def tools_hook_cloudflare_access_client_id_var(config: dict[str, Any] | None = None) -> str:
99101
if _tools_hook_cloudflare_access_client_id_var is None:
100-
return "CF_ACCESS_CLIENT_ID"
102+
from cyt.config import (
103+
tools_hook_cloudflare_access_client_id_var as config_tools_hook_cloudflare_access_client_id_var,
104+
)
105+
106+
return config_tools_hook_cloudflare_access_client_id_var(config)
101107
return _tools_hook_cloudflare_access_client_id_var(config)
102108

103109

104110
def tools_hook_cloudflare_access_client_secret_var(config: dict[str, Any] | None = None) -> str:
105111
if _tools_hook_cloudflare_access_client_secret_var is None:
106-
return "CF_ACCESS_CLIENT_SECRET"
112+
from cyt.config import (
113+
tools_hook_cloudflare_access_client_secret_var as config_tools_hook_cloudflare_access_client_secret_var,
114+
)
115+
116+
return config_tools_hook_cloudflare_access_client_secret_var(config)
107117
return _tools_hook_cloudflare_access_client_secret_var(config)
108118

109119

110120
def uses_cloudflare_tool_catalog(config: dict[str, Any] | None = None) -> bool:
111121
if _uses_cloudflare_tool_catalog is None:
112-
return False
122+
from cyt.config import uses_cloudflare_tool_catalog as config_uses_cloudflare_tool_catalog
123+
124+
return config_uses_cloudflare_tool_catalog(config)
113125
return _uses_cloudflare_tool_catalog(config)

‎src/cyt/hook/cli_invocation.py‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,10 @@
5353
"INSTALLED_CYT_DAEMON_START_COMMAND_BASE",
5454
"INSTALLED_CYT_MCP_COMMAND",
5555
"HookCliInvocation",
56+
"agent_hook_command_env",
5657
"build_installed_cyt_client_command",
5758
"build_installed_cyt_daemon_restart_command",
5859
"build_installed_cyt_daemon_start_command",
59-
"agent_hook_command_env",
6060
"build_uv_run_dev_command",
6161
"cursor_hooks_dir",
6262
"cyt_cli_script_path",
@@ -69,9 +69,9 @@
6969
"cyt_mcp_mcp_server_entry",
7070
"detect_cyt_mcp_cli_invocation",
7171
"detect_hook_cli_invocation",
72-
"prefix_agent_hook_command",
7372
"invoked_via_cyt_cli_script",
7473
"is_uv_run_dev_hook_command",
74+
"prefix_agent_hook_command",
7575
"proxy_cli_script_path",
7676
"repo_root_from_cyt_cli_script",
7777
"repo_root_from_proxy_cli_script",
@@ -237,14 +237,14 @@ def prefix_command_env(env: dict[str, str], command: str) -> str:
237237
return command
238238
parts: list[str] = []
239239
for key, value in env.items():
240-
if any(char in value for char in (' ', '"', "&", "|", "<", ">", "^")):
240+
if any(char in value for char in (" ", '"', "&", "|", "<", ">", "^")):
241241
escaped = value.replace('"', '""')
242242
parts.append(f'set "{key}={escaped}"')
243243
else:
244244
parts.append(f"set {key}={value}")
245245
if command.lower().endswith(".cmd"):
246246
tail = f'call "{command}"'
247-
elif any(char in command for char in (' ', "&", "|", "<", ">")):
247+
elif any(char in command for char in (" ", "&", "|", "<", ">")):
248248
tail = f'"{command}"'
249249
else:
250250
tail = command
@@ -287,8 +287,7 @@ def _windows_wrapper_env_lines(env: dict[str, str]) -> list[str]:
287287
if value == _WORKSPACE_FOLDER_TEMPLATE and key == CYT_WORKSPACE_ENV:
288288
for agent_var in _AGENT_WORKSPACE_ENV_VARS:
289289
lines.append(
290-
f'if not defined {key} if defined {agent_var} '
291-
f'set "{key}=!{agent_var}!"',
290+
f'if not defined {key} if defined {agent_var} set "{key}=!{agent_var}!"',
292291
)
293292
continue
294293
escaped = value.replace("%", "%%")

‎src/cyt/hook/setup_wizard.py‎

Lines changed: 44 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import copy
66
import json
7-
import os
87
import sys
98
from collections.abc import Iterator
109
from pathlib import Path
@@ -47,6 +46,7 @@
4746
prefix_command_env,
4847
remove_windows_hook_wrappers,
4948
)
49+
from cyt.hook.install_scope import CytInstallScope
5050
from cyt.launch.inject_via_prompt import ensure_hook_inject_via
5151
from cyt.mcpc.readiness import report_mcpc_hook_readiness
5252
from cyt.platform.compat import is_windows
@@ -873,13 +873,21 @@ def _is_legacy_cyt_hook_stdin_command(command: str) -> bool:
873873
)
874874

875875

876+
def _command_invokes_cyt_client(command: str) -> bool:
877+
normalized = command.strip()
878+
if normalized == CYT_CLIENT_COMMAND or normalized.endswith(f" {CYT_CLIENT_COMMAND}"):
879+
return True
880+
parts = normalized.split()
881+
return bool(parts) and Path(parts[-1]).name == CYT_CLIENT_COMMAND
882+
883+
876884
def _is_cyt_hook_command(command: object) -> bool:
877885
if not isinstance(command, str):
878886
return False
879887
normalized = command.strip()
880888
if is_windows_hook_wrapper_command(normalized):
881889
return True
882-
if normalized == CYT_CLIENT_COMMAND or normalized.endswith(f" {CYT_CLIENT_COMMAND}"):
890+
if _command_invokes_cyt_client(normalized):
883891
return True
884892
if is_dev_cyt_hook_command(normalized):
885893
return True
@@ -2526,27 +2534,12 @@ def _finish_hook_setup(
25262534
_print_hook_uninstall_instructions()
25272535

25282536

2529-
def run_hook_setup(
2537+
def _prepare_hook_setup_workspace(
25302538
*,
2531-
config_path: Path | None = None,
2532-
agents: list[HookAgentName] | None = None,
2533-
prevent_hallucinations: bool = False,
2534-
workspace: Path | None = None,
2535-
) -> None:
2536-
"""Install CYT agent hooks and ensure runtime credentials."""
2537-
selected_agents = _resolve_hook_setup_agents(agents)
2538-
if len(selected_agents) == 1:
2539-
print(f"CYT hook setup ({selected_agents[0]})\n")
2540-
else:
2541-
print("CYT hook setup\n")
2542-
2543-
resolved_config_path = resolve_setup_config_path(config_path)
2544-
from cyt.migrations.migrate import (
2545-
ensure_config_file_current,
2546-
ensure_workspace_config_current,
2547-
)
2548-
2549-
ensure_config_file_current(resolved_config_path, scope="user")
2539+
workspace: Path | None,
2540+
hook_agent: str,
2541+
selected_agents: list[HookAgentName],
2542+
) -> tuple[Any, Path | None]:
25502543
from cyt.hook.workspace_resolution import (
25512544
WorkspaceResolutionConflictError,
25522545
ensure_cyt_mcp_dev_wrapper,
@@ -2556,8 +2549,8 @@ def run_hook_setup(
25562549
print_hook_setup_workspace_report,
25572550
resolve_hook_setup_workspace,
25582551
)
2552+
from cyt.migrations.migrate import ensure_workspace_config_current
25592553

2560-
hook_agent = selected_agents[0] if len(selected_agents) == 1 else "cursor"
25612554
for agent in selected_agents:
25622555
ensure_cyt_uv_wrapper_scripts(agent)
25632556
ensure_cyt_mcp_dev_wrapper(agent)
@@ -2583,6 +2576,34 @@ def run_hook_setup(
25832576
f"Updated {settings_path} with terminal.integrated.env "
25842577
f"CYT_WORKSPACE (Windows/Linux/macOS)",
25852578
)
2579+
return hook_workspace_resolution, consumer_root
2580+
2581+
2582+
def run_hook_setup(
2583+
*,
2584+
config_path: Path | None = None,
2585+
agents: list[HookAgentName] | None = None,
2586+
prevent_hallucinations: bool = False,
2587+
workspace: Path | None = None,
2588+
) -> None:
2589+
"""Install CYT agent hooks and ensure runtime credentials."""
2590+
selected_agents = _resolve_hook_setup_agents(agents)
2591+
if len(selected_agents) == 1:
2592+
print(f"CYT hook setup ({selected_agents[0]})\n")
2593+
else:
2594+
print("CYT hook setup\n")
2595+
2596+
resolved_config_path = resolve_setup_config_path(config_path)
2597+
from cyt.migrations.migrate import ensure_config_file_current
2598+
2599+
ensure_config_file_current(resolved_config_path, scope="user")
2600+
2601+
hook_agent = selected_agents[0] if len(selected_agents) == 1 else "cursor"
2602+
hook_workspace_resolution, consumer_root = _prepare_hook_setup_workspace(
2603+
workspace=workspace,
2604+
hook_agent=hook_agent,
2605+
selected_agents=selected_agents,
2606+
)
25862607
from cyt.hook.install_scope import CytInstallScope
25872608
from cyt.hook.workspace_resolution import hook_setup_mcp_workspace_root
25882609

‎src/cyt/hook/workspace_config.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,10 @@ def set_hook_workspace_in_config(
7373
if workspace is None:
7474
merged.pop(HOOK_WORKSPACE_CONFIG_KEY, None)
7575
return merged
76-
from cyt.hook.workspace_resolution import require_absolute_workspace_dir
76+
from cyt.hook.workspace_resolution import resolve_absolute_workspace_path
7777

7878
merged[HOOK_WORKSPACE_CONFIG_KEY] = str(
79-
require_absolute_workspace_dir(workspace, label="hook workspace"),
79+
resolve_absolute_workspace_path(workspace, label="hook workspace"),
8080
)
8181
return merged
8282

0 commit comments

Comments
 (0)