@wise/wds-codemods 0.0.1-experimental-e54b200 → 0.0.1-experimental-c8c6ec3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,67 +4,157 @@ const node_child_process = require_reportManualReview.__toESM(require("node:chil
4
4
  const node_fs_promises = require_reportManualReview.__toESM(require("node:fs/promises"));
5
5
  const node_path = require_reportManualReview.__toESM(require("node:path"));
6
6
  const node_url = require_reportManualReview.__toESM(require("node:url"));
7
- const __inquirer_prompts = require_reportManualReview.__toESM(require("@inquirer/prompts"));
8
7
  const node_fs = require_reportManualReview.__toESM(require("node:fs"));
8
+ const __inquirer_prompts = require_reportManualReview.__toESM(require("@inquirer/prompts"));
9
9
 
10
10
  //#region src/controller/helpers/getOptions.ts
11
- async function getOptions(transformFiles) {
12
- const args = process.argv.slice(2);
13
- if (args.length > 0) {
14
- const [transformFile$1, targetPath$1] = args;
15
- const dry$1 = args.includes("--dry") || args.includes("--dry-run");
16
- const print$1 = args.includes("--print");
17
- const ignorePatternIndex = args.findIndex((arg) => arg === "--ignore-pattern");
18
- let ignorePattern$1;
19
- if (ignorePatternIndex !== -1 && args.length > ignorePatternIndex + 1) ignorePattern$1 = args[ignorePatternIndex + 1];
20
- const gitignore$1 = args.includes("--gitignore");
21
- const noGitignore = args.includes("--no-gitignore");
22
- if (!transformFile$1 || !transformFiles.includes(transformFile$1)) throw new Error("Invalid transform file specified.");
23
- if (!targetPath$1) throw new Error("Target path cannot be empty.");
24
- const useGitignore = !!(gitignore$1 || !gitignore$1 && !noGitignore);
25
- return {
26
- transformFile: transformFile$1,
27
- targetPath: targetPath$1,
28
- dry: dry$1,
29
- print: print$1,
30
- ignorePattern: ignorePattern$1,
31
- gitignore: useGitignore
32
- };
11
+ /**
12
+ * if args are provided via CLI, log them to the console in
13
+ * a formatted way matching Inquirer's style
14
+ */
15
+ const logToInquirer = (label, value) => {
16
+ const checkmark = "\x1B[32m✔\x1B[0m";
17
+ const boldLabel = `\x1b[1m${label}\x1b[0m`;
18
+ const greenValue = `\x1b[32m${value}\x1b[0m`;
19
+ console.info(`${checkmark} ${boldLabel} ${greenValue}`);
20
+ };
21
+ /**
22
+ * Lets user pick from available packages to run the codemod on
23
+ */
24
+ const queryPackages = async (packages) => {
25
+ const message = "Path to run codemod on:";
26
+ const nonRootPackages = packages.filter((pkg) => pkg !== ".");
27
+ if (packages.length === 1 && nonRootPackages.length === 0) {
28
+ logToInquirer(message, packages[0]);
29
+ return packages;
33
30
  }
34
- const transformFile = await (0, __inquirer_prompts.select)({
35
- message: "Select a codemod transform to run:",
31
+ if (nonRootPackages.length >= 1) return (0, __inquirer_prompts.checkbox)({
32
+ required: true,
33
+ message: "Select packages to transform:",
34
+ choices: nonRootPackages.map((file) => ({
35
+ name: file,
36
+ value: file,
37
+ checked: true
38
+ }))
39
+ });
40
+ };
41
+ /**
42
+ * Determine user choice between CLI arg and Inquirer prompt: codemod
43
+ */
44
+ const determineTransformer = async ({ candidate, transformFiles }) => {
45
+ const codemodMessage = "Select codemod to run:";
46
+ if (candidate && transformFiles.includes(candidate)) {
47
+ logToInquirer(codemodMessage, candidate);
48
+ return candidate;
49
+ }
50
+ return (0, __inquirer_prompts.select)({
51
+ message: codemodMessage,
36
52
  choices: transformFiles.map((file) => ({
37
53
  name: file,
38
54
  value: file
39
55
  }))
40
56
  });
41
- const targetPath = await (0, __inquirer_prompts.input)({
42
- message: "Enter the target directory or file path to run codemod on:",
43
- validate: (value) => value.trim() !== "" || "Target path cannot be empty"
44
- });
45
- const dry = await (0, __inquirer_prompts.confirm)({
46
- message: "Run in dry mode (no changes written to files)?",
47
- default: true
57
+ };
58
+ /**
59
+ * Determine user choice between CLI arg and Inquirer prompt: paths/packages to process
60
+ */
61
+ const determinePaths = async ({ candidate, root, packages }) => {
62
+ const targetPaths = [];
63
+ if (candidate && (0, node_fs.existsSync)((0, node_path.join)(root, candidate))) {
64
+ logToInquirer("Path to run codemod on", candidate);
65
+ targetPaths.push(candidate);
66
+ }
67
+ if (!targetPaths.length) {
68
+ const packagesToProcess = await queryPackages(packages);
69
+ targetPaths.push(...packagesToProcess ?? []);
70
+ }
71
+ return targetPaths;
72
+ };
73
+ /**
74
+ * Determine user choice between CLI arg and Inquirer prompt: dry mode
75
+ */
76
+ const determineIsDryMode = async (args) => {
77
+ const message = "Run in dry mode (no changes written to files)?";
78
+ if (args.includes("--dry") || args.includes("--dry-run")) {
79
+ logToInquirer(message, "Yes");
80
+ return true;
81
+ }
82
+ return (0, __inquirer_prompts.confirm)({
83
+ message,
84
+ default: false
48
85
  });
49
- const print = await (0, __inquirer_prompts.confirm)({
50
- message: "Print transformed source to console?",
86
+ };
87
+ /**
88
+ * Determine user choice between CLI arg and Inquirer prompt: print to CLI
89
+ */
90
+ const determineIsPrint = async (args) => {
91
+ const message = "Print transformed source to console?";
92
+ if (args.includes("--print")) {
93
+ logToInquirer(message, "Yes");
94
+ return true;
95
+ }
96
+ return (0, __inquirer_prompts.confirm)({
97
+ message,
51
98
  default: false
52
99
  });
53
- const ignorePattern = await (0, __inquirer_prompts.input)({
54
- message: "Enter ignore pattern(s) (comma separated) or leave empty:",
55
- validate: (value) => true
100
+ };
101
+ /**
102
+ * Determine user choice between CLI arg and Inquirer prompt: ignore patterns
103
+ */
104
+ const determineIgnorePatterns = async (args) => {
105
+ const message = "Enter ignore pattern(s) (comma separated) or leave empty:";
106
+ const ignorePatternIndex = args.findIndex((arg) => arg === "--ignore-pattern");
107
+ let ignorePattern;
108
+ if (ignorePatternIndex !== -1 && args.length > ignorePatternIndex + 1) ignorePattern = args[ignorePatternIndex + 1];
109
+ if (ignorePattern) {
110
+ logToInquirer(message, ignorePattern);
111
+ return ignorePattern;
112
+ }
113
+ return (0, __inquirer_prompts.input)({
114
+ message,
115
+ validate: () => true
56
116
  });
57
- const gitignore = await (0, __inquirer_prompts.confirm)({
58
- message: "Respect .gitignore files?",
117
+ };
118
+ /**
119
+ * Determine user choice between CLI arg and Inquirer prompt: gitignore
120
+ */
121
+ const determineGitIgnore = async (args) => {
122
+ const message = "Respect .gitignore files?";
123
+ if (args.includes("--gitignore")) {
124
+ logToInquirer(message, "Yes");
125
+ return true;
126
+ }
127
+ if (args.includes("--no-gitignore")) {
128
+ logToInquirer(message, "No");
129
+ return false;
130
+ }
131
+ return (0, __inquirer_prompts.confirm)({
132
+ message,
59
133
  default: true
60
134
  });
135
+ };
136
+ async function getOptions({ transformFiles, packages, root }) {
137
+ const args = process.argv.slice(2);
138
+ const transformFile = await determineTransformer({
139
+ candidate: args[0],
140
+ transformFiles
141
+ });
142
+ const targetPaths = await determinePaths({
143
+ candidate: args[1],
144
+ packages,
145
+ root
146
+ });
147
+ const isDry = await determineIsDryMode(args);
148
+ const isPrint = await determineIsPrint(args);
149
+ const ignorePatterns = await determineIgnorePatterns(args);
150
+ const useGitIgnore = await determineGitIgnore(args);
61
151
  return {
62
152
  transformFile,
63
- targetPath,
64
- dry,
65
- print,
66
- ignorePattern,
67
- gitignore
153
+ targetPaths,
154
+ isDry,
155
+ isPrint,
156
+ ignorePatterns,
157
+ useGitIgnore
68
158
  };
69
159
  }
70
160
  var getOptions_default = getOptions;
@@ -90,48 +180,107 @@ async function loadTransformModules(transformsDir) {
90
180
  }
91
181
  var loadTransformModules_default = loadTransformModules;
92
182
 
183
+ //#endregion
184
+ //#region src/controller/helpers/repository.ts
185
+ /**
186
+ * Finds the root of the project by looking for the `.git` directory.
187
+ */
188
+ function findProjectRoot() {
189
+ try {
190
+ const gitRoot = (0, node_child_process.execSync)("git rev-parse --show-toplevel", {
191
+ cwd: process.cwd(),
192
+ encoding: "utf8",
193
+ stdio: [
194
+ "ignore",
195
+ "pipe",
196
+ "ignore"
197
+ ]
198
+ }).trim();
199
+ return gitRoot && (0, node_fs.existsSync)(gitRoot) ? gitRoot : "";
200
+ } catch {
201
+ return "";
202
+ }
203
+ }
204
+ /**
205
+ * Quick and dirty way of determining package roots based on
206
+ * the presence of `package.json` files and them optimistically
207
+ * containing a `@transferwise/components` string.
208
+ * */
209
+ function findPackages() {
210
+ try {
211
+ const packages = (0, node_child_process.execSync)([
212
+ "find ./",
213
+ "-type f",
214
+ "-name \"package.json\"",
215
+ "-not -path \"*/node_modules/*\"",
216
+ "|",
217
+ "xargs grep -l \"@transferwise/components\""
218
+ ].join(" "), {
219
+ cwd: findProjectRoot(),
220
+ encoding: "utf8"
221
+ }).trim().split("\n").map(node_path.default.dirname);
222
+ if (packages.length === 0) throw new Error();
223
+ return packages;
224
+ } catch {
225
+ throw new Error("No suitable package roots found in the repository.");
226
+ }
227
+ }
228
+
93
229
  //#endregion
94
230
  //#region src/controller/index.ts
95
231
  const currentFilePath = (0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href);
96
232
  const currentDirPath = node_path.default.dirname(currentFilePath);
233
+ const resetReportFile = async (reportPath) => {
234
+ try {
235
+ await node_fs_promises.default.access(reportPath);
236
+ await node_fs_promises.default.rm(reportPath);
237
+ console.debug(`Removed existing report file: ${reportPath}`);
238
+ } catch {
239
+ console.debug(`No existing report file to remove: ${reportPath}`);
240
+ }
241
+ };
242
+ const summariseReportFile = async (reportPath) => {
243
+ try {
244
+ const reportContent = await node_fs_promises.default.readFile(reportPath, "utf8");
245
+ const lines = reportContent.split("\n").filter(Boolean);
246
+ if (lines.length) console.debug(`\n⚠️ ${lines.length} manual review${lines.length > 1 ? "s are" : " is"} required. See ${reportPath} for details.`);
247
+ else console.debug(`Report file exists but is empty: ${reportPath}`);
248
+ } catch {
249
+ console.debug(`No report file generated - no manual reviews needed`);
250
+ }
251
+ };
97
252
  async function runCodemod(transformsDir) {
98
253
  try {
254
+ const packages = findPackages();
255
+ const reportPath = node_path.default.resolve(process.cwd(), "codemod-report.txt");
99
256
  const resolvedTransformsDir = transformsDir ?? node_path.default.resolve(currentDirPath, "../dist/transforms");
100
257
  console.debug(`Resolved transforms directory: ${resolvedTransformsDir}`);
258
+ await resetReportFile(reportPath);
101
259
  const { transformFiles } = await loadTransformModules_default(resolvedTransformsDir);
102
260
  if (transformFiles.length === 0) throw new Error(`No transform scripts found in directory: ${resolvedTransformsDir}`);
103
- const resolvedTransformFiles = await Promise.all(transformFiles);
104
- const options = await getOptions_default(resolvedTransformFiles);
261
+ const options = await getOptions_default({
262
+ packages,
263
+ root: findProjectRoot(),
264
+ transformFiles: await Promise.all(transformFiles)
265
+ });
105
266
  const codemodPath = node_path.default.resolve(resolvedTransformsDir, `${options.transformFile}/transformer.js`);
106
267
  console.debug(`Resolved codemod path: ${codemodPath}`);
107
- const args = [
108
- "-t",
109
- codemodPath,
110
- options.targetPath,
111
- options.dry ? "--dry" : "",
112
- options.print ? "--print" : "",
113
- options.ignorePattern ? options.ignorePattern.split(",").map((pattern) => `--ignore-pattern=${pattern.trim()}`).join(" ") : "",
114
- options.gitignore ? "--gitignore" : ""
115
- ].filter(Boolean);
116
- const command = `npx jscodeshift ${args.join(" ")}`;
117
- console.debug(`Running: ${command}`);
118
- const reportPath = node_path.default.resolve(process.cwd(), "codemod-report.txt");
119
- try {
120
- await node_fs_promises.default.access(reportPath);
121
- await node_fs_promises.default.rm(reportPath);
122
- console.debug(`Removed existing report file: ${reportPath}`);
123
- } catch {
124
- console.debug(`No existing report file to remove: ${reportPath}`);
125
- }
126
- (0, node_child_process.execSync)(command, { stdio: "inherit" });
127
- try {
128
- const reportContent = await node_fs_promises.default.readFile(reportPath, "utf8");
129
- const lines = reportContent.split("\n").filter(Boolean);
130
- if (lines.length) console.log(`\n⚠️ ${lines.length} manual review${lines.length > 1 ? "s are" : " is"} required. See ${reportPath} for details.`);
131
- else console.debug(`Report file exists but is empty: ${reportPath}`);
132
- } catch {
133
- console.debug(`No report file generated - no manual reviews needed`);
134
- }
268
+ options.targetPaths.map((targetPath) => {
269
+ const args = [
270
+ "-t",
271
+ codemodPath,
272
+ targetPath,
273
+ options.isDry ? "--dry" : "",
274
+ options.isPrint ? "--print" : "",
275
+ options.ignorePatterns ? options.ignorePatterns.split(",").map((pattern) => `--ignore-pattern=${pattern.trim()}`).join(" ") : "",
276
+ options.useGitIgnore ? "--gitignore" : ""
277
+ ].filter(Boolean);
278
+ const command = `npx jscodeshift ${args.join(" ")}`;
279
+ console.info(`⚙️ \x1b[1mProcessing:\x1b[0m \x1b[32m${targetPath}\x1b[0m`);
280
+ console.debug(`Running: ${command}`);
281
+ return (0, node_child_process.execSync)(command, { stdio: "inherit" });
282
+ });
283
+ await summariseReportFile(reportPath);
135
284
  } catch (error) {
136
285
  if (error instanceof Error) console.error("Error running codemod:", error.message);
137
286
  else console.error("Error running codemod:", error);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["transformFile","targetPath","dry","print","ignorePattern: string | undefined","gitignore","transformModules: Record<string, unknown>","fs","path","path","loadTransformModules","getOptions","fs","error: unknown"],"sources":["../src/controller/helpers/getOptions.ts","../src/controller/helpers/loadTransformModules.ts","../src/controller/index.ts","../src/index.ts"],"sourcesContent":["import { confirm, input, select as list } from '@inquirer/prompts';\n\nasync function getOptions(transformFiles: string[]) {\n const args = process.argv.slice(2);\n if (args.length > 0) {\n const [transformFile, targetPath] = args;\n const dry = args.includes('--dry') || args.includes('--dry-run');\n const print = args.includes('--print');\n const ignorePatternIndex = args.findIndex((arg) => arg === '--ignore-pattern');\n let ignorePattern: string | undefined;\n if (ignorePatternIndex !== -1 && args.length > ignorePatternIndex + 1) {\n ignorePattern = args[ignorePatternIndex + 1];\n }\n const gitignore = args.includes('--gitignore');\n const noGitignore = args.includes('--no-gitignore');\n\n if (!transformFile || !transformFiles.includes(transformFile)) {\n throw new Error('Invalid transform file specified.');\n }\n if (!targetPath) {\n throw new Error('Target path cannot be empty.');\n }\n\n // If both --gitignore and --no-gitignore are specified, prioritize --gitignore\n const useGitignore = !!(gitignore || (!gitignore && !noGitignore));\n\n return { transformFile, targetPath, dry, print, ignorePattern, gitignore: useGitignore };\n }\n\n const transformFile = await list({\n message: 'Select a codemod transform to run:',\n choices: transformFiles.map((file) => ({ name: file, value: file })),\n });\n\n const targetPath = await input({\n message: 'Enter the target directory or file path to run codemod on:',\n validate: (value) => value.trim() !== '' || 'Target path cannot be empty',\n });\n\n const dry = await confirm({\n message: 'Run in dry mode (no changes written to files)?',\n default: true,\n });\n\n const print = await confirm({\n message: 'Print transformed source to console?',\n default: false,\n });\n\n const ignorePattern = await input({\n message: 'Enter ignore pattern(s) (comma separated) or leave empty:',\n validate: (value) => true,\n });\n\n const gitignore = await confirm({\n message: 'Respect .gitignore files?',\n default: true,\n });\n\n return { transformFile, targetPath, dry, print, ignorePattern, gitignore };\n}\n\nexport default getOptions;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\ninterface TransformModule {\n default: {\n default: unknown;\n };\n}\n\nasync function loadTransformModules(transformsDir: string) {\n let transformModules: Record<string, unknown> = {};\n const transformers = await fs.readdir(transformsDir);\n\n const transformFiles = await Promise.all(\n transformers.map(async (name) => {\n const transformPath = path.join(transformsDir, name, 'transformer.js');\n const transformModule = (await import(transformPath)) as TransformModule;\n transformModules = { ...transformModules, [name]: transformModule.default.default };\n return name;\n }),\n );\n\n return { transformModules, transformFiles };\n}\n\nexport default loadTransformModules;\n","#!/usr/bin/env node\n\nimport { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { getOptions, handleError, loadTransformModules } from './helpers';\n\nconst currentFilePath = fileURLToPath(import.meta.url);\nconst currentDirPath = path.dirname(currentFilePath);\n\nasync function runCodemod(transformsDir?: string) {\n try {\n const resolvedTransformsDir =\n transformsDir ?? path.resolve(currentDirPath, '../dist/transforms');\n console.debug(`Resolved transforms directory: ${resolvedTransformsDir}`);\n\n const { transformFiles } = await loadTransformModules(resolvedTransformsDir);\n\n if (transformFiles.length === 0) {\n throw new Error(`No transform scripts found in directory: ${resolvedTransformsDir}`);\n }\n\n const resolvedTransformFiles = await Promise.all(transformFiles);\n const options = await getOptions(resolvedTransformFiles);\n\n const codemodPath = path.resolve(\n resolvedTransformsDir,\n `${options.transformFile}/transformer.js`,\n );\n console.debug(`Resolved codemod path: ${codemodPath}`);\n\n const args = [\n '-t',\n codemodPath,\n options.targetPath,\n options.dry ? '--dry' : '',\n options.print ? '--print' : '',\n options.ignorePattern\n ? options.ignorePattern\n .split(',')\n .map((pattern) => `--ignore-pattern=${pattern.trim()}`)\n .join(' ')\n : '',\n options.gitignore ? '--gitignore' : '',\n ].filter(Boolean);\n\n const command = `npx jscodeshift ${args.join(' ')}`;\n\n console.debug(`Running: ${command}`);\n\n const reportPath = path.resolve(process.cwd(), 'codemod-report.txt');\n\n try {\n await fs.access(reportPath);\n await fs.rm(reportPath);\n console.debug(`Removed existing report file: ${reportPath}`);\n } catch {\n console.debug(`No existing report file to remove: ${reportPath}`);\n }\n\n execSync(command, { stdio: 'inherit' });\n\n try {\n const reportContent = await fs.readFile(reportPath, 'utf8');\n const lines = reportContent.split('\\n').filter(Boolean);\n if (lines.length) {\n console.log(\n `\\n⚠️ ${lines.length} manual review${lines.length > 1 ? 's are' : ' is'} required. See ${reportPath} for details.`,\n );\n } else {\n console.debug(`Report file exists but is empty: ${reportPath}`);\n }\n } catch {\n console.debug(`No report file generated - no manual reviews needed`);\n }\n } catch (error: unknown) {\n if (error instanceof Error) {\n console.error('Error running codemod:', error.message);\n } else {\n console.error('Error running codemod:', error);\n }\n if (process.env.NODE_ENV !== 'test') {\n process.exit(1);\n }\n }\n}\n\nexport { runCodemod };\n","#!/usr/bin/env node\nimport { runCodemod } from './controller';\n\nvoid runCodemod();\n"],"mappings":";;;;;;;;;;AAEA,eAAe,WAAW,gBAA0B;CAClD,MAAM,OAAO,QAAQ,KAAK,MAAM;AAChC,KAAI,KAAK,SAAS,GAAG;EACnB,MAAM,CAACA,iBAAeC,gBAAc;EACpC,MAAMC,QAAM,KAAK,SAAS,YAAY,KAAK,SAAS;EACpD,MAAMC,UAAQ,KAAK,SAAS;EAC5B,MAAM,qBAAqB,KAAK,WAA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,MAAM,0BAA0B;AAE1C,MAAI,QAAQ,IAAI,aAAa,OAC3B,SAAQ,KAAK;;;;;;ACjFd"}
1
+ {"version":3,"file":"index.js","names":["ignorePattern: string | undefined","transformModules: Record<string, unknown>","fs","path","path","path","fs","loadTransformModules","getOptions","error: unknown"],"sources":["../src/controller/helpers/getOptions.ts","../src/controller/helpers/loadTransformModules.ts","../src/controller/helpers/repository.ts","../src/controller/index.ts","../src/index.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport { checkbox, confirm, input, select as list } from '@inquirer/prompts';\n\n/**\n * if args are provided via CLI, log them to the console in\n * a formatted way matching Inquirer's style\n */\nconst logToInquirer = (label: string, value: string) => {\n const checkmark = '\\x1b[32m✔\\x1b[0m'; // Green checkmark\n const boldLabel = `\\x1b[1m${label}\\x1b[0m`; // Bold label\n const greenValue = `\\x1b[32m${value}\\x1b[0m`; // Green value\n\n console.info(`${checkmark} ${boldLabel} ${greenValue}`);\n};\n\n/**\n * Lets user pick from available packages to run the codemod on\n */\nconst queryPackages = async (packages: string[]) => {\n const message = 'Path to run codemod on:';\n const nonRootPackages = packages.filter((pkg) => pkg !== '.');\n\n // root package only\n if (packages.length === 1 && nonRootPackages.length === 0) {\n logToInquirer(message, packages[0]);\n return packages;\n }\n\n // multiple non-root packages\n if (nonRootPackages.length >= 1) {\n return checkbox({\n required: true,\n message: 'Select packages to transform:',\n choices: nonRootPackages.map((file) => ({\n name: file,\n value: file,\n checked: true,\n })),\n });\n }\n};\n\n/**\n * Determine user choice between CLI arg and Inquirer prompt: codemod\n */\nconst determineTransformer = async ({\n candidate,\n transformFiles,\n}: {\n candidate: string;\n transformFiles: string[];\n}): Promise<string> => {\n const codemodMessage = 'Select codemod to run:';\n\n if (candidate && transformFiles.includes(candidate)) {\n logToInquirer(codemodMessage, candidate);\n return candidate;\n }\n\n return list({\n message: codemodMessage,\n choices: transformFiles.map((file) => ({ name: file, value: file })),\n });\n};\n\n/**\n * Determine user choice between CLI arg and Inquirer prompt: paths/packages to process\n */\nconst determinePaths = async ({\n candidate,\n root,\n packages,\n}: {\n candidate: string;\n root: string;\n packages: string[];\n}): Promise<string[]> => {\n const targetPaths = [];\n\n if (candidate && existsSync(join(root, candidate))) {\n logToInquirer('Path to run codemod on', candidate);\n targetPaths.push(candidate);\n }\n\n if (!targetPaths.length) {\n const packagesToProcess = await queryPackages(packages);\n targetPaths.push(...(packagesToProcess ?? []));\n }\n\n return targetPaths;\n};\n\n/**\n * Determine user choice between CLI arg and Inquirer prompt: dry mode\n */\nconst determineIsDryMode = async (args: string[]) => {\n const message = 'Run in dry mode (no changes written to files)?';\n if (args.includes('--dry') || args.includes('--dry-run')) {\n logToInquirer(message, 'Yes');\n return true;\n }\n\n return confirm({ message, default: false });\n};\n\n/**\n * Determine user choice between CLI arg and Inquirer prompt: print to CLI\n */\nconst determineIsPrint = async (args: string[]) => {\n const message = 'Print transformed source to console?';\n\n if (args.includes('--print')) {\n logToInquirer(message, 'Yes');\n return true;\n }\n\n return confirm({ message, default: false });\n};\n\n/**\n * Determine user choice between CLI arg and Inquirer prompt: ignore patterns\n */\nconst determineIgnorePatterns = async (args: string[]) => {\n const message = 'Enter ignore pattern(s) (comma separated) or leave empty:';\n const ignorePatternIndex = args.findIndex((arg) => arg === '--ignore-pattern');\n\n let ignorePattern: string | undefined;\n\n if (ignorePatternIndex !== -1 && args.length > ignorePatternIndex + 1) {\n ignorePattern = args[ignorePatternIndex + 1];\n }\n\n if (ignorePattern) {\n logToInquirer(message, ignorePattern);\n return ignorePattern;\n }\n\n return input({\n message,\n validate: () => true,\n });\n};\n\n/**\n * Determine user choice between CLI arg and Inquirer prompt: gitignore\n */\nconst determineGitIgnore = async (args: string[]) => {\n const message = 'Respect .gitignore files?';\n\n if (args.includes('--gitignore')) {\n logToInquirer(message, 'Yes');\n return true;\n }\n\n if (args.includes('--no-gitignore')) {\n logToInquirer(message, 'No');\n return false;\n }\n\n return confirm({ message, default: true });\n};\n\ninterface OptionsParams {\n transformFiles: string[];\n packages: string[];\n root: string;\n}\nasync function getOptions({ transformFiles, packages, root }: OptionsParams) {\n const args = process.argv.slice(2);\n\n const transformFile = await determineTransformer({ candidate: args[0], transformFiles });\n const targetPaths = await determinePaths({ candidate: args[1], packages, root });\n const isDry = await determineIsDryMode(args);\n const isPrint = await determineIsPrint(args);\n const ignorePatterns = await determineIgnorePatterns(args);\n const useGitIgnore = await determineGitIgnore(args);\n\n return {\n transformFile,\n targetPaths,\n isDry,\n isPrint,\n ignorePatterns,\n useGitIgnore,\n };\n}\n\nexport default getOptions;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\ninterface TransformModule {\n default: {\n default: unknown;\n };\n}\n\nasync function loadTransformModules(transformsDir: string) {\n let transformModules: Record<string, unknown> = {};\n const transformers = await fs.readdir(transformsDir);\n\n const transformFiles = await Promise.all(\n transformers.map(async (name) => {\n const transformPath = path.join(transformsDir, name, 'transformer.js');\n const transformModule = (await import(transformPath)) as TransformModule;\n transformModules = { ...transformModules, [name]: transformModule.default.default };\n return name;\n }),\n );\n\n return { transformModules, transformFiles };\n}\n\nexport default loadTransformModules;\n","import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Finds the root of the project by looking for the `.git` directory.\n */\nexport function findProjectRoot(): string {\n try {\n const gitRoot = execSync('git rev-parse --show-toplevel', {\n cwd: process.cwd(),\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim();\n\n return gitRoot && existsSync(gitRoot) ? gitRoot : '';\n } catch {\n return '';\n }\n}\n\n/**\n * Quick and dirty way of determining package roots based on\n * the presence of `package.json` files and them optimistically\n * containing a `@transferwise/components` string.\n * */\nexport function findPackages() {\n try {\n const packages = execSync(\n [\n 'find ./',\n '-type f',\n '-name \"package.json\"',\n '-not -path \"*/node_modules/*\"',\n '|',\n 'xargs grep -l \"@transferwise/components\"',\n ].join(' '),\n {\n cwd: findProjectRoot(),\n encoding: 'utf8',\n },\n )\n .trim()\n .split('\\n')\n .map(path.dirname);\n\n if (packages.length === 0) {\n throw new Error();\n }\n\n return packages;\n } catch {\n throw new Error('No suitable package roots found in the repository.');\n }\n}\n","#!/usr/bin/env node\n\nimport { execSync } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { findPackages, findProjectRoot, getOptions, loadTransformModules } from './helpers';\n\nconst currentFilePath = fileURLToPath(import.meta.url);\nconst currentDirPath = path.dirname(currentFilePath);\n\nconst resetReportFile = async (reportPath: string) => {\n try {\n await fs.access(reportPath);\n await fs.rm(reportPath);\n console.debug(`Removed existing report file: ${reportPath}`);\n } catch {\n console.debug(`No existing report file to remove: ${reportPath}`);\n }\n};\n\nconst summariseReportFile = async (reportPath: string) => {\n try {\n const reportContent = await fs.readFile(reportPath, 'utf8');\n const lines = reportContent.split('\\n').filter(Boolean);\n if (lines.length) {\n console.debug(\n `\\n⚠️ ${lines.length} manual review${lines.length > 1 ? 's are' : ' is'} required. See ${reportPath} for details.`,\n );\n } else {\n console.debug(`Report file exists but is empty: ${reportPath}`);\n }\n } catch {\n console.debug(`No report file generated - no manual reviews needed`);\n }\n};\n\nasync function runCodemod(transformsDir?: string) {\n try {\n const packages = findPackages();\n const reportPath = path.resolve(process.cwd(), 'codemod-report.txt');\n const resolvedTransformsDir =\n transformsDir ?? path.resolve(currentDirPath, '../dist/transforms');\n console.debug(`Resolved transforms directory: ${resolvedTransformsDir}`);\n\n await resetReportFile(reportPath);\n\n const { transformFiles } = await loadTransformModules(resolvedTransformsDir);\n if (transformFiles.length === 0) {\n throw new Error(`No transform scripts found in directory: ${resolvedTransformsDir}`);\n }\n\n const options = await getOptions({\n packages,\n root: findProjectRoot(),\n transformFiles: await Promise.all(transformFiles),\n });\n\n const codemodPath = path.resolve(\n resolvedTransformsDir,\n `${options.transformFile}/transformer.js`,\n );\n console.debug(`Resolved codemod path: ${codemodPath}`);\n\n options.targetPaths.map((targetPath) => {\n const args = [\n '-t',\n codemodPath,\n targetPath,\n options.isDry ? '--dry' : '',\n options.isPrint ? '--print' : '',\n options.ignorePatterns\n ? options.ignorePatterns\n .split(',')\n .map((pattern) => `--ignore-pattern=${pattern.trim()}`)\n .join(' ')\n : '',\n options.useGitIgnore ? '--gitignore' : '',\n ].filter(Boolean);\n\n const command = `npx jscodeshift ${args.join(' ')}`;\n console.info(`⚙️ \\x1b[1mProcessing:\\x1b[0m \\x1b[32m${targetPath}\\x1b[0m`);\n console.debug(`Running: ${command}`);\n\n return execSync(command, { stdio: 'inherit' });\n });\n\n await summariseReportFile(reportPath);\n } catch (error: unknown) {\n if (error instanceof Error) {\n console.error('Error running codemod:', error.message);\n } else {\n console.error('Error running codemod:', error);\n }\n if (process.env.NODE_ENV !== 'test') {\n process.exit(1);\n }\n }\n}\n\nexport { runCodemod };\n","#!/usr/bin/env node\nimport { runCodemod } from './controller';\n\nvoid runCodemod();\n"],"mappings":";;;;;;;;;;;;;;AASA,MAAM,iBAAiB,OAAe,UAAkB;CACtD,MAAM,YAAY;CAClB,MAAM,YAAY,UAAU,MAAM;CAClC,MAAM,aAAa,WAAW,MAAM;AAEpC,SAAQ,KAAK,GAAG,UAAU,GAAG,UAAU,GAAG;;;;;AAM5C,MAAM,gBAAgB,OAAO,aAAuB;CAClD,MAAM,UAAU;CAChB,MAAM,kBAAkB,SAAS,QAAQ,QAAQ,QAAQ;AAGzD,KAAI,SAAS,WAAW,KAAK,gBAAgB,WAAW,GAAG;AACzD,gBAAc,SAAS,SAAS;AAChC,SAAO;;AAIT,KAAI,gBAAgB,UAAU,EAC5B,yCAAgB;EACd,UAAU;EACV,SAAS;EACT,SAAS,gBAAgB,KAAK,UAAU;GACtC,MAAM;GACN,OAAO;GACP,SAAS;;;;;;;AASjB,MAAM,uBAAuB,OAAO,EAClC,WACA,qBAIqB;CACrB,MAAM,iBAAiB;AAEvB,KAAI,aAAa,eAAe,SAAS,YAAY;AACnD,gBAA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WAAQ,MAAM,YAAY;AAE1B,2CAAgB,SAAS,EAAE,OAAO;;AAGpC,QAAM,oBAAoB;UACnBI,OAAgB;AACvB,MAAI,iBAAiB,MACnB,SAAQ,MAAM,0BAA0B,MAAM;MAE9C,SAAQ,MAAM,0BAA0B;AAE1C,MAAI,QAAQ,IAAI,aAAa,OAC3B,SAAQ,KAAK;;;;;;AC7Fd"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wise/wds-codemods",
3
- "version": "0.0.1-experimental-e54b200",
3
+ "version": "0.0.1-experimental-c8c6ec3",
4
4
  "license": "UNLICENSED",
5
5
  "author": "Wise Payments Ltd.",
6
6
  "repository": {