Przejdź do głównej zawartości

Batch Operations

Ta treść nie jest jeszcze dostępna w Twoim języku.

When you need to transform hundreds of files, migrate entire codebases, or apply systematic changes across multiple services, Claude Code becomes a force multiplier. This guide reveals advanced patterns for orchestrating large-scale code transformations that would take days manually but can be completed in hours with the right approach.

Batch operations in Claude Code follow a different paradigm than interactive development:

Batch Operation Principles

  • Systematic over ad-hoc: Define patterns once, apply everywhere
  • Verification at scale: Automated testing for every change
  • Incremental progress: Break large migrations into checkpointable steps
  • Rollback ready: Every batch operation should be reversible
  • Pattern-based: Use consistent approaches across similar transformations

Recognize scenarios that benefit from batch processing:

  • Framework migrations: React 16 → 18, Vue 2 → 3, Angular updates
  • API contract changes: Updating all consumers of a modified API
  • Linting rule enforcement: Applying new standards across entire codebase
  • Dependency updates: Handling breaking changes in core libraries
  • Code modernization: ES5 → ES6+, callback → async/await patterns
  • Cross-service refactoring: Renaming entities used across microservices

The foundation of most batch operations is systematic task generation:

Terminal window
> Analyze the codebase and create migration-tasks.md listing:
- All React class components that need conversion to hooks
- Current file path and component name
- Estimated complexity (simple/medium/complex)
- Dependencies on other components
Sort by dependency order so we can migrate bottom-up

Claude generates a structured task list:

# React Hooks Migration Tasks
## Simple Components (no state, pure render)
1. components/ui/Button.jsx - Button
2. components/ui/Label.jsx - Label
...
## Medium Components (local state only)
10. components/forms/TextInput.jsx - TextInput
11. components/forms/Checkbox.jsx - Checkbox
...
## Complex Components (context, refs, lifecycle)
25. components/auth/LoginForm.jsx - LoginForm (uses AuthContext)
26. components/data/DataTable.jsx - DataTable (complex lifecycle)
...

Transform the task list into executable batches:

Terminal window
> For each component in migration-tasks.md marked "simple":
1. Convert to functional component with hooks
2. Run component tests
3. If tests pass, commit with message "refactor: convert [name] to hooks"
4. Update the task list marking complete
5. If tests fail, log error and skip to next
Start with the first 5 simple components

Build verification into every batch operation:

Terminal window
> For each migrated component:
1. Generate snapshot tests if missing
2. Run existing tests
3. Compare bundle size before/after
4. Check for console errors
5. Only proceed if all checks pass

Leverage multiple Claude instances for truly parallel execution:

Terminal window
# Terminal 1: Handle simple components
$ claude
> Process all "simple" components from migration-tasks.md
# Terminal 2: Handle medium components
$ claude
> Process all "medium" components from migration-tasks.md
# Terminal 3: Update documentation
$ claude
> As components are migrated, update their documentation
# Terminal 4: Monitor and coordinate
$ claude
> Monitor git log, ensure no conflicts, track overall progress

For risky large-scale changes, use feature flags and incremental rollout:

Terminal window
> Implement dual-mode support for authentication:
1. Add feature flag USE_NEW_AUTH
2. Wrap old auth code in if (!USE_NEW_AUTH)
3. Implement new auth in else block
4. Both paths must pass all tests
5. Deploy with flag off, test in production
6. Gradually enable for more users
7. Once stable, remove old code
Start with auth/login.js

Coordinate changes across multiple repositories:

Terminal window
# Create a coordination script
> Generate cross-repo-update.sh that:
1. Lists all repos needing updates
2. For each repo:
- Clone if not present
- Create branch 'update-api-contract'
- Run claude with same prompt
- Commit changes
- Push branch
3. Generate summary of all changes
4. Create PR links document
  1. Analysis Phase

    Terminal window
    > Analyze our Express app and create a migration plan to Fastify:
    - List all middleware used
    - Identify Express-specific patterns
    - Find Fastify equivalents
    - Estimate effort per module
  2. Compatibility Layer

    Terminal window
    > Create express-compat.js that:
    - Wraps Fastify to support Express middleware
    - Provides req/res compatibility
    - Allows gradual migration
  3. Route Migration

    Terminal window
    > For each route file in routes/:
    1. Convert Express router to Fastify plugin
    2. Update middleware to Fastify hooks
    3. Adjust request/response handling
    4. Maintain same API contract
    5. Test with existing integration tests
  4. Middleware Migration

    Terminal window
    > Convert Express middleware to Fastify plugins:
    - Authentication preHandler hook
    - Error handling error handler
    - Body parsing built-in support
    - Static files @fastify/static
  5. Cleanup Phase

    Terminal window
    > Once all routes migrated:
    1. Remove Express dependencies
    2. Remove compatibility layer
    3. Optimize Fastify-specific features
    4. Update documentation

When changing a widely-used API:

Terminal window
> We need to rename 'customerId' to 'clientId' across 10 services.
Phase 1 - Add backward compatibility:
For each service:
1. Add 'clientId' field alongside 'customerId'
2. Log deprecation warning when 'customerId' used
3. Update internal code to use 'clientId'
4. Deploy with both fields supported
Phase 2 - Update consumers:
For each consuming service:
1. Update to send/expect 'clientId'
2. Remove 'customerId' usage
3. Test integration
4. Deploy
Phase 3 - Remove deprecated field:
For each service:
1. Remove 'customerId' support
2. Remove deprecation warnings
3. Final testing
4. Deploy

Managing complex schema changes:

Terminal window
> Migrate from single 'address' field to structured address:
1. Add new columns (keep old):
- street_address
- city
- state
- postal_code
- country
2. Create migration script:
- Parse existing address data
- Populate new fields
- Handle edge cases
- Log unparseable addresses
3. Update application code:
- Add new fields to models
- Dual-write to both old and new
- Update queries gradually
4. Verify and switch:
- Compare old vs new data
- Switch reads to new fields
- Stop writing to old field
5. Cleanup:
- Remove old column
- Remove dual-write code

Leverage Claude’s headless mode for scripted transformations:

batch-refactor.sh
#!/bin/bash
# Generate file list
find src -name "*.js" -type f > files-to-process.txt
# Process each file
while IFS= read -r file; do
echo "Processing $file..."
claude -p "In $file, convert all var to const/let based on usage. \
Use const for never-reassigned, let for reassigned. \
Preserve all functionality." \
--allowedTools Edit \
--quiet
# Run quick test
if npm test -- --findRelatedTests "$file" > /dev/null 2>&1; then
git add "$file"
git commit -m "refactor: modernize variable declarations in $file"
else
echo "Tests failed for $file, skipping"
git checkout -- "$file"
fi
done < files-to-process.txt

For massive parallel operations:

fan-out-migration.sh
> Create a fan-out script for processing 1000+ components:
#!/bin/bash
# Split tasks into chunks
split -l 50 migration-tasks.txt chunk-
# Process chunks in parallel
for chunk in chunk-*; do
(
claude -p "Process all components listed in $chunk following the migration guide. \
Log progress to $chunk.log" \
--allowedTools Edit Bash View \
> "$chunk.output" 2>&1
) &
done
# Wait for all background jobs
wait
# Combine results
cat chunk-*.log > migration-complete.log

Configure hooks for consistent processing:

.claude/hooks.mjs
{
"hooks": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "prettier --write \"$CLAUDE_FILE_PATHS\""
},
{
"type": "command",
"command": "eslint --fix \"$CLAUDE_FILE_PATHS\""
}
]
},
{
"matcher": "PostBatch",
"hooks": [
{
"type": "command",
"command": "npm test -- --coverage"
}
]
}
]
}

Create restoration points during batch operations:

Terminal window
> Before starting the migration:
1. Create git tag 'pre-migration-backup'
2. Generate file checksums: find . -type f -exec md5sum {} \; > pre-migration.md5
3. Backup critical configs
4. Document current working state
After each major milestone:
1. Commit with descriptive message
2. Tag with 'migration-checkpoint-N'
3. Run full test suite
4. Update progress log

Rollback Procedures

Terminal window
# Quick rollback to last checkpoint
git reset --hard migration-checkpoint-3
# Full rollback with cleanup
git checkout pre-migration-backup
rm -rf node_modules package-lock.json
npm install
npm test
# Selective rollback
git checkout pre-migration-backup -- src/components/
git commit -m "revert: rollback component migration"

When batch operations fail:

Terminal window
> Analyze the migration failure:
1. Read error logs from failed-migrations.log
2. Identify common patterns in failures
3. Suggest fixes for the migration script
4. Create recovery plan for partially migrated state
> Generate recovery script that:
1. Identifies partially migrated files
2. Completes or reverts each file
3. Ensures consistent state
4. Re-runs affected tests

Optimize for efficiency at scale:

❌ Token-Heavy Approach

Terminal window
"Analyze the entire codebase and
convert all components to TypeScript"
# Loads everything into context

✅ Token-Efficient Approach

Terminal window
"Convert user.js to TypeScript
following patterns in types.md"
# Focused context per file

Find the sweet spot for your operations:

Terminal window
# Test different batch sizes
> Process migration in batches of:
- 10 files: measure time and success rate
- 25 files: measure time and success rate
- 50 files: measure time and success rate
Recommend optimal batch size based on:
- Token usage per batch
- Error rate
- Total completion time

Create comprehensive progress reporting:

Terminal window
> Generate migration-dashboard.html that shows:
- Total files: 500
- Completed: 350 (70%)
- Failed: 12 (2.4%)
- Skipped: 38 (7.6%)
- Remaining: 100 (20%)
Include:
- Success rate by component type
- Common failure reasons
- Estimated completion time
- Test coverage changes

Before launching any batch operation:

  • Create comprehensive backups
  • Test on small subset first
  • Set up progress monitoring
  • Prepare rollback procedures
  • Document expected outcomes
  • Notify affected teams
  • Schedule during low-traffic periods
  • Have manual intervention plan

Continue mastering Claude Code with:

Remember: Batch operations amplify both successes and failures. Start small, verify thoroughly, and scale gradually. With Claude Code’s systematic approach, you can transform codebases that would take teams weeks to update manually.