Issue 10 | Batch File Processing and Refactoring Power Tool

Updated on 4/5/2026

🎯 Learning Objectives

By the end of this issue, you will master:

  1. Command writing techniques for cross-file batch refactoring
  2. How to make Claude perform large-scale code migration using Glob + Read + Edit
  3. Application of Subagents in parallel refactoring
  4. Safety strategies for isolated refactoring with Git Worktree

📖 Core Concepts Explained

10.1 Three Modes of Batch Refactoring

Mode 1: Sequential Refactoring
  Claude opens files one by one and modifies them sequentially
  Suitable for: Up to 10 files
  Characteristics: Slow but precise

Mode 2: Subagent Parallel
  Claude launches multiple subagents (TaskCreate), each processing different files
  Suitable for: A large number of independent files
  Characteristics: Fast, but each subagent has a smaller context

Mode 3: Worktree Isolation (Git Worktree)
  Execute refactoring in a new Worktree branch
  Suitable for: High-risk refactoring (can roll back an entire branch at any time)
  Characteristics: Safest, does not affect the main branch

10.2 Refactoring Toolchain

Typical refactoring tool call chain:

Glob("**/*.ts")          → Discover all target files
  │
Grep("oldImport" in **)  → Locate files that need modification
  │
Read(file1.ts)           → Read file to understand context
  │
Edit(file1.ts)           → Precise modification
  │
Bash("npm run lint")     → Verify modifications for no syntax errors
  │
Bash("npm test")         → Run tests to confirm no regressions

💻 Simulate Claude TUI Interaction

Scenario 1: Batch Migration of Import Paths

> Our project changed from @/utils to @/lib/utils.
  Please update all import paths in all files.

╭─ Claude ─────────────────────────────────────────────╮
│                                                      │
│  🔍 Tool: Grep ("from '@/utils" across src/**)      │
│  → Found 23 files with matching imports              │
│                                                      │
│  📋 Affected files list:                             │
│  1. src/components/UserCard.tsx                      │
│  2. src/components/DataTable.tsx                     │
│  3. src/hooks/useAuth.ts                             │
│  4. src/api/routes/users.ts                          │
│  ... Total 23 files                                  │
│                                                      │
│  I will modify the import paths in these files one by one.│
│                                                      │
│  ⚙️ Tool: Edit → src/components/UserCard.tsx         │
│  ╭─ DIFF ─────────────────────────────────────╮      │
│  │ - import { formatDate } from '@/utils';     │      │
│  │ - import { cn } from '@/utils/classnames';  │      │
│  │ + import { formatDate } from '@/lib/utils'; │      │
│  │ + import { cn }                             │      │
│  │ +   from '@/lib/utils/classnames';          │      │
│  ╰─────────────────────────────────────────────╯      │
│                                                      │
│  ⚙️ Tool: Edit → src/components/DataTable.tsx        │
│  ✅ Updated (1 import changed)                       │
│                                                      │
│  ⚙️ Tool: Edit → src/hooks/useAuth.ts               │
│  ✅ Updated (2 imports changed)                      │
│                                                      │
│  ... (Processing all 23 files one by one)            │
│                                                      │
│  ⚙️ Tool: Bash                                       │
│  $ npx tsc --noEmit                                  │
│  ✅ No errors found                                  │
│                                                      │
│  ⚙️ Tool: Bash                                       │
│  $ npm test                                          │
│  ✅ 147 tests passed, 0 failed                       │
│                                                      │
│  🎉 All 23 files updated!                            │
│  TypeScript compiled successfully, all tests passed. │
│                                                      │
╰──────────────────────────────────────────────────────╯

Scenario 2: Using Git Worktree to Isolate High-Risk Refactoring

> Refactor all class components to function components.
  This is a major change, please do it on an isolated branch.

╭─ Claude ─────────────────────────────────────────────╮
│                                                      │
│  Okay, I'll first create a Git Worktree to isolate this refactoring.│
│                                                      │
│  ⚙️ Tool: EnterWorktree                              │
│  Branch: refactor/class-to-function                  │
│  Path: ../my-project-worktree-refactor               │
│  ✅ Worktree created and switched                    │
│                                                      │
│  Now I'm working on the isolated branch, the main branch is unaffected.│
│                                                      │
│  🔍 Tool: Grep ("extends Component\|extends          │
│           React.Component" across src/**)             │
│  → Found 8 class components                          │
│                                                      │
│  📋 Components to refactor:                          │
│  1. src/components/Header.tsx (47 lines)             │
│  2. src/components/Sidebar.tsx (92 lines)            │
│  3. src/components/Modal.tsx (65 lines)              │
│  ... Total 8 components                              │
│                                                      │
│  Starting refactoring one by one...                  │
│                                                      │
│  ⚙️ Tool: Read → src/components/Header.tsx           │
│  ⚙️ Tool: Edit → src/components/Header.tsx           │
│  ╭─ DIFF (Summary) ──────────────────────────╮       │
│  │ - class Header extends React.Component {   │       │
│  │ -   state = { isOpen: false };              │       │
│  │ -   render() { ... }                        │       │
│  │ + export function Header() {                │       │
│  │ +   const [isOpen, setIsOpen] =             │       │
│  │ +     useState(false);                      │       │
│  │ +   return ( ... );                         │       │
│  │ + }                                         │       │
│  ╰─────────────────────────────────────────────╯      │
│  ✅ Header: class → function ✓                       │
│                                                      │
│  ... (Processing all 8 components one by one)        │
│                                                      │
│  ⚙️ Tool: Bash                                       │
│  $ npm test                                          │
│  ✅ All 147 tests passed                             │
│                                                      │
│  ⚙️ Tool: Bash                                       │
│  $ git add -A && git commit -m                       │
│    "refactor: convert 8 class components             │
│     to function components"                          │
│  ✅ Committed                                        │
│                                                      │
│  ⚙️ Tool: ExitWorktree                               │
│  ✅ Back to main branch                              │
│                                                      │
│  🎉 Refactoring complete! Results are on branch      │
│  'refactor/class-to-function'.                       │
│  You can code review and decide whether to merge.    │
│                                                      │
╰──────────────────────────────────────────────────────╯

💻 Code Demo: Batch Processing Command Line Usage

# ✅ Batch Replace (Print Mode)
claude -p "Replace all console.log with structured logger in the project"

# ✅ Batch Add Error Handling
claude -p "Add try-catch to all route handler functions under src/routes/"

# ✅ Batch Add Type Annotations
claude -p "Add TypeScript type annotations to all functions under src/utils/"

# ✅ Code Modernization Migration
claude -p "Change all CommonJS require() to ES Module import"

# ✅ API Version Migration
claude -p "Change all axios calls to use fetch API"

Using Subagents for Parallel Processing

# Define refactoring subagent in CLAUDE.md
cat > .claude/agents/refactor-agent.md << 'EOF'
---
description: "Handles file-level refactoring tasks. Use when
  asked to refactor, migrate, or transform code across
  multiple files."
allowed_tools:
  - Read
  - Edit
  - Glob
  - Grep
  - Bash
---

# Refactoring Agent

## Instructions
1. Read the target file
2. Apply the requested transformation
3. Run `npx tsc --noEmit` to verify
4. Report success or failure
EOF

🔧 Involved Tools

Tool Refactoring Stage Purpose
Glob Discovery Find all files that need modification
Grep Locating Search for code patterns to replace
Read Understanding Read file content to understand context
Edit Modification Precisely edit specific lines
Bash Verification Run tsc, tests, lint
EnterWorktree Isolation Create Git Worktree
ExitWorktree Reversion Exit Worktree
TaskCreate Parallelization Create subtasks for parallel processing

📝 Key Takeaways from this Issue

  1. Batch refactoring follows the Discovery → Locating → Understanding → Modification → Verification process
  2. For small-scale refactoring (<10 files), Sequential Mode is sufficient
  3. For high-risk refactoring, prioritize using Git Worktree for isolation
  4. After each modification, run tests to ensure no regressions
  5. Use --allowedTools to restrict to Edit only, preventing accidental execution of dangerous commands

🔗 References