The user wants a "repo-wide migration assistant" that incorporates three key components:
Codemods: Scripts to automate code transformations.
Review Bots: Automation to check code during the review process (e.g., Pull Requests).
Guardrails: Preventing regressions or enforcing rules in the CI/CD pipeline or via linting.
The context is likely a large-scale refactoring or migration project (e.g., upgrading a framework version, moving from one library to another, changing API patterns).
I need to design a system or a toolkit that enables this. I cannot implement the specific logic for a specific migration (since the user didn't specify what is being migrated), but I must provide the infrastructure and framework for users to define their own migration rules.
Scope & Architecture:
Language/Stack: I'll assume a generic TypeScript/JavaScript ecosystem (most common for this kind of tooling), but keep concepts general. AST (Abstract Syntax Tree) manipulation is central here.
Component 1: Codemods. I'll use jscodeshift as the industry standard runner. I need to provide a wrapper or a helper to make writing these easier and maybe a CLI runner.
Component 2: Review Bots. This usually involves a GitHub Action or a bot (like DangerJS or a custom GitHub App) that comments on PRs if it spots anti-patterns or if a codemod needs to be applied.
Component 3: Guardrails. This refers to ESLint rules (custom or configured) and ts-morph scripts to enforce types or presence of code. It also includes CI checks.
Drafting the Solution - "MigrateMate" (Hypothetical Name):
Core Logic: A "Rule Registry". Each migration step is a rule.
Codemod Implementation: A wrapper around jscodeshift that reads from the registry.
Linting/Guardrails: A custom ESLint plugin that reads from the registry (using the same logic pattern but for detection, not modification).
Bot Implementation: A script (e.g., for GitHub Actions) that runs the detection logic and posts comments.
Step-by-Step Implementation Plan:
Project Structure: A monorepo structure or a folder structure within a repo.
The "Registry" (config): A central place to list what is being migrated (e.g., "Remove Lodash", "Upgrade React").
Codemods: Provide a template for a jscodeshift transform.
Guardrails (ESLint): Show how to write a custom rule that prevents the old code and suggests the new code.
Review Bot: A script using Octokit (GitHub API) to scan PRs.
Refining the implementation details:
Scenario: Let's use a concrete example to make the code understandable. Migration: moment.js -> date-fns. This is a classic, complex migration scenario.
Codemod: Find import moment from 'moment' and moment().format() -> format(new Date()).
Guardrail: Lint rule that bans import moment.
Bot: If the PR adds moment, warn them.
Code Structure for the Output:
I will provide a comprehensive Python/Node toolkit structure. Let's stick to Node.js/TypeScript because the tooling (jscodeshift, eslint, octokit) is best there.
Directory:migration-toolkit/
1. The Codemod Engine:transforms/ folder.
2. The Guardrails:eslint-rules/ folder.
3. The Review Bot:scripts/pr-bot.ts.
4. CI Integration: Example GitHub Actions workflow.
Self-Correction during thought process:
Writing a full bot server is too complex for a single prompt. I should implement the Review Bot as a "CI Check script" that can be run inside a GitHub Action. It's stateless and easier to deploy. It essentially acts as a "Diff Linter".
Let's ensure the distinction between "Guardrails" and "Review Bot" is clear.
Guardrails: Static Analysis (ESLint/Typescript strict mode). Runs locally and in CI.
Review Bot: Analyzes the diff specifically. "You are adding bad code here."
Final Output Structure:
Overview: Explain the architecture.
Part 1: Codemods (The Offense):jscodeshift setup.
Part 2: Guardrails (The Defense): Custom ESLint rule.
Part 3: Review Bot (The Enforcer): GitHub Action script.
Usage: How to put it together.
Let's write the code. I will use a moment.js to date-fns migration as the illustrative example, but keep the framework generic.
Code details:
Codemod: Use jscodeshift. Detect moment(...).
ESLint: Create a rule no-moment-js.
Bot: Use @actions/core and @actions/github.
Let's add a "Migration Dashboard" concept (optional)? No, keep it practical. Just the tooling.
Let's refine the Review Bot logic:
It shouldn't just run the linter. It should ideally run the codemod in dry-run mode. If the codemod finds changes, the bot comments: "Hey, it looks like you are using old code. Run npm run migrate to fix this."
That is a powerful workflow.
Dev commits code using old API.
CI starts.
Bot (Dry Run Codemod) detects old API.
Bot comments on PR with instructions or posts a diff.
Guardrails (ESLint) fail the build if strictness is required.
I will structure the response as a "Migration Toolkit" implementation.
Detailed Implementation Steps:
Setup: Dependencies.
The Codemod (jscodeshift): The script to rewrite code.
The Guardrail (Custom ESLint): The rule to ban old code.
The Review Bot (GitHub Action): The script to scan PRs.
Orchestration: The configuration file holding the migration state.
Let's execute.
Implementing a repo-wide migration requires a three-layered strategy: Automated Transformation (Codemods), Continuous Enforcement (Guardrails), and Process Integration (Review Bots).
Below is a complete implementation framework called "MigrateOps". It uses a standard Node.js/TypeScript ecosystem, which is the industry standard for handling Abstract Syntax Trees (AST) manipulation across multiple languages.
Architecture Overview
The Codemod Engine: Uses jscodeshift to programmatically rewrite code.
The Guardrails: A custom ESLint plugin to prevent regressions (e.g., "Don't use the old API anymore").
The Review Bot: A CI script that runs on Pull Requests to detect unmigrated code and posts comments.
Phase 1: The Codemod Engine
We will create a transformation script to automate the heavy lifting. We'll use a hypothetical migration: Replacing moment.js with date-fns.
2. The Transform Script (transforms/moment-to-date-fns.js)
This script parses the AST, finds moment() calls, and replaces them with format(new Date()).
javascript
// transforms/moment-to-date-fns.js
module.exports = function(fileInfo, api, options) {
const j = api.jscodeshift;
const root = j(fileInfo.source);
// Track imports needed
let needsFormat = false;
let needsToDate = false;
// 1. Replace Usage: moment(date).format('YYYY-MM-DD') -> format(date, 'yyyy-MM-dd')
root.find(j.CallExpression, {
callee: {
type: 'MemberExpression',
object: { name: 'moment' },
property: { name: 'format' }
}
}).forEach(path => {
const args = path.node.arguments;
// moment format strings differ from date-fns
// This is a naive replacement for demo purposes
const formatArg = args[0] || j.literal('yyyy-MM-dd');
// Replace the node with the new date-fns structure
// Assuming the moment object was the first arg of the parent call
// In real life, you'd trace the variable binding
j(path.parent).replaceWith(
j.callExpression(
j.identifier('format'),
[args[0], formatArg]
)
);
needsFormat = true;
});
// 2. Update Imports
if (needsFormat) {
// Remove old moment import
root.find(j.ImportDeclaration, { source: { value: 'moment' } }).remove();
// Add new date-fns import (prepend to file)
const importStatement = j.importDeclaration(
[j.importSpecifier(j.identifier('format'))],
j.literal('date-fns')
);
root.get().node.program.body.unshift(importStatement);
}
return root.toSource();
};
Execution:
bash
# Run across the entire src folder
npx jscodeshift -t transforms/moment-to-date-fns.js src/ --extensions=js,ts
Phase 2: The Guardrails (Eslint Plugin)
Codemods handle the existing code, but guardrails prevent developers from writing new "legacy" code or committing unmigrated code.
1. The Custom Rule (guards/no-moment.js)
This rule bans imports of the library we just migrated away from.
javascript
// guards/no-moment.js
module.exports = {
meta: {
type: 'problem',
docs: { description: 'Prevent usage of moment.js - use date-fns instead' },
messages: {
unexpectedImport: 'moment.js is deprecated in this repo. Use date-fns.'
}
},
create(context) {
return {
ImportDeclaration(node) {
if (node.source.value === 'moment') {
context.report({
node,
messageId: 'unexpectedImport',
});
}
},
CallExpression(node) {
// Catch require('moment')
if (
node.callee.name === 'require' &&
node.arguments[0] &&
node.arguments[0].value === 'moment'
) {
context.report({
node,
messageId: 'unexpectedImport',
});
}
}
};
}
};
2. Configuration (.eslintrc.js)
Wire up the custom rule.
javascript
module.exports = {
plugins: ['local-rules'], // Assumes you set up eslint-plugin-local-rules
rules: {
'local-rules/no-moment': 'error',
}
};
Phase 3: The Review Bot
This script runs in CI (GitHub Actions, GitLab CI). It runs the linter and potentially the codemod in "dry-run" mode to see if the developer forgot to run the migration.
The Bot Script (bot/pr-scanner.js)
javascript
// bot/pr-scanner.js
const { execSync } = require('child_process');
const chalk = require('chalk'); // npm install chalk
console.log('🤖 Migration Bot Scanning PR...');
try {
// 1. Run Guardrails (Linting)
console.log('Checking for banned patterns...');
execSync('npx eslint src/ --format json --output-file lint-results.json', { stdio: 'inherit' });
} catch (error) {
console.log(chalk.red('Guardrails failed! Check lint-results.json.'));
// In a real CI environment, you would parse lint-results.json here
// and post a comment to the PR using the GitHub API.
process.exit(1);
}
// 2. Check for drift (Run Codemod in dry-run)
console.log('Checking for unmigrated code patterns...');
try {
// jscodeshift throws if it finds nothing to change? No, usually returns count.
// We can use a simple grep or a dry-run flag logic here.
// For this demo, we'll simulate checking for 'moment' string.
const result = execSync('grep -r "from \'moment\'" src/', { encoding: 'utf-8' });
if (result) {
console.log(chalk.yellow('⚠️ Unmigrated code found!'));
console.log('Please run: npx jscodeshift -t transforms/moment-to-date-fns.js src/');
// Exit with error to block the PR merge
process.exit(1);
}
} catch (e) {
// Grep returns exit code 1 if no matches, which is good here.
console.log(chalk.green('✅ No unmigrated patterns found.'));
}
name: Migration Bot
on: [pull_request]
jobs:
check-migration:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm ci
- name: Run Migration Assistant
run: node bot/pr-scanner.js
Operational Strategy
To implement this effectively in a large organization:
Codemod Strategy (The "Surgical Strike"):
Write the transform.
Run it on a single "pilot" team/package first.
Refine the transform based on edge cases (e.g., mocked dates in tests).
Run it repo-wide via a scripted PR.
Guardrail Strategy (The "Moat"):
Deploy the custom ESLint rules immediately.
Set them to warn for 1 week.
Flip the switch to error.
This ensures that even if the Codemod missed a file, no new legacy code enters the repo.
Review Bot Strategy (The "Gatekeeper"):
The Bot provides the "Self-Service" aspect.
Instead of a human reviewer saying "Please migrate this," the Bot comments on the PR automatically, giving the developer the exact command to run to fix the issue.