Private
Public Access
0
0
Files
manual_slop/src/external_editor.py
T
ed 91a612887c Merge origin/tier2/module_taxonomy_refactor_20260627: bring in v2 SHIPPED work
Per post_module_taxonomy_de_cruft_20260627 Phase 0 prerequisite.
Master is at 6344b49f (pre-merge of v2 SHIPPED). This merge brings in
the 18 v2 SHIPPED commits that define the destination modules
(src.mma, src/project.py, src/project_files.py, src.tool_presets,
src.tool_bias, src.external_editor, src.personas,
src.workspace_manager, src.mcp_client) needed by the Phase 2
consumer migration in commit 8f11340b.

Conflicts resolved (all were import-block re-orderings between my
migration's update and v2 SHIPPED's update of the same files):
 - src/external_editor.py: took v2 SHIPPED version (class definitions
                                    + the no-alias import pattern)
 - src/personas.py: took v2 SHIPPED version
 - src/tool_bias.py: took v2 SHIPPED version
 - src/tool_presets.py: took v2 SHIPPED version
 - src/workspace_manager.py: took v2 SHIPPED version
 - src/ai_client.py: took v2 SHIPPED version (removes the 'as _FIC'
                              alias; uses 'from src.project_files import
                              FileItem' directly per the v2 SHIPPED style)
 - conductor/tracks/module_taxonomy_refactor_20260627/spec.md: took
                              HEAD version (my Phase 1 VC2 + VC10
                              corrections; the v2 SHIPPED version was
                              the pre-correction spec)
2026-06-26 13:51:05 -04:00

202 lines
7.6 KiB
Python

"""External Editor Launcher - Opens files in external text editors for diff viewing."""
from __future__ import annotations
import os
import subprocess
import tempfile
# TODO(Ed): Eliminate these?
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, List, Dict, Any
from src.result_types import ErrorInfo, ErrorKind, Result
from src.type_aliases import Metadata
@dataclass
class TextEditorConfig:
name: str = ""
path: str = ""
diff_args: List[str] = field(default_factory=list)
def to_dict(self) -> Metadata:
return {
"name": self.name,
"path": self.path,
"diff_args": self.diff_args,
}
@classmethod
def from_dict(cls, data: Metadata) -> "TextEditorConfig":
return cls(
name = data["name"],
path = data["path"],
diff_args = data.get("diff_args", []),
)
@dataclass
class ExternalEditorConfig:
editors: Dict[str, TextEditorConfig] = field(default_factory=dict)
default_editor: Optional[str] = None
def get_default(self) -> TextEditorConfig:
if self.default_editor and self.default_editor in self.editors:
return self.editors[self.default_editor]
if self.editors:
return next(iter(self.editors.values()))
return EMPTY_TEXT_EDITOR_CONFIG
def to_dict(self) -> Metadata:
return {
"editors": {k: v.to_dict() for k, v in self.editors.items()},
"default_editor": self.default_editor,
}
@classmethod
def from_dict(cls, data: Metadata) -> "ExternalEditorConfig":
editors = {}
for name, ed_data in data.get("editors", {}).items():
if isinstance(ed_data, dict): editors[name] = TextEditorConfig.from_dict(ed_data)
elif isinstance(ed_data, str): editors[name] = TextEditorConfig(name=name, path=ed_data)
return cls(editors=editors, default_editor=data.get("default_editor"))
EMPTY_TEXT_EDITOR_CONFIG: TextEditorConfig = TextEditorConfig()
class ExternalEditorLauncher:
def __init__(self, config: ExternalEditorConfig):
"""
[C: src/mcp_client.py:_DDGParser.__init__, src/mcp_client.py:_TextExtractor.__init__]
"""
self.config = config
def get_editor(self, editor_name: Optional[str] = None) -> TextEditorConfig:
"""
[C: tests/test_external_editor.py:TestExternalEditorLauncher.test_get_editor_by_name, tests/test_external_editor.py:TestExternalEditorLauncher.test_get_editor_returns_default, tests/test_external_editor.py:TestExternalEditorLauncher.test_get_editor_unknown_name]
"""
if editor_name:
return self.config.editors.get(editor_name) or EMPTY_TEXT_EDITOR_CONFIG
return self.config.get_default()
def build_diff_command(self, editor: TextEditorConfig, original_path: str, modified_path: str) -> List[str]:
"""
[C: tests/test_external_editor.py:TestExternalEditorLauncher.test_build_diff_command, tests/test_external_editor_gui.py:test_verify_command_format, tests/test_external_editor_gui.py:test_verify_vscode_command_format]
"""
cmd = [editor.path] + editor.diff_args + [original_path, modified_path]
return cmd
def launch_diff_result(self, editor_name: Optional[str], original_path: str, modified_path: str) -> Result[subprocess.Popen]:
"""
[C: src/gui_2.py:App._open_patch_in_external_editor, tests/test_external_editor.py:TestExternalEditorLauncher.test_launch_diff_file_not_found, tests/test_external_editor.py:TestExternalEditorLauncher.test_launch_diff_missing_editor, tests/test_external_editor.py:TestExternalEditorLauncher.test_launch_diff_success]
"""
editor = self.get_editor(editor_name)
if not editor.name or not editor.path:
return Result(data=None, errors=[ErrorInfo(kind=ErrorKind.NOT_FOUND, message=f"No editor configured: {editor_name}", source="external_editor.launch_diff_result")])
cmd = self.build_diff_command(editor, original_path, modified_path)
try:
return Result(data=subprocess.Popen(cmd))
except FileNotFoundError as e:
return Result(data=None, errors=[ErrorInfo(kind=ErrorKind.NOT_FOUND, message=f"Editor binary not found: {cmd[0]}", source="external_editor.launch_diff_result", original=e)])
_cached_vscode_config: Optional[TextEditorConfig] = None
def _find_vscode_in_registry() -> Result[Optional[str]]:
paths = []
errors: list[ErrorInfo] = []
reg_keys = [
r"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
r"HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
r"HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*",
]
for key in reg_keys:
try:
result = subprocess.run(
["powershell", "-Command", f"Get-ItemProperty -Path '{key}' -ErrorAction SilentlyContinue | Where-Object {{ $_.DisplayName -like '*Visual Studio Code*' }} | Select-Object -ExpandProperty InstallLocation"],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.strip().split('\n'):
line = line.strip()
if line and line != "":
exe_path = line.strip() + "\\Code.exe"
if os.path.exists(exe_path):
paths.append(exe_path)
except (OSError, subprocess.SubprocessError, subprocess.TimeoutExpired) as e:
errors.append(ErrorInfo(kind=ErrorKind.INTERNAL, message=str(e), source=f"external_editor._find_vscode_in_registry[{key}]", original=e))
if paths:
return Result(data=paths[0], errors=errors)
return Result(data=None, errors=errors)
def _find_vscode_common_paths() -> str:
candidates = [
r"C:\apps\Microsoft VS Code\Code.exe",
r"C:\Program Files\Microsoft VS Code\Code.exe",
r"C:\Program Files (x86)\Microsoft VS Code\Code.exe",
os.path.expanduser(r"~\AppData\Local\Programs\Microsoft VS Code\Code.exe"),
]
for path in candidates:
if os.path.exists(path):
return path
return ""
def auto_detect_vscode() -> TextEditorConfig:
global _cached_vscode_config
if _cached_vscode_config is not None:
return _cached_vscode_config
vscode_result = _find_vscode_in_registry()
vscode_path = vscode_result.data if vscode_result.ok else ""
if not vscode_path:
vscode_path = _find_vscode_common_paths()
if vscode_path:
_cached_vscode_config = TextEditorConfig(
name="vscode",
path=vscode_path,
diff_args=["--new-window", "--diff"]
)
return _cached_vscode_config
return EMPTY_TEXT_EDITOR_CONFIG
def get_default_launcher(config: Optional[Dict[str, Any]] = None) -> ExternalEditorLauncher:
"""
Caller passes the live config dict (typically app.config from the
AppController). Direct file I/O (the legacy public functions on src.models) is an
architectural smell (bypasses the controller state owner) and is
forbidden by scripts/audit_no_models_config_io.py.
[C: src/gui_2.py:App._open_patch_in_external_editor, src/gui_2.py:App._render_external_editor_panel]
"""
editors_config = config.get("tools", {}).get("text_editors", {}) if config else {}
default_editor = config.get("tools", {}).get("default_editor", {}).get("default_editor") if config else None
ext_config = ExternalEditorConfig.from_dict({
"editors": editors_config,
"default_editor": default_editor,
})
launcher = ExternalEditorLauncher(ext_config)
if not launcher.config.editors:
detected = auto_detect_vscode()
if detected:
launcher.config.editors["vscode"] = detected
launcher.config.default_editor = "vscode"
else:
vscode = launcher.config.editors.get("vscode")
if vscode and "--new-window" not in vscode.diff_args:
vscode.diff_args = ["--new-window", "--diff"]
return launcher
def create_temp_modified_file(content: str) -> str:
"""
[C: src/gui_2.py:App._open_patch_in_external_editor, tests/test_external_editor.py:TestHelperFunctions.test_create_temp_modified_file]
"""
with tempfile.NamedTemporaryFile(mode="w", suffix="_modified", delete=False, encoding="utf-8") as f:
f.write(content)
return f.name