weco 0.3.9__py3-none-any.whl → 0.3.11__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.
weco/cli.py CHANGED
@@ -185,10 +185,30 @@ def configure_credits_parser(credits_parser: argparse.ArgumentParser) -> None:
185
185
  )
186
186
 
187
187
 
188
+ def _add_setup_source_args(parser: argparse.ArgumentParser) -> None:
189
+ """Add common source arguments to a setup subparser."""
190
+ source_group = parser.add_mutually_exclusive_group()
191
+ source_group.add_argument(
192
+ "--local", type=str, metavar="PATH", help="Use a local weco-skill directory (creates symlink for development)"
193
+ )
194
+ source_group.add_argument("--repo", type=str, metavar="URL", help="Use a different git repo URL (for forks or testing)")
195
+ parser.add_argument(
196
+ "--ref",
197
+ type=str,
198
+ metavar="REF",
199
+ help="Checkout a specific branch, tag, or commit hash (used with git clone, not --local)",
200
+ )
201
+
202
+
188
203
  def configure_setup_parser(setup_parser: argparse.ArgumentParser) -> None:
189
204
  """Configure the setup command parser and its subcommands."""
190
205
  setup_subparsers = setup_parser.add_subparsers(dest="tool", help="AI tool to set up")
191
- setup_subparsers.add_parser("claude-code", help="Set up Weco skill for Claude Code")
206
+
207
+ claude_parser = setup_subparsers.add_parser("claude-code", help="Set up Weco skill for Claude Code")
208
+ _add_setup_source_args(claude_parser)
209
+
210
+ cursor_parser = setup_subparsers.add_parser("cursor", help="Set up Weco rules for Cursor")
211
+ _add_setup_source_args(cursor_parser)
192
212
 
193
213
 
194
214
  def configure_resume_parser(resume_parser: argparse.ArgumentParser) -> None:
weco/git.py ADDED
@@ -0,0 +1,121 @@
1
+ # weco/git.py
2
+ """
3
+ Git utilities for command execution and validation.
4
+ """
5
+
6
+ import pathlib
7
+ import shutil
8
+ import subprocess
9
+
10
+
11
+ class GitError(Exception):
12
+ """Raised when a git command fails."""
13
+
14
+ def __init__(self, message: str, stderr: str = ""):
15
+ super().__init__(message)
16
+ self.stderr = stderr
17
+
18
+
19
+ class GitNotFoundError(Exception):
20
+ """Raised when git is not available on the system."""
21
+
22
+ pass
23
+
24
+
25
+ def is_available() -> bool:
26
+ """Check if git is available on the system."""
27
+ return shutil.which("git") is not None
28
+
29
+
30
+ def is_repo(path: pathlib.Path) -> bool:
31
+ """Check if a directory is a git repository."""
32
+ return (path / ".git").is_dir()
33
+
34
+
35
+ def validate_ref(ref: str) -> None:
36
+ """
37
+ Validate a git ref to prevent option injection.
38
+
39
+ Raises:
40
+ ValueError: If ref could be interpreted as a git option.
41
+ """
42
+ if ref.startswith("-"):
43
+ raise ValueError(f"Invalid git ref: {ref!r} (cannot start with '-')")
44
+
45
+
46
+ def validate_repo_url(url: str) -> None:
47
+ """
48
+ Validate a git repository URL.
49
+
50
+ Raises:
51
+ ValueError: If URL doesn't match expected patterns.
52
+ """
53
+ valid_prefixes = ("git@", "https://", "http://", "ssh://", "file://", "/", "./", "../")
54
+ if not any(url.startswith(prefix) for prefix in valid_prefixes):
55
+ raise ValueError(f"Invalid repository URL: {url!r}")
56
+
57
+
58
+ def run(*args: str, cwd: pathlib.Path | None = None, error_msg: str = "Git command failed") -> subprocess.CompletedProcess:
59
+ """
60
+ Run a git command and return the result.
61
+
62
+ Args:
63
+ *args: Git subcommand and arguments (e.g., "clone", url, path).
64
+ Do NOT include "git" — it's prepended automatically.
65
+ cwd: Working directory for the command.
66
+ error_msg: Message to include in exception on failure.
67
+
68
+ Raises:
69
+ GitError: If the command fails or returns non-zero.
70
+ """
71
+ cmd = ["git", *args]
72
+ try:
73
+ result = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
74
+ except Exception as e:
75
+ raise GitError(f"{error_msg}: {e}") from e
76
+
77
+ if result.returncode != 0:
78
+ raise GitError(error_msg, result.stderr)
79
+ return result
80
+
81
+
82
+ def clone(repo_url: str, dest: pathlib.Path, ref: str | None = None) -> None:
83
+ """
84
+ Clone a git repository.
85
+
86
+ Args:
87
+ repo_url: The repository URL to clone.
88
+ dest: Destination directory.
89
+ ref: Optional branch, tag, or commit to checkout after cloning.
90
+
91
+ Raises:
92
+ GitError: If clone or checkout fails.
93
+ """
94
+ run("clone", repo_url, str(dest), error_msg="Failed to clone repository")
95
+ if ref:
96
+ run("checkout", ref, cwd=dest, error_msg=f"Failed to checkout '{ref}'")
97
+
98
+
99
+ def pull(repo_path: pathlib.Path) -> None:
100
+ """
101
+ Pull latest changes in a git repository.
102
+
103
+ Raises:
104
+ GitError: If pull fails.
105
+ """
106
+ run("pull", cwd=repo_path, error_msg="Failed to pull repository")
107
+
108
+
109
+ def fetch_and_checkout(repo_path: pathlib.Path, ref: str) -> None:
110
+ """
111
+ Fetch all remotes and checkout a specific ref.
112
+
113
+ Args:
114
+ repo_path: Path to the git repository.
115
+ ref: Branch, tag, or commit to checkout.
116
+
117
+ Raises:
118
+ GitError: If fetch or checkout fails.
119
+ """
120
+ run("fetch", "--all", cwd=repo_path, error_msg="Failed to fetch from repository")
121
+ run("checkout", ref, cwd=repo_path, error_msg=f"Failed to checkout '{ref}'")
weco/setup.py CHANGED
@@ -4,189 +4,292 @@ Setup commands for integrating Weco with various AI tools.
4
4
  """
5
5
 
6
6
  import pathlib
7
- import shutil
8
- import subprocess
7
+ import sys
8
+
9
9
  from rich.console import Console
10
10
  from rich.prompt import Confirm
11
11
 
12
+ from . import git
13
+ from .utils import copy_directory, copy_file, read_from_path, remove_directory, write_to_path
14
+
15
+
16
+ # =============================================================================
17
+ # Exceptions
18
+ # =============================================================================
19
+
20
+
21
+ class SetupError(Exception):
22
+ """Base exception for setup failures."""
23
+
24
+ pass
25
+
26
+
27
+ class InvalidLocalRepoError(SetupError):
28
+ """Raised when a local path is not a valid skill repository."""
29
+
30
+ pass
31
+
32
+
33
+ # =============================================================================
34
+ # Path constants
35
+ # =============================================================================
36
+
12
37
  # Claude Code paths
13
38
  CLAUDE_DIR = pathlib.Path.home() / ".claude"
14
39
  CLAUDE_SKILLS_DIR = CLAUDE_DIR / "skills"
15
- CLAUDE_MD_PATH = CLAUDE_DIR / "CLAUDE.md"
16
40
  WECO_SKILL_DIR = CLAUDE_SKILLS_DIR / "weco"
17
41
  WECO_SKILL_REPO = "git@github.com:WecoAI/weco-skill.git"
42
+ WECO_CLAUDE_SNIPPET_PATH = WECO_SKILL_DIR / "snippets" / "claude.md"
43
+ WECO_CLAUDE_MD_PATH = WECO_SKILL_DIR / "CLAUDE.md"
44
+
45
+ # Cursor paths
46
+ CURSOR_DIR = pathlib.Path.home() / ".cursor"
47
+ CURSOR_RULES_DIR = CURSOR_DIR / "rules"
48
+ CURSOR_WECO_RULES_PATH = CURSOR_RULES_DIR / "weco.mdc"
49
+ CURSOR_SKILLS_DIR = CURSOR_DIR / "skills"
50
+ CURSOR_WECO_SKILL_DIR = CURSOR_SKILLS_DIR / "weco"
51
+ CURSOR_RULES_SNIPPET_PATH = CURSOR_WECO_SKILL_DIR / "snippets" / "cursor.md"
52
+
53
+ # Files/directories to skip when copying local repos
54
+ _COPY_IGNORE_PATTERNS = {".git", "__pycache__", ".DS_Store"}
18
55
 
19
- CLAUDE_MD_SECTION = """
20
- # Weco Code Optimization
21
56
 
22
- When users ask to optimize code against a measurable metric (speed, accuracy, loss, latency, F1, etc.), use Weco. Read
23
- `~/.claude/skills/weco/CLAUDE.md` for the full workflow.
57
+ # =============================================================================
58
+ # Domain helpers
59
+ # =============================================================================
24
60
 
25
- **Trigger phrases**: "make faster", "speed up", "optimize", "improve performance", "improve accuracy", "reduce loss",
26
- "optimize kernel", "improve prompt"
27
61
 
28
- **Do NOT** manually optimize - Weco's AI search achieves better results.
62
+ def generate_cursor_mdc_content(snippet_content: str) -> str:
63
+ """Generate Cursor MDC file content with YAML frontmatter."""
64
+ return f"""---
65
+ 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.
66
+ alwaysApply: true
67
+ ---
68
+ {snippet_content}
29
69
  """
30
70
 
31
71
 
32
- def is_git_available() -> bool:
33
- """Check if git is available on the system."""
34
- return shutil.which("git") is not None
72
+ def validate_local_skill_repo(local_path: pathlib.Path) -> None:
73
+ """
74
+ Validate that a local path is a valid weco-skill repository.
75
+
76
+ Raises:
77
+ InvalidLocalRepoError: If validation fails.
78
+ """
79
+ if not local_path.exists():
80
+ raise InvalidLocalRepoError(f"Local path does not exist: {local_path}")
81
+ if not local_path.is_dir():
82
+ raise InvalidLocalRepoError(f"Local path is not a directory: {local_path}")
83
+ if not (local_path / "SKILL.md").exists():
84
+ raise InvalidLocalRepoError(
85
+ f"Local path does not appear to be a weco-skill repository (expected SKILL.md at {local_path / 'SKILL.md'})"
86
+ )
35
87
 
36
88
 
37
- def is_git_repo(path: pathlib.Path) -> bool:
38
- """Check if a directory is a git repository."""
39
- return (path / ".git").is_dir()
89
+ # =============================================================================
90
+ # Installation functions
91
+ # =============================================================================
40
92
 
41
93
 
42
- def clone_skill_repo(console: Console) -> bool:
94
+ def install_skill_from_git(skill_dir: pathlib.Path, console: Console, repo_url: str | None, ref: str | None) -> None:
43
95
  """
44
- Clone or update the weco-skill repository.
96
+ Clone or update skill from git.
45
97
 
46
- Returns:
47
- True if successful, False otherwise.
98
+ Raises:
99
+ git.GitNotFoundError: If git is not available.
100
+ git.GitError: If git operations fail.
48
101
  """
49
- if not is_git_available():
50
- console.print("[bold red]Error:[/] git is not installed or not in PATH.")
51
- console.print("Please install git and try again.")
52
- return False
53
-
54
- # Ensure the skills directory exists
55
- CLAUDE_SKILLS_DIR.mkdir(parents=True, exist_ok=True)
56
-
57
- if WECO_SKILL_DIR.exists():
58
- if is_git_repo(WECO_SKILL_DIR):
59
- # Directory exists and is a git repo - pull latest
60
- console.print(f"[cyan]Updating existing skill at {WECO_SKILL_DIR}...[/]")
61
- try:
62
- result = subprocess.run(["git", "pull"], cwd=WECO_SKILL_DIR, capture_output=True, text=True)
63
- if result.returncode != 0:
64
- console.print("[bold red]Error:[/] Failed to update skill repository.")
65
- console.print(f"[dim]{result.stderr}[/]")
66
- return False
102
+ if not git.is_available():
103
+ raise git.GitNotFoundError("git is not installed or not in PATH")
104
+
105
+ skill_dir.parent.mkdir(parents=True, exist_ok=True)
106
+
107
+ if skill_dir.exists():
108
+ if git.is_repo(skill_dir):
109
+ console.print(f"[cyan]Updating existing skill at {skill_dir}...[/]")
110
+ if ref:
111
+ git.fetch_and_checkout(skill_dir, ref)
112
+ console.print(f"[green]Checked out {ref}.[/]")
113
+ else:
114
+ git.pull(skill_dir)
67
115
  console.print("[green]Skill updated successfully.[/]")
68
- return True
69
- except Exception as e:
70
- console.print(f"[bold red]Error:[/] Failed to update skill repository: {e}")
71
- return False
72
- else:
73
- # Directory exists but is not a git repo
74
- console.print(f"[bold red]Error:[/] Directory {WECO_SKILL_DIR} exists but is not a git repository.")
75
- console.print("Please remove it manually and try again.")
76
- return False
116
+ return
117
+
118
+ # Not a git repo clear and re-clone
119
+ console.print(f"[cyan]Removing existing directory at {skill_dir}...[/]")
120
+ remove_directory(skill_dir)
121
+
122
+ console.print(f"[cyan]Cloning Weco skill to {skill_dir}...[/]")
123
+ git.clone(repo_url or WECO_SKILL_REPO, skill_dir, ref=ref)
124
+ if ref:
125
+ console.print(f"[green]Cloned and checked out {ref}.[/]")
77
126
  else:
78
- # Clone the repository
79
- console.print(f"[cyan]Cloning Weco skill to {WECO_SKILL_DIR}...[/]")
80
- try:
81
- result = subprocess.run(["git", "clone", WECO_SKILL_REPO, str(WECO_SKILL_DIR)], capture_output=True, text=True)
82
- if result.returncode != 0:
83
- console.print("[bold red]Error:[/] Failed to clone skill repository.")
84
- console.print(f"[dim]{result.stderr}[/]")
85
- return False
86
- console.print("[green]Skill cloned successfully.[/]")
87
- return True
88
- except Exception as e:
89
- console.print(f"[bold red]Error:[/] Failed to clone skill repository: {e}")
90
- return False
91
-
92
-
93
- def update_claude_md(console: Console) -> bool:
127
+ console.print("[green]Skill cloned successfully.[/]")
128
+
129
+
130
+ def install_skill_from_local(skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path) -> None:
94
131
  """
95
- Update the user's CLAUDE.md file with the Weco skill reference.
132
+ Copy skill from local path.
96
133
 
97
- Returns:
98
- True if updated or user declined, False on error.
134
+ Raises:
135
+ InvalidLocalRepoError: If local path is invalid.
136
+ OSError: If copy fails.
99
137
  """
100
- # Check if the section already exists
101
- if CLAUDE_MD_PATH.exists():
102
- try:
103
- content = CLAUDE_MD_PATH.read_text()
104
- if "~/.claude/skills/weco/CLAUDE.md" in content:
105
- console.print("[dim]CLAUDE.md already contains the Weco skill reference.[/]")
106
- return True
107
- except Exception as e:
108
- console.print(f"[bold yellow]Warning:[/] Could not read CLAUDE.md: {e}")
109
-
110
- # Prompt user for permission
111
- if CLAUDE_MD_PATH.exists():
112
- console.print("\n[bold yellow]CLAUDE.md Update[/]")
113
- console.print("To enable automatic skill discovery, we can add a reference to your CLAUDE.md file.")
114
- should_update = Confirm.ask(
115
- "Would you like to update your CLAUDE.md to enable automatic skill discovery?", default=True
116
- )
138
+ validate_local_skill_repo(local_path)
139
+
140
+ skill_dir.parent.mkdir(parents=True, exist_ok=True)
141
+
142
+ if skill_dir.exists():
143
+ console.print(f"[cyan]Removing existing directory at {skill_dir}...[/]")
144
+ remove_directory(skill_dir)
145
+
146
+ copy_directory(local_path, skill_dir, ignore_patterns=_COPY_IGNORE_PATTERNS)
147
+ console.print(f"[green]Copied local repo from: {local_path}[/]")
148
+
149
+
150
+ def install_skill(
151
+ skill_dir: pathlib.Path, console: Console, local_path: pathlib.Path | None, repo_url: str | None, ref: str | None
152
+ ) -> None:
153
+ """Install skill by copying from local path or cloning from git."""
154
+ if local_path:
155
+ if ref:
156
+ console.print("[bold yellow]Warning:[/] --ref is ignored when using --local")
157
+ install_skill_from_local(skill_dir, console, local_path)
117
158
  else:
118
- console.print("\n[bold yellow]CLAUDE.md Creation[/]")
119
- console.print("To enable automatic skill discovery, we can create a CLAUDE.md file.")
120
- should_update = Confirm.ask("Would you like to create CLAUDE.md to enable automatic skill discovery?", default=True)
121
-
122
- if not should_update:
123
- console.print("\n[yellow]Skipping CLAUDE.md update.[/]")
124
- console.print(
125
- "[dim]The Weco skill has been installed but may not be discovered automatically.\n"
126
- f"You can manually reference it at {WECO_SKILL_DIR}/CLAUDE.md[/]"
127
- )
128
- return True
159
+ install_skill_from_git(skill_dir, console, repo_url, ref)
129
160
 
130
- # Update or create the file
131
- try:
132
- CLAUDE_DIR.mkdir(parents=True, exist_ok=True)
133
-
134
- if CLAUDE_MD_PATH.exists():
135
- # Append to existing file
136
- with open(CLAUDE_MD_PATH, "a") as f:
137
- f.write(CLAUDE_MD_SECTION)
138
- console.print("[green]CLAUDE.md updated successfully.[/]")
139
- else:
140
- # Create new file
141
- with open(CLAUDE_MD_PATH, "w") as f:
142
- f.write(CLAUDE_MD_SECTION.lstrip())
143
- console.print("[green]CLAUDE.md created successfully.[/]")
144
- return True
145
- except Exception as e:
146
- console.print(f"[bold red]Error:[/] Failed to update CLAUDE.md: {e}")
147
- return False
148
-
149
-
150
- def setup_claude_code(console: Console) -> bool:
151
- """
152
- Set up Weco skill for Claude Code.
153
161
 
154
- Returns:
155
- True if setup was successful, False otherwise.
156
- """
162
+ # =============================================================================
163
+ # Setup commands
164
+ # =============================================================================
165
+
166
+
167
+ def setup_claude_code(
168
+ console: Console, local_path: pathlib.Path | None = None, repo_url: str | None = None, ref: str | None = None
169
+ ) -> None:
170
+ """Set up Weco skill for Claude Code."""
157
171
  console.print("[bold blue]Setting up Weco for Claude Code...[/]\n")
158
172
 
159
- # Step 1: Clone or update the skill repository
160
- if not clone_skill_repo(console):
161
- return False
173
+ # Claude Code setup is intentionally "skill-centric":
174
+ # - Install the skill into Claude's skills directory.
175
+ # - `CLAUDE.md` lives *inside* that installed skill folder, so configuration is just
176
+ # copying a file within the skill directory.
177
+ # - There is no separate global config file to reconcile or prompt before overwriting.
178
+ install_skill(WECO_SKILL_DIR, console, local_path, repo_url, ref)
162
179
 
163
- # Step 2: Update CLAUDE.md
164
- if not update_claude_md(console):
165
- return False
180
+ # Copy snippets/claude.md to CLAUDE.md (skip for local - user manages their own)
181
+ if not local_path:
182
+ copy_file(WECO_CLAUDE_SNIPPET_PATH, WECO_CLAUDE_MD_PATH)
183
+ console.print("[green]CLAUDE.md installed to skill directory.[/]")
166
184
 
167
185
  console.print("\n[bold green]Setup complete![/]")
186
+ if local_path:
187
+ console.print(f"[dim]Skill copied from: {local_path}[/]")
168
188
  console.print(f"[dim]Skill installed at: {WECO_SKILL_DIR}[/]")
169
- return True
189
+
190
+
191
+ def setup_cursor(
192
+ console: Console, local_path: pathlib.Path | None = None, repo_url: str | None = None, ref: str | None = None
193
+ ) -> None:
194
+ """Set up Weco rules for Cursor."""
195
+ console.print("[bold blue]Setting up Weco for Cursor...[/]\n")
196
+
197
+ # Cursor setup is intentionally "editor-config-centric":
198
+ # - Install/copy the skill into Cursor's skills directory (so we can read snippets).
199
+ # - The behavior change is controlled by `~/.cursor/rules/weco.mdc`, which is *global*
200
+ # editor state (not part of the installed skill folder).
201
+ # - Because users may have customized that file, we:
202
+ # 1) compute desired content from the snippet
203
+ # 2) check if it is already up to date
204
+ # 3) prompt before creating/updating it
205
+ install_skill(CURSOR_WECO_SKILL_DIR, console, local_path, repo_url, ref)
206
+
207
+ snippet_content = read_from_path(CURSOR_RULES_SNIPPET_PATH)
208
+ mdc_content = generate_cursor_mdc_content(snippet_content.strip())
209
+
210
+ # Check if already up to date
211
+ existing_content = None
212
+ if CURSOR_WECO_RULES_PATH.exists():
213
+ try:
214
+ existing_content = read_from_path(CURSOR_WECO_RULES_PATH)
215
+ except Exception:
216
+ pass
217
+
218
+ if existing_content is not None and existing_content.strip() == mdc_content.strip():
219
+ console.print("[dim]weco.mdc already contains the latest Weco rules.[/]")
220
+ console.print("\n[bold green]Setup complete![/]")
221
+ console.print(f"[dim]Rules file at: {CURSOR_WECO_RULES_PATH}[/]")
222
+ return
223
+
224
+ # Prompt user for creation/update
225
+ if existing_content is not None:
226
+ console.print("\n[bold yellow]weco.mdc Update[/]")
227
+ console.print("The Weco rules file can be updated to the latest version.")
228
+ if not Confirm.ask("Would you like to update weco.mdc?", default=True):
229
+ console.print("\n[yellow]Skipping weco.mdc update.[/]")
230
+ console.print(f"[dim]Skill installed but rules not configured. Create manually at {CURSOR_WECO_RULES_PATH}[/]")
231
+ return
232
+ else:
233
+ console.print("\n[bold yellow]weco.mdc Creation[/]")
234
+ console.print("To enable Weco optimization rules, we can create a weco.mdc file.")
235
+ if not Confirm.ask("Would you like to create weco.mdc?", default=True):
236
+ console.print("\n[yellow]Skipping weco.mdc creation.[/]")
237
+ console.print(f"[dim]Skill installed but rules not configured. Create manually at {CURSOR_WECO_RULES_PATH}[/]")
238
+ return
239
+
240
+ write_to_path(CURSOR_WECO_RULES_PATH, mdc_content, mkdir=True)
241
+ console.print("[green]weco.mdc created successfully.[/]")
242
+
243
+ console.print("\n[bold green]Setup complete![/]")
244
+ if local_path:
245
+ console.print(f"[dim]Skill copied from: {local_path}[/]")
246
+ console.print(f"[dim]Skill installed at: {CURSOR_WECO_SKILL_DIR}[/]")
247
+ console.print(f"[dim]Rules file at: {CURSOR_WECO_RULES_PATH}[/]")
248
+
249
+
250
+ # =============================================================================
251
+ # CLI entry point
252
+ # =============================================================================
253
+
254
+ SETUP_HANDLERS = {"claude-code": setup_claude_code, "cursor": setup_cursor}
170
255
 
171
256
 
172
257
  def handle_setup_command(args, console: Console) -> None:
173
258
  """Handle the setup command with its subcommands."""
174
- if args.tool == "claude-code":
175
- success = setup_claude_code(console)
176
- if not success:
177
- import sys
259
+ available_tools = ", ".join(SETUP_HANDLERS)
178
260
 
179
- sys.exit(1)
180
- elif args.tool is None:
261
+ if args.tool is None:
181
262
  console.print("[bold red]Error:[/] Please specify a tool to set up.")
182
- console.print("Available tools: claude-code")
183
- console.print("\nUsage: weco setup claude-code")
184
- import sys
185
-
263
+ console.print(f"Available tools: {available_tools}")
264
+ console.print("\nUsage: weco setup <tool>")
186
265
  sys.exit(1)
187
- else:
266
+
267
+ handler = SETUP_HANDLERS.get(args.tool)
268
+ if handler is None:
188
269
  console.print(f"[bold red]Error:[/] Unknown tool: {args.tool}")
189
- console.print("Available tools: claude-code")
190
- import sys
270
+ console.print(f"Available tools: {available_tools}")
271
+ sys.exit(1)
272
+
273
+ # Validate and extract args
274
+ repo_url = getattr(args, "repo", None)
275
+ ref = getattr(args, "ref", None)
276
+ local_path = None
277
+ if hasattr(args, "local") and args.local:
278
+ local_path = pathlib.Path(args.local).expanduser().resolve()
279
+
280
+ try:
281
+ if repo_url:
282
+ git.validate_repo_url(repo_url)
283
+ if ref:
284
+ git.validate_ref(ref)
285
+
286
+ handler(console, local_path=local_path, repo_url=repo_url, ref=ref)
191
287
 
288
+ except git.GitError as e:
289
+ console.print(f"[bold red]Error:[/] {e}")
290
+ if e.stderr:
291
+ console.print(f"[dim]{e.stderr}[/]")
292
+ sys.exit(1)
293
+ except (SetupError, git.GitNotFoundError, FileNotFoundError, OSError, ValueError) as e:
294
+ console.print(f"[bold red]Error:[/] {e}")
192
295
  sys.exit(1)
weco/utils.py CHANGED
@@ -1,5 +1,6 @@
1
1
  from typing import Any, Dict, List, Tuple, Union
2
2
  import json
3
+ import shutil
3
4
  import time
4
5
  import subprocess
5
6
  import psutil
@@ -63,8 +64,19 @@ def read_from_path(fp: pathlib.Path, is_json: bool = False) -> Union[str, Dict[s
63
64
  return f.read()
64
65
 
65
66
 
66
- def write_to_path(fp: pathlib.Path, content: Union[str, Dict[str, Any]], is_json: bool = False) -> None:
67
- """Write content to a file path, optionally as JSON."""
67
+ def write_to_path(fp: pathlib.Path, content: Union[str, Dict[str, Any]], is_json: bool = False, mkdir: bool = False) -> None:
68
+ """
69
+ Write content to a file path, optionally as JSON.
70
+
71
+ Args:
72
+ fp: File path to write to.
73
+ content: Content to write (string or dict for JSON).
74
+ is_json: If True, write as JSON.
75
+ mkdir: If True, create parent directories if they don't exist.
76
+ """
77
+ if mkdir:
78
+ fp.parent.mkdir(parents=True, exist_ok=True)
79
+
68
80
  with fp.open("w", encoding="utf-8") as f:
69
81
  if is_json:
70
82
  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
74
86
  raise TypeError("Error writing to file. Please verify the file path and try again.")
75
87
 
76
88
 
89
+ def copy_file(src: pathlib.Path, dest: pathlib.Path, mkdir: bool = False) -> None:
90
+ """
91
+ Copy a single file.
92
+
93
+ Args:
94
+ src: Source file path.
95
+ dest: Destination file path.
96
+ mkdir: If True, create parent directories if they don't exist.
97
+
98
+ Raises:
99
+ FileNotFoundError: If source doesn't exist.
100
+ OSError: If copy fails.
101
+ """
102
+ if not src.exists():
103
+ raise FileNotFoundError(f"Source file not found: {src}")
104
+ if mkdir:
105
+ dest.parent.mkdir(parents=True, exist_ok=True)
106
+ shutil.copy(src, dest)
107
+
108
+
109
+ def copy_directory(src: pathlib.Path, dest: pathlib.Path, ignore_patterns: set[str] | None = None) -> None:
110
+ """
111
+ Copy a directory tree.
112
+
113
+ Args:
114
+ src: Source directory path.
115
+ dest: Destination directory path.
116
+ ignore_patterns: Optional set of file/directory names to skip.
117
+
118
+ Raises:
119
+ FileNotFoundError: If source doesn't exist.
120
+ OSError: If copy fails.
121
+ """
122
+ if not src.exists():
123
+ raise FileNotFoundError(f"Source directory not found: {src}")
124
+
125
+ def ignore_func(_: str, files: list[str]) -> list[str]:
126
+ if not ignore_patterns:
127
+ return []
128
+ return [f for f in files if f in ignore_patterns]
129
+
130
+ shutil.copytree(src, dest, ignore=ignore_func)
131
+
132
+
133
+ def remove_directory(path: pathlib.Path) -> None:
134
+ """
135
+ Remove a directory and all its contents.
136
+
137
+ Does nothing if the directory doesn't exist.
138
+ """
139
+ if path.exists():
140
+ shutil.rmtree(path)
141
+
142
+
77
143
  # Visualization helper functions
78
144
  def smooth_update(
79
145
  live: Live, layout: Layout, sections_to_update: List[Tuple[str, Panel]], transition_delay: float = 0.05
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: weco
3
- Version: 0.3.9
3
+ Version: 0.3.11
4
4
  Summary: Documentation for `weco`, a CLI for using Weco AI's code optimizer.
5
5
  Author-email: Weco AI Team <contact@weco.ai>
6
6
  License:
@@ -347,14 +347,17 @@ For more advanced examples, including [Triton](/examples/triton/README.md), [CUD
347
347
  | Command | Description |
348
348
  |---------|-------------|
349
349
  | `weco setup claude-code` | Set up Weco skill for Claude Code |
350
+ | `weco setup cursor` | Set up Weco rules for Cursor |
350
351
 
351
- The `setup` command installs Weco skills for AI coding assistants. Currently supports Claude Code:
352
+ The `setup` command installs Weco skills for AI coding assistants:
352
353
 
353
354
  ```bash
354
- weco setup claude-code
355
+ weco setup claude-code # For Claude Code
356
+ weco setup cursor # For Cursor
355
357
  ```
356
358
 
357
- This clones the Weco skill to `~/.claude/skills/weco/` and optionally updates your `~/.claude/CLAUDE.md` to enable automatic skill discovery.
359
+ - **Claude Code**: Clones the Weco skill to `~/.claude/skills/weco/` and updates `~/.claude/CLAUDE.md`
360
+ - **Cursor**: Clones the Weco skill to `~/.cursor/skills/weco/` and creates `~/.cursor/rules/weco.mdc`
358
361
 
359
362
  ### Model Selection
360
363
 
@@ -0,0 +1,20 @@
1
+ weco/__init__.py,sha256=ClO0uT6GKOA0iSptvP0xbtdycf0VpoPTq37jHtvlhtw,303
2
+ weco/api.py,sha256=hy0D01x-AJ26DURtKEywQAS7nQgo38A-wAJfPKHGGqM,17395
3
+ weco/auth.py,sha256=O31Hoj-Loi8DWJJG2LfeWgUMuNqAUeGDpd2ZGjA9Ah0,9997
4
+ weco/browser.py,sha256=nsqQtLqbNOe9Zhu9Zogc8rMmBMyuDxuHzKZQL_w10Ps,923
5
+ weco/cli.py,sha256=6JDMZ6jNyqaTlzbabzaCxK_UpImh818wabNI5kBsh6M,14775
6
+ weco/constants.py,sha256=rxL6yrpIzK8zvPTmPqOYl7LUMZ01vUJ9zUqfZD2n-0U,519
7
+ weco/credits.py,sha256=C08x-TRcLg3ccfKqMGNRY7zBn7t3r7LZ119bxgfztaI,7629
8
+ weco/git.py,sha256=j7JI9nzB7jqEACBsQflU5h4l2bOlg5oWVyEmZ0-ORkI,3377
9
+ weco/optimizer.py,sha256=l9TrAsie5yPbhq71kStW5jfdz9jfIXuN6Azdn6hUMZo,25224
10
+ weco/panels.py,sha256=POHt0MdRKDykwUJYXcry92O41lpB9gxna55wFI9abWU,16272
11
+ weco/setup.py,sha256=wh_yFrTML_Qt5QDhhaDyIJQccxId8p_1DjmWYxDq9hc,11393
12
+ weco/ui.py,sha256=Y7ASIQydwuYFdSYrvme5aGvkplFMi-cjhsnCj5Ebgoc,15092
13
+ weco/utils.py,sha256=5MpUFoydk_AFkzZRQQH5ddPA6G_3YI7ocNQBaFXHy6o,11283
14
+ weco/validation.py,sha256=n5aDuF3BFgwVb4eZ9PuU48nogrseXYNI8S3ePqWZCoc,3736
15
+ weco-0.3.11.dist-info/licenses/LICENSE,sha256=9LUfoGHjLPtak2zps2kL2tm65HAZIICx_FbLaRuS4KU,11337
16
+ weco-0.3.11.dist-info/METADATA,sha256=_zThzvB4LDG0REEW_hCMGzsVgXRnNAG-xRZ3o3RBipU,30804
17
+ weco-0.3.11.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
18
+ weco-0.3.11.dist-info/entry_points.txt,sha256=ixJ2uClALbCpBvnIR6BXMNck8SHAab8eVkM9pIUowcs,39
19
+ weco-0.3.11.dist-info/top_level.txt,sha256=F0N7v6e2zBSlsorFv-arAq2yDxQbzX3KVO8GxYhPUeE,5
20
+ weco-0.3.11.dist-info/RECORD,,
@@ -1,19 +0,0 @@
1
- weco/__init__.py,sha256=ClO0uT6GKOA0iSptvP0xbtdycf0VpoPTq37jHtvlhtw,303
2
- weco/api.py,sha256=hy0D01x-AJ26DURtKEywQAS7nQgo38A-wAJfPKHGGqM,17395
3
- weco/auth.py,sha256=O31Hoj-Loi8DWJJG2LfeWgUMuNqAUeGDpd2ZGjA9Ah0,9997
4
- weco/browser.py,sha256=nsqQtLqbNOe9Zhu9Zogc8rMmBMyuDxuHzKZQL_w10Ps,923
5
- weco/cli.py,sha256=zPWQa2UU19ClzTtIvsXuYmo7E9xm50wUzY2fU8iwcro,13921
6
- weco/constants.py,sha256=rxL6yrpIzK8zvPTmPqOYl7LUMZ01vUJ9zUqfZD2n-0U,519
7
- weco/credits.py,sha256=C08x-TRcLg3ccfKqMGNRY7zBn7t3r7LZ119bxgfztaI,7629
8
- weco/optimizer.py,sha256=l9TrAsie5yPbhq71kStW5jfdz9jfIXuN6Azdn6hUMZo,25224
9
- weco/panels.py,sha256=POHt0MdRKDykwUJYXcry92O41lpB9gxna55wFI9abWU,16272
10
- weco/setup.py,sha256=UWlJNfNvxmET3ZrhaJxQFrtZCMSyjp4HC8d6h1ndaC4,7078
11
- weco/ui.py,sha256=Y7ASIQydwuYFdSYrvme5aGvkplFMi-cjhsnCj5Ebgoc,15092
12
- weco/utils.py,sha256=v_rvgw-ktRoXrpPA2copngI8QDCB8UXmbiN-wAiYvEE,9450
13
- weco/validation.py,sha256=n5aDuF3BFgwVb4eZ9PuU48nogrseXYNI8S3ePqWZCoc,3736
14
- weco-0.3.9.dist-info/licenses/LICENSE,sha256=9LUfoGHjLPtak2zps2kL2tm65HAZIICx_FbLaRuS4KU,11337
15
- weco-0.3.9.dist-info/METADATA,sha256=dry9z1fIVdbnCdRy8i-0Xu3SClyAZNPBCdl-hDyL6MM,30660
16
- weco-0.3.9.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
17
- weco-0.3.9.dist-info/entry_points.txt,sha256=ixJ2uClALbCpBvnIR6BXMNck8SHAab8eVkM9pIUowcs,39
18
- weco-0.3.9.dist-info/top_level.txt,sha256=F0N7v6e2zBSlsorFv-arAq2yDxQbzX3KVO8GxYhPUeE,5
19
- weco-0.3.9.dist-info/RECORD,,
File without changes