Skip to content

Commit 96639f5

Browse files
authored
Improve migration/utils.js and index.js (#34)
1 parent 35ca1ad commit 96639f5

File tree

5 files changed

+736
-723
lines changed

5 files changed

+736
-723
lines changed

index.js

Lines changed: 128 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ import { relative } from "path";
88
import process from "process";
99
import { coerce, gt, lte, parse } from "semver";
1010
import { Project } from "ts-morph";
11+
12+
// Constants
13+
const CSS_IGNORE_FOLDERS = ["node_modules", "dist", "build"];
14+
const SALT_DS_PACKAGE_FILTER = /@salt-ds/;
1115
import { css100RenameMap, react100 } from "./migration/core100.js";
1216
import { react110 } from "./migration/core110.js";
1317
import { react1110 } from "./migration/core1110.js";
@@ -52,7 +56,11 @@ import {
5256
verboseOnlyDimLog,
5357
verboseOnlyTableLog,
5458
verboseOnlyLog,
59+
infoLog,
60+
errorLog,
61+
warnLog,
5562
} from "./utils/log.js";
63+
import { applyMigrationIfInRange } from "./utils/migration-helpers.js";
5664
import { react1372 } from "./migration/core1372.js";
5765
import { react1380 } from "./migration/core1380.js";
5866
import { react1390 } from "./migration/core1390.js";
@@ -153,42 +161,51 @@ const v1530 = parse("1.53.0");
153161
// NOTE: don't forget to modify `LATEST_SUPPORTED_VERSION` in args.js
154162

155163
if (dryRun) {
156-
console.log(chalk.bold("Dry run mode"));
164+
infoLog(chalk.bold("Dry run mode"));
157165
}
158166

159167
// <-------- Upgrade package.json version ---------->
160168

161169
let upgradedVersion = undefined;
162170

163171
if (!skipUpgrade || dryRun) {
164-
const upgraded = await ncu.run({
165-
upgrade: true,
166-
filter: new RegExp("@salt-ds"),
167-
install: "always",
168-
// Logging is not supported in json mode - https://github.com/raineorshine/npm-check-updates/blob/982bd407dd46ec4f8173ed867f117e4d45686981/src/lib/logging.ts#L53-L70
169-
});
172+
try {
173+
const upgraded = await ncu.run({
174+
upgrade: true,
175+
filter: SALT_DS_PACKAGE_FILTER,
176+
install: "always",
177+
// Logging is not supported in json mode - https://github.com/raineorshine/npm-check-updates/blob/982bd407dd46ec4f8173ed867f117e4d45686981/src/lib/logging.ts#L53-L70
178+
});
170179

171-
if (Object.entries(upgraded).length) {
172-
verboseOnlyDimLog("Package upgraded to ", JSON.stringify(upgraded)); // { '@salt-ds/core': '^1.37.1', ... }
173-
const newCoreRange = upgraded["@salt-ds/core"];
174-
upgradedVersion = coerce(newCoreRange)?.version;
175-
} else {
176-
verboseOnlyDimLog("No @salt-ds/* package was upgraded");
180+
if (Object.entries(upgraded).length) {
181+
verboseOnlyDimLog("Package upgraded to ", JSON.stringify(upgraded)); // { '@salt-ds/core': '^1.37.1', ... }
182+
const newCoreRange = upgraded["@salt-ds/core"];
183+
upgradedVersion = coerce(newCoreRange)?.version;
184+
} else {
185+
verboseOnlyDimLog("No @salt-ds/* package was upgraded");
186+
}
187+
} catch (error) {
188+
errorLog(chalk.red("Failed to upgrade packages:"), error.message);
189+
infoLog(chalk.yellow("Continuing with codemod using specified versions..."));
177190
}
178191
}
179192

180193
const fromVersion = parse(fromInput) || parse(DEFAULT_FROM_VERSION);
181194
const toVersion =
182195
parse(toInput) || parse(upgradedVersion) || parse(LATEST_SUPPORTED_VERSION);
183196

184-
console.log(
197+
infoLog(
185198
"Running codemod from version",
186199
chalk.bold(fromVersion.format()),
187200
"to version",
188201
chalk.bold(toVersion.format())
189202
);
190203

191-
// <-------- TS Code ---------->
204+
// ============================================================================
205+
// TypeScript/React Migrations
206+
// ============================================================================
207+
// This section handles all React component and TypeScript code migrations
208+
// using ts-morph to parse and transform source files.
192209

193210
// Keep track of project and source files for SaltProviderNext detection
194211
let project = null;
@@ -209,13 +226,13 @@ if (mode === undefined || mode === "ts") {
209226
tsConfigFilePath: initialiseFromTsConfig ? tsconfig : undefined,
210227
});
211228

212-
// console.log(project);
229+
// infoLog(project);
213230

214231
if (initialiseFromTsConfig) {
215-
console.log(chalk.dim("Initialising TypeScript project from", tsconfig));
232+
infoLog(chalk.dim("Initialising TypeScript project from", tsconfig));
216233
// project.addSourceFilesFromTsConfig();
217234
} else {
218-
console.log(
235+
infoLog(
219236
chalk.dim(
220237
"Initialising TypeScript project from source glob:",
221238
tsSourceGlob,
@@ -227,7 +244,7 @@ if (mode === undefined || mode === "ts") {
227244
}
228245

229246
sourceFiles = project.getSourceFiles();
230-
console.log(chalk.dim("Found", sourceFiles.length, "source files"));
247+
infoLog(chalk.dim("Found", sourceFiles.length, "source files"));
231248

232249
for (const file of sourceFiles) {
233250
const filePath = file.getFilePath();
@@ -406,13 +423,17 @@ if (mode === undefined || mode === "ts") {
406423
await project.save();
407424
}
408425

409-
console.log(chalk.dim("TypeScript conversion done."));
426+
infoLog(chalk.dim("TypeScript conversion done."));
410427
}
411428

412-
// <-------- CSS Var ---------->
429+
// ============================================================================
430+
// CSS Variable Migrations
431+
// ============================================================================
432+
// This section handles CSS variable renames and validations across
433+
// CSS, TypeScript, and TSX files.
413434

414435
if (mode === undefined || mode === "css") {
415-
console.log(chalk.dim("Starting CSS variable migrations"));
436+
infoLog(chalk.dim("Starting CSS variable migrations"));
416437

417438
// Detect if SaltProviderNext is being used in the codebase
418439
let usesSaltProviderNext = false;
@@ -448,61 +469,70 @@ if (mode === undefined || mode === "css") {
448469
"Reading Salt theme CSS variables from",
449470
relative(process.cwd(), themeCss)
450471
);
451-
const saltThemeCssContent = readFileSync(themeCss, {
452-
encoding: "utf8",
453-
flag: "r",
454-
});
455-
const allSaltThemeCssVars = new Set(
456-
[...saltThemeCssContent.matchAll(/--salt[-\w]+\b/g)].map((x) => x[0])
457-
);
458472

459-
// If SaltProviderNext is detected and theme-next.css exists, also load its variables
460-
if (usesSaltProviderNext && existsSync(themeNextCss)) {
461-
verboseOnlyDimLog(
462-
"Reading additional Salt theme CSS variables from",
463-
relative(process.cwd(), themeNextCss)
464-
);
465-
const saltThemeNextCssContent = readFileSync(themeNextCss, {
473+
let allSaltThemeCssVars = new Set();
474+
try {
475+
const saltThemeCssContent = readFileSync(themeCss, {
466476
encoding: "utf8",
467477
flag: "r",
468478
});
469-
const themeNextVars = [
470-
...saltThemeNextCssContent.matchAll(/--salt[-\w]+\b/g),
471-
].map((x) => x[0]);
479+
allSaltThemeCssVars = new Set(
480+
[...saltThemeCssContent.matchAll(/--salt[-\w]+\b/g)].map((x) => x[0])
481+
);
482+
483+
// If SaltProviderNext is detected and theme-next.css exists, also load its variables
484+
if (usesSaltProviderNext && existsSync(themeNextCss)) {
485+
verboseOnlyDimLog(
486+
"Reading additional Salt theme CSS variables from",
487+
relative(process.cwd(), themeNextCss)
488+
);
489+
const saltThemeNextCssContent = readFileSync(themeNextCss, {
490+
encoding: "utf8",
491+
flag: "r",
492+
});
493+
const themeNextVars = [
494+
...saltThemeNextCssContent.matchAll(/--salt[-\w]+\b/g),
495+
].map((x) => x[0]);
496+
497+
themeNextVars.forEach((cssVar) => allSaltThemeCssVars.add(cssVar));
472498

473-
themeNextVars.forEach((cssVar) => allSaltThemeCssVars.add(cssVar));
499+
verboseOnlyDimLog(
500+
"Added",
501+
themeNextVars.length,
502+
"variables from theme-next.css"
503+
);
504+
}
474505

475506
verboseOnlyDimLog(
476-
"Added",
477-
themeNextVars.length,
478-
"variables from theme-next.css"
507+
"Total valid Salt theme CSS var count:",
508+
allSaltThemeCssVars.size
509+
);
510+
} catch (error) {
511+
errorLog(
512+
chalk.yellow("Warning: Could not read theme CSS file:"),
513+
error.message
479514
);
515+
infoLog(chalk.yellow("CSS variable validation will be skipped."));
480516
}
481517

482-
verboseOnlyDimLog(
483-
"Total valid Salt theme CSS var count:",
484-
allSaltThemeCssVars.size
485-
);
486-
487-
const cssIgnoreFolders = ["node_modules", "dist", "build"];
488-
console.log(
518+
infoLog(
489519
chalk.dim(
490520
"Scanning CSS using source glob:",
491521
cssGlob,
492522
", ignoring folders:",
493-
cssIgnoreFolders
523+
CSS_IGNORE_FOLDERS
494524
)
495525
);
496526
const filePaths = glob.sync(cssGlob, {
497-
ignore: cssIgnoreFolders,
527+
ignore: CSS_IGNORE_FOLDERS,
498528
});
499529

500530
verboseOnlyDimLog(
501531
"Total files to scan for migrating CSS variables:",
502532
filePaths.length
503533
);
504534

505-
/** A array of css variable to move from version a to b. */
535+
// Collect all CSS variable migrations that apply to the version range
506536
const cssMigrationMapArray = [];
507537

508538
if (gt(v100, fromVersion) && lte(v100, toVersion)) {
@@ -572,47 +602,60 @@ if (mode === undefined || mode === "css") {
572602
}
573603
verboseOnlyDimLog("Processing", filePath);
574604

575-
const originalContent = readFileSync(filePath, {
576-
encoding: "utf-8",
577-
flag: "r",
578-
});
605+
try {
606+
const originalContent = readFileSync(filePath, {
607+
encoding: "utf-8",
608+
flag: "r",
609+
});
579610

580-
const newContent = originalContent
581-
.split(/\r?\n|\r|\n/g)
582-
.map((line, lineIndex) => {
583-
let newLine = line;
584-
585-
if (cssMigrationMap.size > 0) {
586-
newLine = migrateCssVar(
587-
// Replace uitk prefix with salt prefix for pre-1.0.0 migration
588-
gt(v100, fromVersion) ? line : line.replace(/--uitk/g, "--salt"),
589-
knownCssRenameCheckRegex,
590-
cssMigrationMap
611+
const newContent = originalContent
612+
.split(/\r?\n|\r|\n/g)
613+
.map((line, lineIndex) => {
614+
let newLine = line;
615+
616+
if (cssMigrationMap.size > 0) {
617+
// Apply uitk -> salt prefix migration for pre-1.0.0
618+
const lineToMigrate = gt(v100, fromVersion)
619+
? line
620+
: line.replace(/--uitk/g, "--salt");
621+
622+
newLine = migrateCssVar(
623+
lineToMigrate,
624+
knownCssRenameCheckRegex,
625+
cssMigrationMap
626+
);
627+
}
628+
629+
warnUnknownSaltThemeVars(
630+
allSaltThemeCssVars,
631+
newLine,
632+
lineIndex,
633+
filePath
591634
);
592-
}
593-
594-
warnUnknownSaltThemeVars(
595-
allSaltThemeCssVars,
596-
newLine,
597-
lineIndex,
598-
filePath
599-
);
600635

601-
return newLine;
602-
})
603-
.join("\n");
636+
return newLine;
637+
})
638+
.join("\n");
604639

605-
if (newContent !== originalContent && !dryRun) {
606-
writeFileSync(filePath, newContent, { encoding: "utf-8" });
607-
verboseOnlyDimLog("Writing new", filePath);
640+
if (newContent !== originalContent && !dryRun) {
641+
writeFileSync(filePath, newContent, { encoding: "utf-8" });
642+
verboseOnlyDimLog("Writing new", filePath);
643+
}
644+
} catch (error) {
645+
errorLog(chalk.red(`Failed to process ${filePath}:`), error.message);
608646
}
609647
}
610648

611-
console.log(chalk.dim("CSS variable migrations done."));
649+
infoLog(chalk.dim("CSS variable migrations done."));
612650
}
613651

652+
// ============================================================================
653+
// Completion
654+
// ============================================================================
655+
614656
if (dryRun) {
615-
console.log("Dry run mode done!");
657+
infoLog(chalk.bold.cyan("Dry run mode complete!"));
658+
infoLog(chalk.dim("No files were modified. Remove --dryRun to apply changes."));
616659
} else {
617-
console.log("All done!");
660+
infoLog(chalk.bold.green("All migrations complete!"));
618661
}

0 commit comments

Comments
 (0)