feat: add code-operations-skills plugin (converted from code-copy-mcp) (#10)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
mhattingpete
2025-10-24 10:46:42 +02:00
committed by GitHub
co-authored by Claude
parent d305fceb93
commit 23766b569e
8 changed files with 1598 additions and 0 deletions
+9
View File
@@ -31,6 +31,15 @@
"author": {
"name": "mhattingpete"
}
},
{
"name": "code-operations-skills",
"source": "./code-operations-plugin",
"description": "High-precision code manipulation operations including line-based insertion, bulk refactoring, and file analysis - converted from code-copy-mcp",
"version": "1.0.0",
"author": {
"name": "mhattingpete"
}
}
]
}
+62
View File
@@ -40,6 +40,16 @@ claude-skills-marketplace/
│ │ ├── conversation-analyzer/ # Usage analysis skill
│ │ └── project-bootstrapper/ # Project setup skill
│ └── README.md
├── code-operations-plugin/ # Code manipulation plugin
│ ├── .claude-plugin/
│ │ └── plugin.json # Plugin manifest
│ ├── skills/
│ │ ├── code-transfer/ # Code transfer skill
│ │ │ └── scripts/
│ │ │ └── line_insert.py # Line-based insertion script
│ │ ├── code-refactor/ # Bulk refactoring skill
│ │ └── file-operations/ # File analysis skill
│ └── README.md
├── LICENSE
└── README.md
```
@@ -84,6 +94,9 @@ To install individual plugins:
# Install only productivity skills
/plugin marketplace add mhattingpete/claude-skills-marketplace/productivity-skills-plugin
# Install only code operations
/plugin marketplace add mhattingpete/claude-skills-marketplace/code-operations-plugin
```
## Available Plugins
@@ -106,6 +119,12 @@ Productivity and workflow optimization skills for analyzing usage patterns, audi
[View Plugin Documentation →](productivity-skills-plugin/README.md)
### Code Operations Plugin
High-precision code manipulation operations including line-based insertion, bulk refactoring, and file analysis. Converted from [code-copy-mcp](https://github.com/mhattingpete/code-copy-mcp) to native Claude Code skills.
[View Plugin Documentation →](code-operations-plugin/README.md)
## Available Skills
### Feature Development
@@ -166,6 +185,49 @@ Process and implement code review feedback systematically with todo tracking.
---
### Code Operations
#### `code-transfer`
Transfer code between files with line-based precision using the included `line_insert.py` script.
**Activates when:** User requests copying code between files, moving functions/classes, extracting code, or inserting at specific line numbers.
**Example usage:**
- "Copy the authenticate function from auth.py to utils.py"
- "Move this class to a separate file"
- "Extract this function to a new file"
- "Insert this code at line 45"
**Key feature:** Includes Python script for precise line-number-based insertion where Edit tool's string matching isn't suitable.
---
#### `code-refactor`
Perform bulk code refactoring operations like renaming variables/functions across files and replacing patterns.
**Activates when:** User requests renaming identifiers, replacing deprecated patterns, updating API calls, or making consistent changes across multiple locations.
**Example usage:**
- "Rename getUserData to fetchUserData everywhere"
- "Replace all var declarations with let or const"
- "Update all authentication API calls to use the new endpoint"
- "Convert callbacks to async/await"
---
#### `file-operations`
Analyze files and get detailed metadata without modifying them.
**Activates when:** User requests file information, statistics, or analysis without making changes.
**Example usage:**
- "Analyze this file"
- "How many lines in app.py?"
- "Compare the sizes of all Python files"
- "Give me code quality metrics for the project"
---
### Productivity & Analysis
#### `conversation-analyzer`
@@ -0,0 +1,9 @@
{
"name": "code-operations-skills",
"version": "1.0.0",
"description": "Skills for code manipulation operations including line-based code transfer, bulk refactoring, and file analysis - converted from code-copy-mcp",
"author": {
"name": "mhattingpete",
"email": "noreply@github.com"
}
}
+287
View File
@@ -0,0 +1,287 @@
# Code Operations Skills Plugin
High-precision code manipulation operations including line-based insertion, bulk refactoring, and file analysis.
**Origin:** Converted from [code-copy-mcp](https://github.com/mhattingpete/code-copy-mcp) to native Claude Code skills for simpler setup and better integration.
## Why This Plugin?
The original MCP server provided precise file operations that complemented Claude's native tools. This plugin preserves that functionality while:
✅ **Simpler setup** - No MCP server needed, just install the plugin
✅ **Natural activation** - Skills detect intent automatically from user requests
✅ **Better integration** - Works seamlessly with other Claude Code skills
✅ **Version controlled** - Part of the skills marketplace ecosystem
## Skills Included
### 1. code-transfer
Transfer code between files with line-based precision.
**Activates when you say:**
- "copy this code to [file]"
- "move [function/class] to [file]"
- "extract this to a new file"
- "insert at line [number]"
- "transfer code from X to Y"
**What it does:**
- Extracts code from source files (functions, classes, code blocks)
- Inserts code at specific line numbers using `line_insert.py` script
- Moves code between files while maintaining structure
- Reorganizes code into separate modules
**Example:**
```
User: "Move the DatabaseConnection class from app.py to a new file database.py"
Claude:
1. Finds and extracts the DatabaseConnection class
2. Creates database.py with the extracted class
3. Updates imports in app.py
4. Removes the old class definition
✅ Code successfully transferred
```
**Key feature:** Includes `line_insert.py` Python script for precise line-number-based insertion (works where Edit tool's string matching isn't suitable).
---
### 2. code-refactor
Perform bulk code refactoring operations across files.
**Activates when you say:**
- "rename [identifier] to [new_name]"
- "replace all [pattern] with [replacement]"
- "refactor to use [new_pattern]"
- "update all calls to [function/API]"
- "convert [old_pattern] to [new_pattern]"
**What it does:**
- Renames variables/functions consistently across entire codebase
- Replaces deprecated patterns with modern alternatives
- Updates API calls when endpoints change
- Converts code patterns (callbacks → async/await, var → let/const)
- Standardizes code style across files
**Example:**
```
User: "Rename getUserData to fetchUserData everywhere"
Claude:
1. Searches codebase: Found 15 occurrences in 5 files
2. Previews changes with context
3. Replaces all instances using Edit with replace_all
4. Verifies all replacements completed
5. Suggests running tests
✅ Refactored 15 instances across 5 files
```
---
### 3. file-operations
Analyze files and get detailed metadata without modifying them.
**Activates when you say:**
- "analyze [file]"
- "get file info for [file]"
- "how many lines in [file]"
- "file statistics for [file]"
- "compare [file1] and [file2]"
**What it does:**
- Retrieves file size, modification time, permissions
- Counts lines, words, characters in files
- Analyzes code structure (functions, classes, imports)
- Compares file sizes across directories
- Generates code quality metrics
**Example:**
```
User: "Analyze app.py and tell me about it"
Claude:
app.py Analysis:
- Size: 15.2 KB
- Lines: 456
- Functions: 12
- Classes: 3
- Imports: 8 modules
- Last modified: 2025-10-20
- TODO comments: 3
✅ Analysis complete
```
## Integration Example
The skills work together for complete code manipulation workflows:
```
User: "Refactor utils.py - split it into separate utility modules by category"
Claude:
1. [file-operations] Analyzes utils.py structure
- Found 45 functions across 3 categories
- File size: 1,245 lines (too large)
2. [code-transfer] Extracts string utilities
- Creates string_utils.py
- Transfers 15 related functions
3. [code-transfer] Extracts file utilities
- Creates file_utils.py
- Transfers 18 related functions
4. [code-refactor] Updates all imports
- Finds 23 files importing from utils.py
- Updates to use specific utility modules
✅ Successfully refactored utils.py into focused modules
```
## Installation
### From Claude Code CLI
```bash
# Install from marketplace
claude plugins install code-operations-skills
# Or install from local directory
claude plugins install /path/to/code-operations-plugin
```
### Manual Installation
1. Copy `code-operations-plugin/` to `~/.claude/plugins/`
2. Restart Claude Code
3. Skills will activate automatically based on usage patterns
## Usage Tips
### When to Use code-transfer vs Edit
**Use code-transfer when:**
- Moving code between files
- Inserting at specific line numbers
- Creating new files from extracted code
- User specifies "line N"
**Use native Edit when:**
- Replacing existing code in-place
- Insertion point defined by content, not line number
- Simple find-and-replace
### Efficient Refactoring Workflow
1. **Search first** - Use Grep to understand scope
2. **Preview changes** - Show user what will be affected
3. **Execute systematically** - Make changes file by file
4. **Verify** - Re-search to confirm completion
5. **Test** - Suggest running test suite
### File Analysis Best Practices
- Combine multiple metrics for comprehensive analysis
- Use human-readable formats for user reporting
- Suggest optimizations when finding issues
- Compare against project baselines
## Dependencies
**Minimal - only Python stdlib:**
- Python 3.6+ (for `line_insert.py` script)
- No external packages required
## Comparison with Original MCP
| Feature | MCP Server | This Plugin |
|---------|-----------|-------------|
| Line-based insertion | ✅ copy_code tool | ✅ line_insert.py script |
| Bulk refactoring | ✅ search_and_replace | ✅ Edit + replace_all |
| File analysis | ✅ get_file_info | ✅ Bash + Grep + Read |
| Copy entire files | ✅ copy_entire_file | ✅ Read + Write |
| Setup complexity | MCP server config | Plugin install |
| Activation | Explicit tool calls | Natural language |
| Integration | Separate process | Native skills |
**What we kept:**
- Precise line-based insertion capability
- Safety features (backups, validation)
- Comprehensive file operations
**What we improved:**
- No server process needed
- Automatic skill activation
- Better integration with Claude Code ecosystem
- Leverages native tools where possible
## Technical Details
### line_insert.py Script
**Location:** `skills/code-transfer/scripts/line_insert.py`
**Purpose:** Insert code at specific line numbers (complements Edit tool's string matching)
**Features:**
- 1-based line numbering
- Automatic file creation if needed
- Optional timestamped backups
- Multi-line code support
- Basic path validation for security
**Usage:**
```bash
python3 line_insert.py <file_path> <line_number> <code> [--backup]
```
**Example:**
```bash
# Insert function at line 50
python3 line_insert.py src/utils.py 50 "def helper():\\n pass"
# Insert with backup
python3 line_insert.py src/utils.py 50 "def helper():\\n pass" --backup
```
### Skill Activation Logic
Skills activate based on natural language patterns in user requests:
**code-transfer triggers:**
- Keywords: "copy", "move", "extract", "transfer", "insert at line"
- Context: Mentions source and target files
**code-refactor triggers:**
- Keywords: "rename", "replace all", "refactor", "update all", "convert"
- Context: Bulk operations across files
**file-operations triggers:**
- Keywords: "analyze", "info", "statistics", "how many", "compare"
- Context: Non-destructive analysis requests
## Version
**1.0.0** - Initial release (converted from code-copy-mcp)
## Author
mhattingpete
## License
MIT (same as original MCP server)
## Contributing
Issues and PRs welcome at the [skills marketplace repository](https://github.com/anthropics/claude-skills-marketplace).
## Related Resources
- **Original MCP:** [code-copy-mcp](https://github.com/mhattingpete/code-copy-mcp)
- **Skills Marketplace:** [claude-skills-marketplace](https://github.com/anthropics/claude-skills-marketplace)
- **Claude Code Docs:** [docs.claude.com/claude-code](https://docs.claude.com/claude-code)
@@ -0,0 +1,363 @@
---
name: code-refactor
description: Perform bulk code refactoring operations like renaming variables/functions across files, replacing patterns, and updating API calls. Use when users request renaming identifiers, replacing deprecated code patterns, updating method calls, or making consistent changes across multiple locations. Activates on phrases like "rename all instances", "replace X with Y everywhere", "refactor to use", or "update all calls to".
---
# Code Refactor
## Overview
Perform systematic code refactoring operations across files using pattern-based search and replace. This skill focuses on bulk transformations that maintain code functionality while improving structure, naming, or updating APIs.
## When to Use This Skill
Activate this skill when users request:
- **Rename variables/functions**: "Rename `getUserData` to `fetchUserData` everywhere"
- **Replace deprecated patterns**: "Replace all `var` declarations with `let` or `const`"
- **Update API calls**: "Update all calls to the old authentication API"
- **Refactor patterns**: "Convert all callbacks to async/await"
- **Standardize code**: "Make all import statements use absolute paths"
**Activation phrases:**
- "rename [identifier] to [new_name]"
- "replace all [pattern] with [replacement]"
- "refactor to use [new_pattern]"
- "update all calls to [function/API]"
- "convert [old_pattern] to [new_pattern]"
- "standardize [aspect] across the codebase"
## Core Capabilities
### 1. Find All Occurrences
Before refactoring, locate all instances of the pattern to understand scope and impact.
**Search for exact matches:**
```
Grep(pattern="getUserData", output_mode="files_with_matches")
```
**Search with context to verify usage:**
```
Grep(pattern="getUserData", output_mode="content", -n=true, -B=2, -A=2)
```
**Case-insensitive search:**
```
Grep(pattern="getuserdata", -i=true, output_mode="files_with_matches")
```
**Regex patterns:**
```
Grep(pattern="get\\w+Data", output_mode="content")
```
### 2. Replace All Instances
Use the **Edit** tool with `replace_all=true` for bulk replacements:
**Simple replacement:**
```
Edit(
file_path="src/api.js",
old_string="getUserData",
new_string="fetchUserData",
replace_all=true
)
```
**Multi-line replacement:**
```
Edit(
file_path="src/auth.js",
old_string="function authenticate(user) {\\n return user.valid;\\n}",
new_string="async function authenticate(user) {\\n return await validateUser(user);\\n}",
replace_all=true
)
```
### 3. Targeted Replacement
For single occurrences or when context matters, use Edit without `replace_all`:
```
Edit(
file_path="src/config.js",
old_string="const API_URL = 'http://old-api.com'",
new_string="const API_URL = 'https://new-api.com'"
)
```
## Workflow Examples
### Example 1: Rename Function Across Codebase
**User:** "Rename `getUserData` to `fetchUserData` everywhere"
**Workflow:**
1. **Find all occurrences** to understand scope:
```
Grep(pattern="getUserData", output_mode="files_with_matches")
```
2. **Preview changes** by viewing context:
```
Grep(pattern="getUserData", output_mode="content", -n=true, -B=1, -A=1)
```
3. **Inform user of scope**: "Found 15 occurrences in 5 files"
4. **Replace in each file**:
```
Edit(file_path="src/api.js", old_string="getUserData", new_string="fetchUserData", replace_all=true)
Edit(file_path="src/utils.js", old_string="getUserData", new_string="fetchUserData", replace_all=true)
# ... for each file
```
5. **Verify changes**: Re-run Grep to confirm all instances were replaced
6. **Suggest testing**: Recommend running tests to ensure refactoring didn't break functionality
### Example 2: Replace Deprecated Pattern
**User:** "Replace all `var` declarations with `let` or `const`"
**Workflow:**
1. **Find all var declarations**:
```
Grep(pattern="\\bvar\\s+\\w+", output_mode="content", -n=true)
```
2. **Analyze each occurrence** to determine whether to use `let` or `const`:
- Check if variable is reassigned → use `let`
- Check if variable is constant → use `const`
3. **Replace systematically**:
```
Edit(file_path="src/index.js", old_string="var count = 0", new_string="let count = 0", replace_all=false)
Edit(file_path="src/index.js", old_string="var MAX_SIZE = 100", new_string="const MAX_SIZE = 100", replace_all=false)
```
4. **Use linter if available** to verify syntax:
```bash
npm run lint
```
### Example 3: Update API Calls
**User:** "Update all authentication API calls to use the new endpoint"
**Workflow:**
1. **Find all API calls**:
```
Grep(pattern="/api/auth/login", output_mode="content", -n=true)
```
2. **Identify variation patterns**:
- Look for fetch calls, axios calls, or other HTTP methods
- Check for different HTTP methods (GET, POST, etc.)
3. **Replace with updated endpoint**:
```
Edit(
file_path="src/auth.js",
old_string="fetch('/api/auth/login', {",
new_string="fetch('/api/v2/authentication/login', {",
replace_all=true
)
```
4. **Update any response handling** if API contract changed
5. **Recommend integration tests**
### Example 4: Convert Callbacks to Async/Await
**User:** "Refactor this file to use async/await instead of callbacks"
**Workflow:**
1. **Analyze callback patterns**:
```
Grep(pattern="function\\s*\\([^)]*\\)\\s*{", output_mode="content", -n=true)
```
2. **Identify callback functions** (typically with `callback`, `cb`, or `done` parameters)
3. **Transform each function**:
```
Edit(
file_path="src/data.js",
old_string="function loadData(callback) {\\n db.query('SELECT *', callback);\\n}",
new_string="async function loadData() {\\n return await db.query('SELECT *');\\n}"
)
```
4. **Update call sites** to use await:
```
Edit(
file_path="src/app.js",
old_string="loadData((err, data) => {\\n if (err) throw err;\\n process(data);\\n});",
new_string="const data = await loadData();\\nprocess(data);"
)
```
5. **Add try-catch for error handling** where callbacks had error parameters
### Example 5: Standardize Import Paths
**User:** "Convert all relative imports to absolute imports"
**Workflow:**
1. **Find all relative imports**:
```
Grep(pattern="from ['\"]\\.\\.?/", output_mode="content", -n=true)
```
2. **Calculate absolute path** for each import based on project structure
3. **Replace each import**:
```
Edit(
file_path="src/components/Button.jsx",
old_string="import { theme } from '../../utils/theme'",
new_string="import { theme } from '@/utils/theme'",
replace_all=true
)
```
4. **Verify module resolution** works with new paths
## Best Practices
### Planning Refactoring
Before executing refactoring:
1. **Understand scope**: Use Grep to find all affected locations
2. **Assess impact**: Review context of each occurrence
3. **Inform user**: Report how many files/instances will be changed
4. **Consider edge cases**: Look for string literals, comments, documentation
### Safe Refactoring Process
**The refactoring workflow should be:**
1. **Search** → Find all instances
2. **Analyze** → Verify each match is appropriate to change
3. **Inform** → Tell user the scope
4. **Execute** → Make the changes
5. **Verify** → Confirm changes were applied correctly
6. **Test** → Suggest running tests
### Handling Special Cases
**String literals and comments:**
- Ask user if they want to update strings/comments containing the identifier
- Usually rename in code only, not in user-facing strings
**Exported APIs:**
- Warn if renaming exported functions (breaking change for consumers)
- Suggest deprecation warnings or maintaining aliases
**Case sensitivity:**
- Be explicit about case-sensitive vs case-insensitive replacements
- Use `-i` flag in Grep for case-insensitive when appropriate
### Verification
After refactoring:
1. **Re-run Grep** to verify all instances were updated
2. **Check syntax**: Use linter or language-specific checker
3. **Read affected files**: Spot-check critical files
4. **Recommend testing**: Suggest running test suite
## Error Handling
### Common Issues and Solutions
**Issue:** "Replacement created syntax errors"
- **Solution:** Ensure old_string and new_string maintain proper syntax
- **Prevention:** Include sufficient context in old_string to ensure valid replacement points
**Issue:** "Not all instances were replaced"
- **Solution:** Check for variations in whitespace, quotes, or formatting
- **Alternative:** Use regex patterns in Grep to find variations, then handle each
**Issue:** "Replaced instances in comments/strings unintentionally"
- **Solution:** Be more specific with old_string context
- **Consider:** Use language-aware tools if available (parsers, AST tools)
**Issue:** "Replace broke tests"
- **Solution:** Review test files separately, update test expectations
- **Prevention:** Preview test file changes before applying
## Tool Usage Reference
### Edit Tool Parameters
**Required:**
- `file_path`: File to modify
- `old_string`: Exact string to find
- `new_string`: Replacement string
**Optional:**
- `replace_all`: Boolean (default: false)
- `true`: Replace all occurrences in file
- `false`: Replace only first occurrence (or fail if multiple matches)
**Important notes:**
- `old_string` must match EXACTLY (including whitespace, quotes)
- If multiple matches exist without `replace_all=true`, Edit will fail
- Use `replace_all=true` for bulk refactoring
### Grep for Refactoring
**Useful Grep options for refactoring:**
- `-n=true`: Show line numbers (helps locate changes)
- `-B=N`, `-A=N`: Show context (verify match is correct)
- `-i=true`: Case-insensitive (find variations)
- `output_mode="content"`: See actual code
- `output_mode="count"`: Count occurrences per file
- `type`: Filter by file type (e.g., `type="py"`)
## Integration with Other Tools
### Working with Claude's Native Tools
- **Grep**: Find patterns across codebase
- **Read**: Analyze files before refactoring
- **Edit**: Execute replacements (with replace_all)
- **Bash**: Run linters, formatters, tests after refactoring
- **Glob**: Find files by pattern for targeted refactoring
### Working with Other Skills
- **test-fixing**: Fix tests broken by refactoring
- **code-transfer**: Move refactored code to better locations
- **feature-planning**: Plan large-scale refactoring efforts
## Language-Specific Patterns
### JavaScript/TypeScript
**Common refactoring patterns:**
- `var` → `let`/`const`
- Callbacks → Promises/async-await
- require() → import statements
- CommonJS → ES modules
- Class components → Function components (React)
### Python
**Common refactoring patterns:**
- Old string formatting → f-strings
- `%` formatting → `.format()` or f-strings
- Dict access → `.get()` with defaults
- Type hints additions
### General
**Universal refactoring patterns:**
- Function/variable renaming
- API endpoint updates
- Library version migrations
- Naming convention standardization
- Import path updates
@@ -0,0 +1,287 @@
---
name: code-transfer
description: Transfer code between files with line-based precision. Use when users request copying code from one location to another, moving functions or classes between files, extracting code blocks, or inserting code at specific line numbers. Activates on phrases like "copy this code to", "move this function to", "extract this to a new file", or "insert at line N".
---
# Code Transfer
## Overview
Transfer code between files with precise line-based control. This skill enables copying, moving, and inserting code at specific line numbers, which complements Claude's native Edit tool that requires exact string matching.
## When to Use This Skill
Activate this skill when users request:
- **Copy code between files**: "Copy the `authenticate` function from auth.py to utils.py"
- **Move code blocks**: "Move this class to a separate file"
- **Extract code**: "Extract this function into a new file"
- **Line-based insertion**: "Insert this code at line 45"
- **Reorganize code**: "Split this file into multiple modules"
**Activation phrases:**
- "copy this code to [file]"
- "move [function/class] to [file]"
- "extract this to a new file"
- "insert at line [number]"
- "transfer code from X to Y"
- "reorganize this into separate files"
## Core Capabilities
### 1. Extract Source Code
Use the **Read** tool to extract code from source files:
**Full file extraction:**
```
Read(file_path="src/auth.py")
```
**Line range extraction:**
```
Read(file_path="src/auth.py", offset=10, limit=20)
```
**Function/class identification:**
Use Grep to find specific functions or classes:
```
Grep(pattern="def authenticate", path="src/auth.py", output_mode="content", -n=true, -A=10)
```
### 2. Insert Code at Specific Line Numbers
When inserting code at a **specific line number** (not replacing existing text), use the `line_insert.py` script:
**Script location:** `skills/code-transfer/scripts/line_insert.py`
**Usage:**
```bash
python3 skills/code-transfer/scripts/line_insert.py <file_path> <line_number> <code> [--backup]
```
**Parameters:**
- `file_path`: Target file path (creates if doesn't exist)
- `line_number`: Where to insert (1-based index)
- `code`: Code to insert (use literal newlines or \\n)
- `--backup`: Optional flag to create timestamped backup
**Examples:**
```bash
# Insert a function at line 50
python3 skills/code-transfer/scripts/line_insert.py src/utils.py 50 "def helper():\\n pass"
# Insert with backup
python3 skills/code-transfer/scripts/line_insert.py src/utils.py 50 "def helper():\\n pass" --backup
# Insert at beginning of file
python3 skills/code-transfer/scripts/line_insert.py src/new.py 1 "import os\\nimport sys"
```
**When to use line_insert.py vs Edit:**
- **Use line_insert.py** when:
- User specifies exact line number
- Inserting into new/empty files
- Inserting at beginning/end without context
- Creating new sections in files
- **Use Edit** when:
- Replacing existing code (you have the exact old_string)
- Inserting relative to existing code (add after/before specific content)
- The insertion point is defined by content, not line number
### 3. Replace or Insert Adjacent to Existing Code
When the insertion point is **relative to existing content**, use the **Edit** tool:
```
Edit(
file_path="src/utils.py",
old_string="def existing_function():\\n pass",
new_string="def existing_function():\\n pass\\n\\ndef new_function():\\n return True"
)
```
## Workflow Examples
### Example 1: Copy Function Between Files
**User:** "Copy the `validate_user` function from auth.py to validators.py"
**Workflow:**
1. **Find the function** using Grep:
```
Grep(pattern="def validate_user", path="auth.py", output_mode="content", -n=true, -A=20)
```
2. **Extract the complete function** using Read (with line offset/limit from grep results):
```
Read(file_path="auth.py", offset=45, limit=15)
```
3. **Check target file structure** to determine insertion point:
```
Read(file_path="validators.py")
```
4. **Insert using appropriate method**:
- If user specified line number → use `line_insert.py`
- If inserting at end → use `line_insert.py` with line number = file length + 1
- If inserting near existing code → use Edit
### Example 2: Extract Class to New File
**User:** "Move the `DatabaseConnection` class to a new file database.py"
**Workflow:**
1. **Locate the class**:
```
Grep(pattern="class DatabaseConnection", output_mode="content", -n=true, -A=50)
```
2. **Extract full class definition**:
```
Read(file_path="original.py", offset=100, limit=50)
```
3. **Create new file with the class**:
```
Write(file_path="database.py", content="<extracted_class>")
```
4. **Update imports in original file** (using Edit):
```
Edit(
file_path="original.py",
old_string="class DatabaseConnection:",
new_string="from database import DatabaseConnection\\n"
)
```
5. **Remove old class from original** (using Edit with empty replacement if needed)
### Example 3: Insert at Specific Line Number
**User:** "Insert this logging code at line 25 in main.py"
**Workflow:**
1. **Validate the target location** (optional but recommended):
```
Read(file_path="main.py", offset=20, limit=10)
```
2. **Use line_insert.py script**:
```bash
python3 skills/code-transfer/scripts/line_insert.py main.py 25 "logger.info('Starting process')\\nlogger.debug('Debug mode enabled')" --backup
```
3. **Verify the insertion**:
```
Read(file_path="main.py", offset=23, limit=5)
```
### Example 4: Reorganize File Into Multiple Modules
**User:** "Split utils.py into separate files for each utility category"
**Workflow:**
1. **Analyze the file structure**:
```
Read(file_path="utils.py")
```
2. **Identify logical groupings** using Grep:
```
Grep(pattern="^def |^class ", path="utils.py", output_mode="content", -n=true)
```
3. **For each category**, extract and create new files:
- Extract string utilities → `Write(file_path="string_utils.py", content=...)`
- Extract file utilities → `Write(file_path="file_utils.py", content=...)`
- etc.
4. **Update original file** to re-export or redirect
## Best Practices
### Planning Before Transferring
Before transferring code:
1. **Understand dependencies**: Check imports, references to other code
2. **Identify scope**: Determine exact start/end of code block
3. **Check target location**: Verify target file structure and appropriate insertion point
4. **Consider imports**: Ensure necessary imports are included
### Preserving Code Context
When transferring code:
- **Include docstrings** and comments
- **Transfer related functions** together if they're interdependent
- **Update imports** in both source and target files
- **Maintain formatting** and indentation
### Validation
After transferring:
1. **Verify insertion**: Read the affected areas to confirm correct placement
2. **Check syntax**: Ensure no syntax errors introduced
3. **Test imports**: Verify that import statements work
4. **Suggest testing**: Recommend running tests if available
### When to Create Backups
Always create backups (`--backup` flag) when:
- Making significant structural changes
- User explicitly requests safety
- Working with critical files
- Operations involve deletion of large code blocks
## Error Handling
### Common Issues and Solutions
**Issue:** "Line number out of range"
- **Solution:** Check file length first with `wc -l` or Read tool
**Issue:** "Indentation errors after insertion"
- **Solution:** Ensure extracted code maintains proper indentation level for target context
**Issue:** "Import errors after transfer"
- **Solution:** Analyze dependencies and add necessary imports to target file
**Issue:** "Code inserted at wrong location"
- **Solution:** Verify line numbers by reading context around insertion point first
## Integration with Other Tools
### Working with Claude's Native Tools
- **Read**: Extract source code (supports line ranges)
- **Edit**: Insert relative to existing content (requires exact string match)
- **Write**: Create new files with transferred code
- **Grep**: Find functions, classes, or patterns across files
- **Bash**: Get file info (`wc -l`), verify syntax (`python -m py_compile`)
### Working with Other Skills
- **code-refactor**: After transferring, refactor code to fit new context
- **test-fixing**: Run tests after reorganizing to ensure nothing broke
- **feature-planning**: Plan large-scale code reorganization before transferring
## Script Details
### line_insert.py
**Purpose:** Insert code at specific line numbers when Edit tool's string matching isn't suitable.
**Key features:**
- 1-based line numbering (line 1 = first line)
- Automatic file creation if target doesn't exist
- Optional timestamped backups
- Multi-line code support
- UTF-8 encoding
**Security:** Basic path validation to prevent directory traversal
**Dependencies:** Python 3.6+ (stdlib only, no external packages needed)
**Output:** Writes to stderr for status messages, making it safe to use with stdout capture
@@ -0,0 +1,188 @@
#!/usr/bin/env python3
"""
Line-based code insertion utility.
This script provides precise line-number-based code insertion,
which complements Claude's native Edit tool (which requires exact string matching).
Usage:
python line_insert.py <file_path> <line_number> <code> [--backup]
Examples:
# Insert at line 10
python line_insert.py src/main.py 10 "print('hello')"
# Insert with backup
python line_insert.py src/main.py 10 "print('hello')" --backup
"""
import argparse
import sys
from pathlib import Path
from datetime import datetime
def validate_file_path(file_path: Path) -> None:
"""
Validate that the file path is safe to use.
Args:
file_path: Path object to validate
Raises:
ValueError: If path is invalid or unsafe
"""
# Resolve to absolute path
abs_path = file_path.resolve()
# Basic security: prevent directory traversal
if ".." in str(file_path):
raise ValueError(f"Path contains '..' which is not allowed: {file_path}")
# Check parent directory exists (or can be created)
if not abs_path.parent.exists():
raise ValueError(f"Parent directory does not exist: {abs_path.parent}")
def create_backup(file_path: Path) -> Path:
"""
Create a backup of the file with timestamp.
Args:
file_path: Path to the file to backup
Returns:
Path to the backup file
"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = file_path.with_suffix(f"{file_path.suffix}.backup_{timestamp}")
if file_path.exists():
backup_path.write_text(file_path.read_text())
print(f"✅ Created backup: {backup_path}", file=sys.stderr)
return backup_path
def insert_code(
file_path: Path,
line_number: int,
code: str,
create_backup_flag: bool = False
) -> None:
"""
Insert code at a specific line number in a file.
Args:
file_path: Path to the target file
line_number: Line number where code should be inserted (1-based)
code: Code to insert (can be multiple lines)
create_backup_flag: Whether to create a backup before modifying
Raises:
ValueError: If line_number is invalid
IOError: If file operations fail
"""
# Validate inputs
validate_file_path(file_path)
if line_number < 1:
raise ValueError(f"Line number must be >= 1, got: {line_number}")
# Create backup if requested and file exists
if create_backup_flag and file_path.exists():
create_backup(file_path)
# Read existing content or start with empty
if file_path.exists():
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
else:
lines = []
print(f"ℹ️ Creating new file: {file_path}", file=sys.stderr)
# Prepare code lines to insert
code_lines = code.splitlines(keepends=True)
# Ensure last line has newline if inserting in middle of file
if code_lines and not code_lines[-1].endswith('\n'):
code_lines[-1] += '\n'
# Insert at the specified line (1-based index)
# Line 1 means insert at the beginning
# Line len(lines)+1 means append at the end
insert_index = line_number - 1
if insert_index > len(lines):
# If line number is beyond file, pad with empty lines
lines.extend(['\\n'] * (insert_index - len(lines)))
# Insert the code
lines[insert_index:insert_index] = code_lines
# Write back to file
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, 'w', encoding='utf-8') as f:
f.writelines(lines)
print(f"✅ Inserted {len(code_lines)} line(s) at line {line_number} in {file_path}", file=sys.stderr)
def main():
"""Main entry point for CLI usage."""
parser = argparse.ArgumentParser(
description="Insert code at a specific line number in a file",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Insert a single line at line 10
%(prog)s src/main.py 10 "print('hello')"
# Insert multiple lines
%(prog)s src/main.py 10 "def foo():\\n pass"
# Insert with backup
%(prog)s src/main.py 10 "print('hello')" --backup
"""
)
parser.add_argument(
'file_path',
type=Path,
help='Path to the target file'
)
parser.add_argument(
'line_number',
type=int,
help='Line number where code should be inserted (1-based)'
)
parser.add_argument(
'code',
type=str,
help='Code to insert (use \\n for newlines)'
)
parser.add_argument(
'--backup',
action='store_true',
help='Create a backup before modifying the file'
)
args = parser.parse_args()
try:
insert_code(
file_path=args.file_path,
line_number=args.line_number,
code=args.code,
create_backup_flag=args.backup
)
sys.exit(0)
except Exception as e:
print(f"❌ Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,393 @@
---
name: file-operations
description: Analyze files and get detailed metadata including size, line counts, modification times, and content statistics. Use when users request file information, statistics, or analysis without modifying files. Activates on phrases like "analyze this file", "get file info", "how many lines", "file statistics", or "show file details".
---
# File Operations
## Overview
Analyze files and retrieve detailed metadata using Claude's native tools. This skill provides convenient workflows for gathering file statistics, comparing files, and analyzing code structure without making modifications.
## When to Use This Skill
Activate this skill when users request:
- **File metadata**: "What's the size of config.json?"
- **Line counts**: "How many lines are in this file?"
- **File comparison**: "Compare the sizes of these two files"
- **Code statistics**: "Analyze the structure of this Python file"
- **File details**: "Show me info about all JavaScript files"
**Activation phrases:**
- "analyze [file]"
- "get file info for [file]"
- "how many lines in [file]"
- "file statistics for [file]"
- "show details of [file]"
- "compare [file1] and [file2]"
## Core Operations
### 1. Get File Size and Modification Time
Use **Bash** commands for quick file metadata:
**Single file info:**
```bash
stat -f "%z bytes, modified %Sm" [file_path]
```
**Multiple files:**
```bash
ls -lh [directory]
```
**File size in human-readable format:**
```bash
du -h [file_path]
```
### 2. Count Lines in Files
**Line count for single file:**
```bash
wc -l [file_path]
```
**Line count for multiple files:**
```bash
wc -l [file1] [file2] [file3]
```
**Total lines in directory:**
```bash
find [directory] -name "*.py" | xargs wc -l
```
### 3. Analyze File Content
Use **Read** tool to analyze structure:
```
Read(file_path="src/app.py")
```
Then analyze the content:
- Count functions/classes
- Identify imports
- Check documentation coverage
- Assess complexity
### 4. Search for Patterns
Use **Grep** to analyze code patterns:
**Count function definitions:**
```
Grep(pattern="^def ", output_mode="count", path="src/")
```
**Find TODOs:**
```
Grep(pattern="TODO|FIXME|XXX", output_mode="content", -n=true)
```
**Count imports:**
```
Grep(pattern="^import |^from .* import", output_mode="count", path="src/")
```
### 5. Find Files by Pattern
Use **Glob** to discover files:
```
Glob(pattern="**/*.py")
```
## Workflow Examples
### Example 1: Comprehensive File Analysis
**User:** "Analyze app.py and tell me about it"
**Workflow:**
1. **Get file size and modification time**:
```bash
stat -f "%z bytes, modified %Sm" app.py
```
2. **Count lines**:
```bash
wc -l app.py
```
3. **Read the file**:
```
Read(file_path="app.py")
```
4. **Analyze structure**:
- Count functions: `Grep(pattern="^def ", output_mode="count", path="app.py")`
- Count classes: `Grep(pattern="^class ", output_mode="count", path="app.py")`
- Find imports: `Grep(pattern="^import |^from ", output_mode="content", -n=true, path="app.py")`
5. **Report findings**:
```
app.py Analysis:
- Size: 15.2 KB
- Lines: 456
- Functions: 12
- Classes: 3
- Imports: 8 modules
- Last modified: 2025-10-20
```
### Example 2: Compare File Sizes
**User:** "Compare the sizes of all Python files in src/"
**Workflow:**
1. **Find all Python files**:
```
Glob(pattern="src/**/*.py")
```
2. **Get sizes for each file**:
```bash
ls -lh src/**/*.py
```
3. **Calculate total size**:
```bash
du -sh src/*.py
```
4. **Present comparison**:
```
Python Files in src/:
- auth.py: 25 KB (largest)
- utils.py: 18 KB
- config.py: 3 KB
- main.py: 12 KB
Total: 58 KB across 4 files
```
### Example 3: Code Quality Metrics
**User:** "Give me code quality metrics for the project"
**Workflow:**
1. **Total line count**:
```bash
find . -name "*.py" -not -path "./venv/*" | xargs wc -l
```
2. **Count test coverage** (test files vs source files):
```bash
find . -name "test_*.py" | wc -l
find . -name "*.py" -not -name "test_*" | wc -l
```
3. **Find TODOs and FIXMEs**:
```
Grep(pattern="TODO|FIXME|HACK|XXX", output_mode="count")
```
4. **Find missing docstrings**:
```
Grep(pattern="^def |^class ", output_mode="content", -n=true, -A=1)
```
(Then analyze which don't have docstrings)
5. **Report metrics**:
```
Code Quality Metrics:
- Total lines of code: 3,456
- Source files: 28
- Test files: 15 (54% coverage by count)
- TODOs/FIXMEs: 12
- Functions without docstrings: 8
```
### Example 4: Find Largest Files
**User:** "What are the largest files in this project?"
**Workflow:**
1. **List all files by size**:
```bash
find . -type f -not -path "./node_modules/*" -not -path "./.git/*" -exec du -h {} + | sort -rh | head -20
```
2. **Identify file types** of largest files
3. **Analyze if large files need refactoring**:
- If source code file > 500 lines, suggest splitting
- If data file, check if it should be externalized
4. **Present findings**:
```
Largest Files:
1. data/dataset.json - 2.3 MB (consider externalizing)
2. src/processor.py - 1,245 lines (suggest refactoring)
3. build/bundle.js - 856 KB (expected for bundle)
```
### Example 5: Directory Structure Analysis
**User:** "Show me the structure of the src/ directory"
**Workflow:**
1. **Use tree command** (if available):
```bash
tree src/ -L 2
```
2. **Or use find**:
```bash
find src/ -type f -o -type d | sort
```
3. **Count files by type**:
```bash
find src/ -name "*.py" | wc -l
find src/ -name "*.js" | wc -l
find src/ -name "*.json" | wc -l
```
4. **Analyze organization**:
- Check for consistent directory structure
- Identify orphaned files
- Note missing documentation
5. **Present structure**:
```
src/ Directory Structure:
├── api/ (8 Python files)
├── models/ (5 Python files)
├── utils/ (12 Python files)
├── tests/ (15 test files)
└── config.json
Total: 40 Python files, 1 config
```
## Best Practices
### Non-Destructive Analysis
This skill should NEVER modify files:
- Use `Read` not `Write`
- Use `stat/ls/wc` not modification commands
- Use `Grep` with `output_mode` not `sed/awk`
### Efficient Information Gathering
**For small files (<100 lines):**
- Read entire file and analyze in context
**For large files (>1000 lines):**
- Use Grep to find specific patterns
- Use `wc -l` for line counts
- Use `head/tail` for quick preview
**For many files:**
- Use Glob to find files first
- Use parallel Bash commands where appropriate
- Summarize rather than showing all details
### Context-Aware Reporting
When reporting file information:
- Include relevant context (e.g., "large for a config file")
- Compare to project averages
- Suggest optimizations if appropriate
- Use human-readable formats
## Integration with Other Tools
### Working with Claude's Native Tools
- **Read**: Read full file content for analysis
- **Grep**: Search patterns, count occurrences
- **Glob**: Find files by pattern
- **Bash**: Execute stat, wc, du, ls, find commands
### Working with Other Skills
- **code-auditor**: For comprehensive codebase analysis
- **code-transfer**: After identifying large files that need splitting
- **codebase-documenter**: For understanding file purposes and relationships
## Common Use Cases
### Development Workflow
**Pre-commit analysis:**
- Check file sizes before committing
- Count lines of new code
- Verify no large files added
**Code review:**
- Compare file versions
- Check complexity metrics
- Identify files needing attention
**Refactoring decisions:**
- Find largest/most complex files
- Identify files with too many responsibilities
- Locate duplicate code patterns
### Project Management
**Progress tracking:**
- Count lines of code over time
- Track test coverage ratios
- Monitor technical debt (TODOs)
**Documentation:**
- Find undocumented files
- Identify missing docstrings
- Check README completeness
## Tool Reference
### Bash Commands for File Operations
**File size:**
- `du -h [file]` - Human-readable size
- `stat -f "%z" [file]` - Exact bytes (macOS)
- `stat -c "%s" [file]` - Exact bytes (Linux)
**Line counts:**
- `wc -l [file]` - Count lines
- `wc -w [file]` - Count words
- `wc -c [file]` - Count bytes
**File info:**
- `stat [file]` - Complete file stats
- `file [file]` - File type
- `ls -lh [file]` - Permissions, size, date
**Find files:**
- `find [dir] -name "pattern"` - Find by name
- `find [dir] -type f -size +1M` - Find large files
- `find [dir] -mtime -7` - Modified in last 7 days
### Grep for Analysis
**Count occurrences:**
```
Grep(pattern="pattern", output_mode="count")
```
**Find with context:**
```
Grep(pattern="pattern", output_mode="content", -n=true, -B=2, -A=2)
```
**Count per file:**
```
Grep(pattern="pattern", output_mode="count", path="dir/")
```