An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): improve upgrade codemod version detection and CI support (#868)
Cindy Zhangb530876cde22
diff --git a/packages/cli/src/codemods/ensure-jscodeshift.mjs b/packages/cli/src/codemods/ensure-jscodeshift.mjsindex fb6e57bffc..1816df8ce1 100644--- a/packages/cli/src/codemods/ensure-jscodeshift.mjs+++ b/packages/cli/src/codemods/ensure-jscodeshift.mjs@@ -3,17 +3,43 @@** Checks if jscodeshift is available and offers to install it on-demand.* Keeps the CLI lean — jscodeshift is only needed for codemods.+ *+ * In non-interactive environments (CI, LLM agents), the interactive prompt+ * is skipped. Pass `installDeps: true` to auto-install without prompting,+ * or the command will fail with a helpful error message.*/import {execSync} from 'node:child_process';import * as p from '@clack/prompts';-export async function ensureJscodeshift() {+/**+ * @param {object} [options]+ * @param {boolean} [options.installDeps] - Auto-install without prompting+ */+export async function ensureJscodeshift({installDeps = false} = {}) {try {await import('jscodeshift');return true;} catch {p.log.warn('jscodeshift is required for codemods but not installed.');++ const isInteractive = process.stdout.isTTY && !process.env.CI;++ if (installDeps) {+ // Explicit opt-in — install without prompting+ return installJscodeshift();+ }++ if (!isInteractive) {+ // Non-interactive environment — fail fast with a helpful message+ p.log.error(+ 'Cannot run codemods without jscodeshift. ' ++ 'Use --install-deps to auto-install in non-interactive environments.',+ );+ return false;+ }++ // Interactive TTY — prompt as beforeconst shouldInstall = await p.confirm({message: 'Install jscodeshift now?',initialValue: true,@@ -22,14 +48,19 @@ export async function ensureJscodeshift() {p.log.error('Cannot run codemods without jscodeshift.');return false;}- try {- p.log.step('Installing jscodeshift...');- execSync('npm install --no-save jscodeshift', {stdio: 'pipe'});- p.log.success('jscodeshift installed.');- return true;- } catch (err) {- p.log.error(`Failed to install jscodeshift: ${err.message}`);- return false;- }+ return installJscodeshift();+ }+}++/** @returns {boolean} */+function installJscodeshift() {+ try {+ p.log.step('Installing jscodeshift...');+ execSync('npm install --no-save jscodeshift', {stdio: 'pipe'});+ p.log.success('jscodeshift installed.');+ return true;+ } catch (err) {+ p.log.error(`Failed to install jscodeshift: ${err.message}`);+ return false;}}diff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjsindex c61fa985dc..46137515cf 100644--- a/packages/cli/src/codemods/runner.mjs+++ b/packages/cli/src/codemods/runner.mjs@@ -72,6 +72,7 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codemlet totalFilesChanged = 0;let totalTransformsApplied = 0;+ const errors = [];for (const {version, transforms} of versionManifests) {p.log.step(`Applying v${version} codemods...`);@@ -86,25 +87,40 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codemlet filesChanged = 0;for (const filePath of files) {- const source = fs.readFileSync(filePath, 'utf-8');- const api = {jscodeshift, stats: () => {}, report: () => {}};- const file = {source, path: filePath};-- const result = transform(file, api);-- if (result != null && result !== source) {- filesChanged++;- totalFilesChanged++;- totalTransformsApplied++;-- const relativePath = path.relative(process.cwd(), filePath);-- if (apply) {- fs.writeFileSync(filePath, result, 'utf-8');- p.log.success(` ✓ ${relativePath}`);- } else {- p.log.warn(` ~ ${relativePath} (would change)`);+ const relativePath = path.relative(process.cwd(), filePath);++ try {+ const source = fs.readFileSync(filePath, 'utf-8');+ // Configure parser based on file extension+ const parser = filePath.endsWith('.tsx')+ ? 'tsx'+ : filePath.endsWith('.jsx')+ ? 'babel'+ : 'babel';+ const api = {+ jscodeshift: jscodeshift.withParser(parser),+ stats: () => {},+ report: () => {},+ };+ const file = {source, path: filePath};++ const result = transform(file, api);++ if (result != null && result !== source) {+ filesChanged++;+ totalFilesChanged++;+ totalTransformsApplied++;++ if (apply) {+ fs.writeFileSync(filePath, result, 'utf-8');+ p.log.success(` ✓ ${relativePath}`);+ } else {+ p.log.warn(` ~ ${relativePath} (would change)`);+ }}+ } catch (err) {+ p.log.error(` ✗ ${relativePath} — ${err.message}`);+ errors.push({file: relativePath, codemod: name, error: err.message});}}@@ -117,12 +133,25 @@ export async function runCodemods(versionManifests, {apply, path: srcPath, codem// Summaryconsole.log('');- if (totalFilesChanged === 0) {++ if (errors.length > 0) {+ p.log.error(+ `${errors.length} error${errors.length === 1 ? '' : 's'} during codemods:`,+ );+ for (const {file, codemod: cm, error} of errors) {+ p.log.error(` ${cm} → ${file}: ${error}`);+ }+ }++ if (totalFilesChanged === 0 && errors.length === 0) {p.log.success('No changes needed — your code is already up to date!');} else if (apply) {p.log.success(`Done! Applied ${totalTransformsApplied} change${totalTransformsApplied === 1 ? '' : 's'} across ${totalFilesChanged} file${totalFilesChanged === 1 ? '' : 's'}.`,);+ if (errors.length > 0) {+ p.log.warn('Some files had errors — review them manually.');+ }p.log.info('Run your type checker and tests to verify the changes.');} else {p.log.warn(diff --git a/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs b/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjsindex 1b536fcbd1..b390aa1f1b 100644--- a/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.6/migrate-shadow-tokens.mjs@@ -99,9 +99,8 @@ export default function transformer(file, api) {});root.find(j.Identifier).forEach((path) => {- const newName = IDENTIFIER_MAP[path.node.name];- if (newName) {- path.node.name = newName;+ if (Object.hasOwn(IDENTIFIER_MAP, path.node.name)) {+ path.node.name = IDENTIFIER_MAP[path.node.name];hasChanges = true;}});diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjsindex a565d82b4b..226c75c6f6 100644--- a/packages/cli/src/commands/upgrade.mjs+++ b/packages/cli/src/commands/upgrade.mjs@@ -5,10 +5,13 @@* all codemods needed to migrate to the target version.** Options:- * --apply Write changes to disk (default: dry-run)- * --to <version> Target version (default: latest in registry)- * --codemod <name> Run a specific transform only- * --path <dir> Source directory (default: ./src)+ * --apply Write changes to disk (default: dry-run)+ * --from <version> Previous version (overrides package.json detection)+ * --to <version> Target version (default: latest in registry)+ * --force Run codemods even if versions appear up to date+ * --codemod <name> Run a specific transform only (skips version check)+ * --path <dir> Source directory (default: ./src)+ * --install-deps Auto-install jscodeshift without prompting (for CI/LLM)*/import * as fs from 'node:fs';@@ -63,9 +66,12 @@ export function registerUpgrade(program) {.command('upgrade').description('Run codemods to migrate between XDS versions').option('--apply', 'Write changes to disk (default: dry-run)', false)+ .option('--from <version>', 'Previous version (overrides package.json detection)').option('--to <version>', 'Target version', latestVersion)+ .option('--force', 'Run codemods even if versions appear up to date', false).option('--codemod <name>', 'Run a specific transform only').option('--path <dir>', 'Source directory to scan', './src')+ .option('--install-deps', 'Auto-install jscodeshift without prompting', false).option('--list', 'List available codemods', false).action(async (options) => {p.intro('XDS Upgrade');@@ -77,11 +83,15 @@ export function registerUpgrade(program) {return;}- // Detect current version- const currentVersion = detectCurrentVersion();- if (!currentVersion) {+ // When --codemod is specified, skip version detection entirely —+ // the user asked for a specific transform, just run it.+ const skipVersionCheck = !!options.codemod;++ // Detect current version (--from overrides package.json)+ const currentVersion = options.from ?? detectCurrentVersion();+ if (!currentVersion && !skipVersionCheck) {p.log.error(- 'Could not detect @xds/core version. Make sure package.json is in the current directory.',+ 'Could not detect @xds/core version. Make sure package.json is in the current directory, or use --from <version>.',);p.outro('Aborted');process.exitCode = 1;@@ -89,18 +99,22 @@ export function registerUpgrade(program) {}const targetVersion = options.to;- p.log.info(`Current version: ${currentVersion}`);- p.log.info(`Target version: ${targetVersion}`);- if (currentVersion >= targetVersion) {- p.log.success('Already up to date — no codemods to run.');- p.outro('Done');- return;+ if (!skipVersionCheck) {+ p.log.info(`Current version: ${currentVersion}`);+ p.log.info(`Target version: ${targetVersion}`);++ if (!options.force && currentVersion >= targetVersion) {+ p.log.success('Already up to date — no codemods to run.');+ p.log.info('Use --force to run codemods anyway, or --from <version> to specify the previous version.');+ p.outro('Done');+ return;+ }}// Resolve transformsconst versionManifests = await getTransformsBetween(- currentVersion,+ skipVersionCheck ? '0.0.0' : currentVersion,targetVersion,);@@ -134,7 +148,7 @@ export function registerUpgrade(program) {);// Ensure jscodeshift is available- const ready = await ensureJscodeshift();+ const ready = await ensureJscodeshift({installDeps: options.installDeps});if (!ready) {p.outro('Aborted');process.exitCode = 1;