diff --git a/pyproject.toml b/pyproject.toml index e5f1df5..ac07ac5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ name = "weco" authors = [{ name = "Weco AI Team", email = "contact@weco.ai" }] description = "Documentation for `weco`, a CLI for using Weco AI's code optimizer." readme = "README.md" -version = "0.3.10" +version = "0.3.11" license = { file = "LICENSE" } requires-python = ">=3.8" dependencies = [ diff --git a/weco/cli.py b/weco/cli.py index b8f1bee..80cbf10 100644 --- a/weco/cli.py +++ b/weco/cli.py @@ -185,11 +185,30 @@ def _parse_credit_amount(value: str) -> float: ) +def _add_setup_source_args(parser: argparse.ArgumentParser) -> None: + """Add common source arguments to a setup subparser.""" + source_group = parser.add_mutually_exclusive_group() + source_group.add_argument( + "--local", type=str, metavar="PATH", help="Use a local weco-skill directory (creates symlink for development)" + ) + source_group.add_argument("--repo", type=str, metavar="URL", help="Use a different git repo URL (for forks or testing)") + parser.add_argument( + "--ref", + type=str, + metavar="REF", + help="Checkout a specific branch, tag, or commit hash (used with git clone, not --local)", + ) + + def configure_setup_parser(setup_parser: argparse.ArgumentParser) -> None: """Configure the setup command parser and its subcommands.""" setup_subparsers = setup_parser.add_subparsers(dest="tool", help="AI tool to set up") - setup_subparsers.add_parser("claude-code", help="Set up Weco skill for Claude Code") - setup_subparsers.add_parser("cursor", help="Set up Weco rules for Cursor") + + claude_parser = setup_subparsers.add_parser("claude-code", help="Set up Weco skill for Claude Code") + _add_setup_source_args(claude_parser) + + cursor_parser = setup_subparsers.add_parser("cursor", help="Set up Weco rules for Cursor") + _add_setup_source_args(cursor_parser) def configure_resume_parser(resume_parser: argparse.ArgumentParser) -> None: diff --git a/weco/git.py b/weco/git.py new file mode 100644 index 0000000..15d6eb3 --- /dev/null +++ b/weco/git.py @@ -0,0 +1,121 @@ +# weco/git.py +""" +Git utilities for command execution and validation. +""" + +import pathlib +import shutil +import subprocess + + +class GitError(Exception): + """Raised when a git command fails.""" + + def __init__(self, message: str, stderr: str = ""): + super().__init__(message) + self.stderr = stderr + + +class GitNotFoundError(Exception): + """Raised when git is not available on the system.""" + + pass + + +def is_available() -> bool: + """Check if git is available on the system.""" + return shutil.which("git") is not None + + +def is_repo(path: pathlib.Path) -> bool: + """Check if a directory is a git repository.""" + return (path / ".git").is_dir() + + +def validate_ref(ref: str) -> None: + """ + Validate a git ref to prevent option injection. + + Raises: + ValueError: If ref could be interpreted as a git option. + """ + if ref.startswith("-"): + raise ValueError(f"Invalid git ref: {ref!r} (cannot start with '-')") + + +def validate_repo_url(url: str) -> None: + """ + Validate a git repository URL. + + Raises: + ValueError: If URL doesn't match expected patterns. + """ + valid_prefixes = ("git@", "https://", "http://", "ssh://", "file://", "/", "./", "../") + if not any(url.startswith(prefix) for prefix in valid_prefixes): + raise ValueError(f"Invalid repository URL: {url!r}") + + +def run(*args: str, cwd: pathlib.Path | None = None, error_msg: str = "Git command failed") -> subprocess.CompletedProcess: + """ + Run a git command and return the result. + + Args: + *args: Git subcommand and arguments (e.g., "clone", url, path). + Do NOT include "git" — it's prepended automatically. + cwd: Working directory for the command. + error_msg: Message to include in exception on failure. + + Raises: + GitError: If the command fails or returns non-zero. + """ + cmd = ["git", *args] + try: + result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) + except Exception as e: + raise GitError(f"{error_msg}: {e}") from e + + if result.returncode != 0: + raise GitError(error_msg, result.stderr) + return result + + +def clone(repo_url: str, dest: pathlib.Path, ref: str | None = None) -> None: + """ + Clone a git repository. + + Args: + repo_url: The repository URL to clone. + dest: Destination directory. + ref: Optional branch, tag, or commit to checkout after cloning. + + Raises: + GitError: If clone or checkout fails. + """ + run("clone", repo_url, str(dest), error_msg="Failed to clone repository") + if ref: + run("checkout", ref, cwd=dest, error_msg=f"Failed to checkout '{ref}'") + + +def pull(repo_path: pathlib.Path) -> None: + """ + Pull latest changes in a git repository. + + Raises: + GitError: If pull fails. + """ + run("pull", cwd=repo_path, error_msg="Failed to pull repository") + + +def fetch_and_checkout(repo_path: pathlib.Path, ref: str) -> None: + """ + Fetch all remotes and checkout a specific ref. + + Args: + repo_path: Path to the git repository. + ref: Branch, tag, or commit to checkout. + + Raises: + GitError: If fetch or checkout fails. + """ + run("fetch", "--all", cwd=repo_path, error_msg="Failed to fetch from repository") + run("checkout", ref, cwd=repo_path, error_msg=f"Failed to checkout '{ref}'") diff --git a/weco/setup.py b/weco/setup.py index 97d4aa8..7aa72f8 100644 --- a/weco/setup.py +++ b/weco/setup.py @@ -4,18 +4,43 @@ """ import pathlib -import shutil -import subprocess +import sys + from rich.console import Console from rich.prompt import Confirm +from . import git +from .utils import copy_directory, copy_file, read_from_path, remove_directory, write_to_path + + +# ============================================================================= +# Exceptions +# ============================================================================= + + +class SetupError(Exception): + """Base exception for setup failures.""" + + pass + + +class InvalidLocalRepoError(SetupError): + """Raised when a local path is not a valid skill repository.""" + + pass + + +# ============================================================================= +# Path constants +# ============================================================================= + # Claude Code paths CLAUDE_DIR = pathlib.Path.home() / ".claude" CLAUDE_SKILLS_DIR = CLAUDE_DIR / "skills" -CLAUDE_MD_PATH = CLAUDE_DIR / "CLAUDE.md" WECO_SKILL_DIR = CLAUDE_SKILLS_DIR / "weco" WECO_SKILL_REPO = "git@github.com:WecoAI/weco-skill.git" -WECO_RULES_SNIPPET_PATH = WECO_SKILL_DIR / "rules-snippet.md" +WECO_CLAUDE_SNIPPET_PATH = WECO_SKILL_DIR / "snippets" / "claude.md" +WECO_CLAUDE_MD_PATH = WECO_SKILL_DIR / "CLAUDE.md" # Cursor paths CURSOR_DIR = pathlib.Path.home() / ".cursor" @@ -23,345 +48,248 @@ CURSOR_WECO_RULES_PATH = CURSOR_RULES_DIR / "weco.mdc" CURSOR_SKILLS_DIR = CURSOR_DIR / "skills" CURSOR_WECO_SKILL_DIR = CURSOR_SKILLS_DIR / "weco" -CURSOR_RULES_SNIPPET_PATH = CURSOR_WECO_SKILL_DIR / "rules-snippet.md" +CURSOR_RULES_SNIPPET_PATH = CURSOR_WECO_SKILL_DIR / "snippets" / "cursor.md" -# Delimiters for agent rules files - allows automatic updates -WECO_RULES_BEGIN_DELIMITER = "" -WECO_RULES_END_DELIMITER = "" +# Files/directories to skip when copying local repos +_COPY_IGNORE_PATTERNS = {".git", "__pycache__", ".DS_Store"} -def is_git_available() -> bool: - """Check if git is available on the system.""" - return shutil.which("git") is not None +# ============================================================================= +# Domain helpers +# ============================================================================= -def read_rules_snippet(snippet_path: pathlib.Path, console: Console) -> str | None: - """ - Read the rules snippet from the cloned skill repository. +def generate_cursor_mdc_content(snippet_content: str) -> str: + """Generate Cursor MDC file content with YAML frontmatter.""" + return f"""--- +description: Weco code optimization skill. Weco automates optimization by iteratively refining code against any metric you define — invoke for speed, accuracy, latency, cost, or anything else you can measure. +alwaysApply: true +--- +{snippet_content} +""" - Args: - snippet_path: Path to the rules-snippet.md file. - console: Rich console for output. - Returns: - The snippet content wrapped in delimiters, or None if not found. +def validate_local_skill_repo(local_path: pathlib.Path) -> None: """ - if not snippet_path.exists(): - console.print(f"[bold red]Error:[/] Snippet file not found at {snippet_path}") - return None + Validate that a local path is a valid weco-skill repository. - try: - snippet_content = snippet_path.read_text().strip() - return f"\n{WECO_RULES_BEGIN_DELIMITER}\n{snippet_content}\n{WECO_RULES_END_DELIMITER}\n" - except Exception as e: - console.print(f"[bold red]Error:[/] Failed to read snippet file: {e}") - return None - - -def read_rules_snippet_raw(snippet_path: pathlib.Path, console: Console) -> str | None: + Raises: + InvalidLocalRepoError: If validation fails. """ - Read the raw rules snippet from the cloned skill repository (without delimiters). + if not local_path.exists(): + raise InvalidLocalRepoError(f"Local path does not exist: {local_path}") + if not local_path.is_dir(): + raise InvalidLocalRepoError(f"Local path is not a directory: {local_path}") + if not (local_path / "SKILL.md").exists(): + raise InvalidLocalRepoError( + f"Local path does not appear to be a weco-skill repository (expected SKILL.md at {local_path / 'SKILL.md'})" + ) - Args: - snippet_path: Path to the rules-snippet.md file. - console: Rich console for output. - Returns: - The raw snippet content, or None if not found. - """ - if not snippet_path.exists(): - console.print(f"[bold red]Error:[/] Snippet file not found at {snippet_path}") - return None +# ============================================================================= +# Installation functions +# ============================================================================= - try: - return snippet_path.read_text().strip() - except Exception as e: - console.print(f"[bold red]Error:[/] Failed to read snippet file: {e}") - return None +def install_skill_from_git(skill_dir: pathlib.Path, console: Console, repo_url: str | None, ref: str | None) -> None: + """ + Clone or update skill from git. -def generate_cursor_mdc_content(snippet_content: str) -> str: + Raises: + git.GitNotFoundError: If git is not available. + git.GitError: If git operations fail. """ - Generate Cursor MDC file content with YAML frontmatter. + if not git.is_available(): + raise git.GitNotFoundError("git is not installed or not in PATH") - Args: - snippet_content: The raw rules snippet content. + skill_dir.parent.mkdir(parents=True, exist_ok=True) - Returns: - MDC formatted content with frontmatter. - """ - return f"""--- -description: Weco code optimization skill - invoke for speed, accuracy, loss optimization -alwaysApply: true ---- -{snippet_content} -""" + if skill_dir.exists(): + if git.is_repo(skill_dir): + console.print(f"[cyan]Updating existing skill at {skill_dir}...[/]") + if ref: + git.fetch_and_checkout(skill_dir, ref) + console.print(f"[green]Checked out {ref}.[/]") + else: + git.pull(skill_dir) + console.print("[green]Skill updated successfully.[/]") + return + # Not a git repo — clear and re-clone + console.print(f"[cyan]Removing existing directory at {skill_dir}...[/]") + remove_directory(skill_dir) -def is_git_repo(path: pathlib.Path) -> bool: - """Check if a directory is a git repository.""" - return (path / ".git").is_dir() + console.print(f"[cyan]Cloning Weco skill to {skill_dir}...[/]") + git.clone(repo_url or WECO_SKILL_REPO, skill_dir, ref=ref) + if ref: + console.print(f"[green]Cloned and checked out {ref}.[/]") + else: + console.print("[green]Skill cloned successfully.[/]") -def clone_skill_repo(skill_dir: pathlib.Path, console: Console) -> bool: +def install_skill_from_local(skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path) -> None: """ - Clone or update the weco-skill repository to the specified directory. + Copy skill from local path. - Args: - skill_dir: The directory to clone/update the skill repository in. - console: Rich console for output. - - Returns: - True if successful, False otherwise. + Raises: + InvalidLocalRepoError: If local path is invalid. + OSError: If copy fails. """ - if not is_git_available(): - console.print("[bold red]Error:[/] git is not installed or not in PATH.") - console.print("Please install git and try again.") - return False + validate_local_skill_repo(local_path) - # Ensure the parent skills directory exists skill_dir.parent.mkdir(parents=True, exist_ok=True) if skill_dir.exists(): - if is_git_repo(skill_dir): - # Directory exists and is a git repo - pull latest - console.print(f"[cyan]Updating existing skill at {skill_dir}...[/]") - try: - result = subprocess.run(["git", "pull"], cwd=skill_dir, capture_output=True, text=True) - if result.returncode != 0: - console.print("[bold red]Error:[/] Failed to update skill repository.") - console.print(f"[dim]{result.stderr}[/]") - return False - console.print("[green]Skill updated successfully.[/]") - return True - except Exception as e: - console.print(f"[bold red]Error:[/] Failed to update skill repository: {e}") - return False - else: - # Directory exists but is not a git repo - console.print(f"[bold red]Error:[/] Directory {skill_dir} exists but is not a git repository.") - console.print("Please remove it manually and try again.") - return False - else: - # Clone the repository - console.print(f"[cyan]Cloning Weco skill to {skill_dir}...[/]") - try: - result = subprocess.run(["git", "clone", WECO_SKILL_REPO, str(skill_dir)], capture_output=True, text=True) - if result.returncode != 0: - console.print("[bold red]Error:[/] Failed to clone skill repository.") - console.print(f"[dim]{result.stderr}[/]") - return False - console.print("[green]Skill cloned successfully.[/]") - return True - except Exception as e: - console.print(f"[bold red]Error:[/] Failed to clone skill repository: {e}") - return False - - -def update_agent_rules_file( - rules_file: pathlib.Path, snippet_path: pathlib.Path, skill_dir: pathlib.Path, console: Console -) -> bool: - """ - Update an agent's rules file with the Weco skill reference. + console.print(f"[cyan]Removing existing directory at {skill_dir}...[/]") + remove_directory(skill_dir) - Uses delimiters to allow automatic updates if the snippet changes. + copy_directory(local_path, skill_dir, ignore_patterns=_COPY_IGNORE_PATTERNS) + console.print(f"[green]Copied local repo from: {local_path}[/]") - Args: - rules_file: Path to the agent's rules file (e.g., ~/.claude/CLAUDE.md) - snippet_path: Path to the rules-snippet.md file. - skill_dir: Path to the skill directory (for user messaging). - console: Rich console for output. - Returns: - True if updated or user declined, False on error. - """ - import re +def install_skill( + skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path | None, repo_url: str | None, ref: str | None +) -> None: + """Install skill by copying from local path or cloning from git.""" + if local_path: + if ref: + console.print("[bold yellow]Warning:[/] --ref is ignored when using --local") + install_skill_from_local(skill_dir, console, local_path) + else: + install_skill_from_git(skill_dir, console, repo_url, ref) - rules_file_name = rules_file.name - # Read the snippet from the cloned skill repo - snippet_section = read_rules_snippet(snippet_path, console) - if snippet_section is None: - return False +# ============================================================================= +# Setup commands +# ============================================================================= - # Check if the section already exists with delimiters - existing_content = "" - has_existing_section = False - if rules_file.exists(): - try: - existing_content = rules_file.read_text() - has_existing_section = ( - WECO_RULES_BEGIN_DELIMITER in existing_content and WECO_RULES_END_DELIMITER in existing_content - ) - except Exception as e: - console.print(f"[bold yellow]Warning:[/] Could not read {rules_file_name}: {e}") - - # Determine what action to take - if has_existing_section: - # Check if content is already up to date - pattern = re.escape(WECO_RULES_BEGIN_DELIMITER) + r".*?" + re.escape(WECO_RULES_END_DELIMITER) - match = re.search(pattern, existing_content, re.DOTALL) - if match and match.group(0).strip() == snippet_section.strip(): - console.print(f"[dim]{rules_file_name} already contains the latest Weco rules.[/]") - return True - - # Prompt for update - console.print(f"\n[bold yellow]{rules_file_name} Update[/]") - console.print(f"The Weco rules in your {rules_file_name} can be updated to the latest version.") - should_update = Confirm.ask("Would you like to update the Weco section?", default=True) - elif rules_file.exists(): - console.print(f"\n[bold yellow]{rules_file_name} Update[/]") - console.print(f"To enable automatic skill discovery, we can add Weco rules to your {rules_file_name} file.") - should_update = Confirm.ask(f"Would you like to update your {rules_file_name}?", default=True) - else: - console.print(f"\n[bold yellow]{rules_file_name} Creation[/]") - console.print(f"To enable automatic skill discovery, we can create a {rules_file_name} file.") - should_update = Confirm.ask(f"Would you like to create {rules_file_name}?", default=True) - - if not should_update: - console.print(f"\n[yellow]Skipping {rules_file_name} update.[/]") - console.print( - "[dim]The Weco skill has been installed but may not be discovered automatically.\n" - f"You can manually reference it at {skill_dir}[/]" - ) - return True - # Update or create the file - try: - rules_file.parent.mkdir(parents=True, exist_ok=True) - - if has_existing_section: - # Replace existing section between delimiters - pattern = re.escape(WECO_RULES_BEGIN_DELIMITER) + r".*?" + re.escape(WECO_RULES_END_DELIMITER) - new_content = re.sub(pattern, snippet_section.strip(), existing_content, flags=re.DOTALL) - rules_file.write_text(new_content) - console.print(f"[green]{rules_file_name} updated successfully.[/]") - elif rules_file.exists(): - # Append to existing file - with open(rules_file, "a") as f: - f.write(snippet_section) - console.print(f"[green]{rules_file_name} updated successfully.[/]") - else: - # Create new file - with open(rules_file, "w") as f: - f.write(snippet_section.lstrip()) - console.print(f"[green]{rules_file_name} created successfully.[/]") - return True - except Exception as e: - console.print(f"[bold red]Error:[/] Failed to update {rules_file_name}: {e}") - return False - - -def setup_claude_code(console: Console) -> bool: - """ - Set up Weco skill for Claude Code. - - Returns: - True if setup was successful, False otherwise. - """ +def setup_claude_code( + console: Console, local_path: pathlib.Path | None = None, repo_url: str | None = None, ref: str | None = None +) -> None: + """Set up Weco skill for Claude Code.""" console.print("[bold blue]Setting up Weco for Claude Code...[/]\n") - # Step 1: Clone or update the skill repository - if not clone_skill_repo(WECO_SKILL_DIR, console): - return False + # Claude Code setup is intentionally "skill-centric": + # - Install the skill into Claude's skills directory. + # - `CLAUDE.md` lives *inside* that installed skill folder, so configuration is just + # copying a file within the skill directory. + # - There is no separate global config file to reconcile or prompt before overwriting. + install_skill(WECO_SKILL_DIR, console, local_path, repo_url, ref) - # Step 2: Update CLAUDE.md - if not update_agent_rules_file(CLAUDE_MD_PATH, WECO_RULES_SNIPPET_PATH, WECO_SKILL_DIR, console): - return False + # Copy snippets/claude.md to CLAUDE.md (skip for local - user manages their own) + if not local_path: + copy_file(WECO_CLAUDE_SNIPPET_PATH, WECO_CLAUDE_MD_PATH) + console.print("[green]CLAUDE.md installed to skill directory.[/]") console.print("\n[bold green]Setup complete![/]") + if local_path: + console.print(f"[dim]Skill copied from: {local_path}[/]") console.print(f"[dim]Skill installed at: {WECO_SKILL_DIR}[/]") - return True -def setup_cursor(console: Console) -> bool: - """ - Set up Weco rules for Cursor. - - Creates a weco.mdc file in ~/.cursor/rules/ with the Weco optimization rules. - - Returns: - True if setup was successful, False otherwise. - """ +def setup_cursor( + console: Console, local_path: pathlib.Path | None = None, repo_url: str | None = None, ref: str | None = None +) -> None: + """Set up Weco rules for Cursor.""" console.print("[bold blue]Setting up Weco for Cursor...[/]\n") - # Step 1: Clone or update the skill repository to Cursor's path - if not clone_skill_repo(CURSOR_WECO_SKILL_DIR, console): - return False - - # Step 2: Read the rules snippet - snippet_content = read_rules_snippet_raw(CURSOR_RULES_SNIPPET_PATH, console) - if snippet_content is None: - return False - - # Step 3: Check if weco.mdc already exists + # Cursor setup is intentionally "editor-config-centric": + # - Install/copy the skill into Cursor's skills directory (so we can read snippets). + # - The behavior change is controlled by `~/.cursor/rules/weco.mdc`, which is *global* + # editor state (not part of the installed skill folder). + # - Because users may have customized that file, we: + # 1) compute desired content from the snippet + # 2) check if it is already up to date + # 3) prompt before creating/updating it + install_skill(CURSOR_WECO_SKILL_DIR, console, local_path, repo_url, ref) + + snippet_content = read_from_path(CURSOR_RULES_SNIPPET_PATH) + mdc_content = generate_cursor_mdc_content(snippet_content.strip()) + + # Check if already up to date + existing_content = None if CURSOR_WECO_RULES_PATH.exists(): try: - existing_content = CURSOR_WECO_RULES_PATH.read_text() - new_content = generate_cursor_mdc_content(snippet_content) - if existing_content.strip() == new_content.strip(): - console.print("[dim]weco.mdc already contains the latest Weco rules.[/]") - console.print("\n[bold green]Setup complete![/]") - console.print(f"[dim]Rules file at: {CURSOR_WECO_RULES_PATH}[/]") - return True - except Exception as e: - console.print(f"[bold yellow]Warning:[/] Could not read existing weco.mdc: {e}") - + existing_content = read_from_path(CURSOR_WECO_RULES_PATH) + except Exception: + pass + + if existing_content is not None and existing_content.strip() == mdc_content.strip(): + console.print("[dim]weco.mdc already contains the latest Weco rules.[/]") + console.print("\n[bold green]Setup complete![/]") + console.print(f"[dim]Rules file at: {CURSOR_WECO_RULES_PATH}[/]") + return + + # Prompt user for creation/update + if existing_content is not None: console.print("\n[bold yellow]weco.mdc Update[/]") console.print("The Weco rules file can be updated to the latest version.") - should_update = Confirm.ask("Would you like to update weco.mdc?", default=True) + if not Confirm.ask("Would you like to update weco.mdc?", default=True): + console.print("\n[yellow]Skipping weco.mdc update.[/]") + console.print(f"[dim]Skill installed but rules not configured. Create manually at {CURSOR_WECO_RULES_PATH}[/]") + return else: console.print("\n[bold yellow]weco.mdc Creation[/]") console.print("To enable Weco optimization rules, we can create a weco.mdc file.") - should_update = Confirm.ask("Would you like to create weco.mdc?", default=True) - - if not should_update: - console.print("\n[yellow]Skipping weco.mdc update.[/]") - console.print( - "[dim]The Weco skill has been installed but rules are not configured.\n" - f"You can manually create the rules file at {CURSOR_WECO_RULES_PATH}[/]" - ) - return True + if not Confirm.ask("Would you like to create weco.mdc?", default=True): + console.print("\n[yellow]Skipping weco.mdc creation.[/]") + console.print(f"[dim]Skill installed but rules not configured. Create manually at {CURSOR_WECO_RULES_PATH}[/]") + return - # Step 4: Write the MDC file - try: - CURSOR_RULES_DIR.mkdir(parents=True, exist_ok=True) - mdc_content = generate_cursor_mdc_content(snippet_content) - CURSOR_WECO_RULES_PATH.write_text(mdc_content) - console.print("[green]weco.mdc created successfully.[/]") - except Exception as e: - console.print(f"[bold red]Error:[/] Failed to write weco.mdc: {e}") - return False + write_to_path(CURSOR_WECO_RULES_PATH, mdc_content, mkdir=True) + console.print("[green]weco.mdc created successfully.[/]") console.print("\n[bold green]Setup complete![/]") + if local_path: + console.print(f"[dim]Skill copied from: {local_path}[/]") + console.print(f"[dim]Skill installed at: {CURSOR_WECO_SKILL_DIR}[/]") console.print(f"[dim]Rules file at: {CURSOR_WECO_RULES_PATH}[/]") - return True + + +# ============================================================================= +# CLI entry point +# ============================================================================= + +SETUP_HANDLERS = {"claude-code": setup_claude_code, "cursor": setup_cursor} def handle_setup_command(args, console: Console) -> None: """Handle the setup command with its subcommands.""" - if args.tool == "claude-code": - success = setup_claude_code(console) - if not success: - import sys - - sys.exit(1) - elif args.tool == "cursor": - success = setup_cursor(console) - if not success: - import sys - - sys.exit(1) - elif args.tool is None: + available_tools = ", ".join(SETUP_HANDLERS) + + if args.tool is None: console.print("[bold red]Error:[/] Please specify a tool to set up.") - console.print("Available tools: claude-code, cursor") + console.print(f"Available tools: {available_tools}") console.print("\nUsage: weco setup ") - import sys - sys.exit(1) - else: + + handler = SETUP_HANDLERS.get(args.tool) + if handler is None: console.print(f"[bold red]Error:[/] Unknown tool: {args.tool}") - console.print("Available tools: claude-code, cursor") - import sys + console.print(f"Available tools: {available_tools}") + sys.exit(1) + + # Validate and extract args + repo_url = getattr(args, "repo", None) + ref = getattr(args, "ref", None) + local_path = None + if hasattr(args, "local") and args.local: + local_path = pathlib.Path(args.local).expanduser().resolve() + try: + if repo_url: + git.validate_repo_url(repo_url) + if ref: + git.validate_ref(ref) + + handler(console, local_path=local_path, repo_url=repo_url, ref=ref) + + except git.GitError as e: + console.print(f"[bold red]Error:[/] {e}") + if e.stderr: + console.print(f"[dim]{e.stderr}[/]") + sys.exit(1) + except (SetupError, git.GitNotFoundError, FileNotFoundError, OSError, ValueError) as e: + console.print(f"[bold red]Error:[/] {e}") sys.exit(1) diff --git a/weco/utils.py b/weco/utils.py index 539e480..179ef00 100644 --- a/weco/utils.py +++ b/weco/utils.py @@ -1,5 +1,6 @@ from typing import Any, Dict, List, Tuple, Union import json +import shutil import time import subprocess import psutil @@ -63,8 +64,19 @@ def read_from_path(fp: pathlib.Path, is_json: bool = False) -> Union[str, Dict[s return f.read() -def write_to_path(fp: pathlib.Path, content: Union[str, Dict[str, Any]], is_json: bool = False) -> None: - """Write content to a file path, optionally as JSON.""" +def write_to_path(fp: pathlib.Path, content: Union[str, Dict[str, Any]], is_json: bool = False, mkdir: bool = False) -> None: + """ + Write content to a file path, optionally as JSON. + + Args: + fp: File path to write to. + content: Content to write (string or dict for JSON). + is_json: If True, write as JSON. + mkdir: If True, create parent directories if they don't exist. + """ + if mkdir: + fp.parent.mkdir(parents=True, exist_ok=True) + with fp.open("w", encoding="utf-8") as f: if is_json: json.dump(content, f, indent=4) @@ -74,6 +86,60 @@ def write_to_path(fp: pathlib.Path, content: Union[str, Dict[str, Any]], is_json raise TypeError("Error writing to file. Please verify the file path and try again.") +def copy_file(src: pathlib.Path, dest: pathlib.Path, mkdir: bool = False) -> None: + """ + Copy a single file. + + Args: + src: Source file path. + dest: Destination file path. + mkdir: If True, create parent directories if they don't exist. + + Raises: + FileNotFoundError: If source doesn't exist. + OSError: If copy fails. + """ + if not src.exists(): + raise FileNotFoundError(f"Source file not found: {src}") + if mkdir: + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(src, dest) + + +def copy_directory(src: pathlib.Path, dest: pathlib.Path, ignore_patterns: set[str] | None = None) -> None: + """ + Copy a directory tree. + + Args: + src: Source directory path. + dest: Destination directory path. + ignore_patterns: Optional set of file/directory names to skip. + + Raises: + FileNotFoundError: If source doesn't exist. + OSError: If copy fails. + """ + if not src.exists(): + raise FileNotFoundError(f"Source directory not found: {src}") + + def ignore_func(_: str, files: list[str]) -> list[str]: + if not ignore_patterns: + return [] + return [f for f in files if f in ignore_patterns] + + shutil.copytree(src, dest, ignore=ignore_func) + + +def remove_directory(path: pathlib.Path) -> None: + """ + Remove a directory and all its contents. + + Does nothing if the directory doesn't exist. + """ + if path.exists(): + shutil.rmtree(path) + + # Visualization helper functions def smooth_update( live: Live, layout: Layout, sections_to_update: List[Tuple[str, Panel]], transition_delay: float = 0.05