@turbo/codemod 1.7.1-canary.1 → 1.7.1-canary.3

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.
@@ -23,20 +23,25 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
23
23
  // src/transforms/add-package-manager.ts
24
24
  var add_package_manager_exports = {};
25
25
  __export(add_package_manager_exports, {
26
- default: () => addPackageManager
26
+ default: () => add_package_manager_default,
27
+ transformer: () => transformer
27
28
  });
28
29
  module.exports = __toCommonJS(add_package_manager_exports);
29
- var import_path2 = __toESM(require("path"));
30
+ var import_path3 = __toESM(require("path"));
31
+ var import_fs_extra2 = __toESM(require("fs-extra"));
30
32
 
31
- // src/getWorkspaceImplementation.ts
33
+ // src/utils/getPackageManager.ts
32
34
  var import_find_up = __toESM(require("find-up"));
33
35
  var import_path = __toESM(require("path"));
34
36
  var cache = {};
35
- function getWorkspaceImplementationAndLockFile(cwd) {
37
+ function getPackageManager({
38
+ directory
39
+ }) {
40
+ const cwd = directory || process.cwd();
36
41
  if (cache[cwd]) {
37
42
  return cache[cwd];
38
43
  }
39
- const lockFile = import_find_up.default.sync(["yarn.lock", "pnpm-workspace.yaml", "package-lock.json"], {
44
+ const lockFile = import_find_up.default.sync(["yarn.lock", "pnpm-lock.yaml", "package-lock.json"], {
40
45
  cwd
41
46
  });
42
47
  if (!lockFile) {
@@ -44,126 +49,303 @@ function getWorkspaceImplementationAndLockFile(cwd) {
44
49
  }
45
50
  switch (import_path.default.basename(lockFile)) {
46
51
  case "yarn.lock":
47
- cache[cwd] = {
48
- implementation: "yarn",
49
- lockFile
50
- };
52
+ cache[cwd] = "yarn";
51
53
  break;
52
- case "pnpm-workspace.yaml":
53
- cache[cwd] = {
54
- implementation: "pnpm",
55
- lockFile
56
- };
54
+ case "pnpm-lock.yaml":
55
+ cache[cwd] = "pnpm";
57
56
  break;
58
57
  case "package-lock.json":
59
- cache[cwd] = {
60
- implementation: "npm",
61
- lockFile
62
- };
58
+ cache[cwd] = "npm";
63
59
  break;
64
60
  }
65
61
  return cache[cwd];
66
62
  }
67
- function getWorkspaceImplementation(cwd) {
68
- var _a;
69
- return (_a = getWorkspaceImplementationAndLockFile(cwd)) == null ? void 0 : _a.implementation;
70
- }
71
63
 
72
- // src/getPackageManagerVersion.ts
64
+ // src/utils/getPackageManagerVersion.ts
73
65
  var import_child_process = require("child_process");
74
- var getPackageManagerVersion = (ws) => {
75
- switch (ws) {
66
+ function getPackageManagerVersion(packageManager, root) {
67
+ switch (packageManager) {
76
68
  case "yarn":
77
- return (0, import_child_process.execSync)("yarn --version").toString().trim();
69
+ return (0, import_child_process.execSync)("yarn --version", { cwd: root }).toString().trim();
78
70
  case "pnpm":
79
- return (0, import_child_process.execSync)("pnpm --version").toString().trim();
71
+ return (0, import_child_process.execSync)("pnpm --version", { cwd: root }).toString().trim();
80
72
  case "npm":
81
- return (0, import_child_process.execSync)("npm --version").toString().trim();
82
- default:
83
- throw new Error(`${ws} is not supported`);
73
+ return (0, import_child_process.execSync)("npm --version", { cwd: root }).toString().trim();
84
74
  }
85
- };
75
+ }
86
76
 
87
- // src/transforms/add-package-manager.ts
88
- var import_fs_extra = __toESM(require("fs-extra"));
89
- var import_chalk2 = __toESM(require("chalk"));
77
+ // src/runner/Runner.ts
78
+ var import_chalk3 = __toESM(require("chalk"));
90
79
 
91
- // src/logger.ts
80
+ // src/runner/FileTransform.ts
92
81
  var import_chalk = __toESM(require("chalk"));
93
- function skip(...args) {
94
- console.log(import_chalk.default.yellow.inverse(` SKIP `), ...args);
95
- }
96
- function error(...args) {
97
- console.log(import_chalk.default.red.inverse(` ERROR `), ...args);
98
- }
99
- function ok(...args) {
100
- console.log(import_chalk.default.green.inverse(` OK `), ...args);
101
- }
102
-
103
- // src/transforms/add-package-manager.ts
104
- function addPackageManager(files, flags) {
105
- if (files.length === 1) {
106
- const dir = files[0];
107
- const root = import_path2.default.resolve(process.cwd(), dir);
108
- console.log(`Set "packageManager" key in root "package.json" file...`);
109
- const packageManager = getWorkspaceImplementation(root);
110
- if (!packageManager) {
111
- error(`Unable to determine package manager for ${dir}`);
112
- process.exit(1);
113
- }
114
- const version = getPackageManagerVersion(packageManager);
115
- const pkgManagerString = `${packageManager}@${version}`;
116
- const rootPackageJsonPath = import_path2.default.join(root, "package.json");
117
- const rootPackageJson = import_fs_extra.default.readJsonSync(rootPackageJsonPath);
118
- const allWorkspaces = [
119
- {
120
- name: "package.json",
121
- path: root,
122
- packageJson: {
123
- ...rootPackageJson,
124
- packageJsonPath: rootPackageJsonPath
82
+ var import_diff = require("diff");
83
+ var import_fs_extra = __toESM(require("fs-extra"));
84
+ var import_os = __toESM(require("os"));
85
+ var import_path2 = __toESM(require("path"));
86
+ var FileTransform = class {
87
+ constructor(args) {
88
+ this.changes = [];
89
+ this.filePath = args.filePath;
90
+ this.rootPath = args.rootPath;
91
+ this.after = args.after;
92
+ this.error = args.error;
93
+ if (args.before === void 0) {
94
+ try {
95
+ if (import_path2.default.extname(args.filePath) === ".json") {
96
+ this.before = import_fs_extra.default.readJsonSync(args.filePath);
97
+ } else {
98
+ this.before = import_fs_extra.default.readFileSync(args.filePath);
125
99
  }
100
+ } catch (err) {
101
+ this.before = "";
126
102
  }
127
- ];
128
- let modifiedCount = 0;
129
- let skippedCount = 0;
130
- let errorCount = 0;
131
- let unmodifiedCount = allWorkspaces.length;
132
- console.log(`Found ${unmodifiedCount} files for modification...`);
133
- for (const workspace of allWorkspaces) {
134
- const { packageJsonPath, ...pkgJson } = workspace.packageJson;
135
- const relPackageJsonPath = import_path2.default.relative(root, packageJsonPath);
136
- try {
137
- if (pkgJson.packageManager === pkgManagerString) {
138
- skip(relPackageJsonPath, import_chalk2.default.dim(`(already set to ${pkgManagerString})`));
103
+ } else if (args.before === null) {
104
+ this.before = "";
105
+ } else {
106
+ this.before = args.before;
107
+ }
108
+ if (args.after) {
109
+ if (typeof this.before === "object" || typeof args.after === "object") {
110
+ this.changes = (0, import_diff.diffJson)(this.before, args.after);
111
+ } else {
112
+ this.changes = (0, import_diff.diffLines)(this.before, args.after);
113
+ }
114
+ } else {
115
+ this.changes = [];
116
+ }
117
+ }
118
+ fileName() {
119
+ return import_path2.default.relative(this.rootPath, this.filePath);
120
+ }
121
+ write() {
122
+ if (this.after) {
123
+ if (typeof this.after === "object") {
124
+ import_fs_extra.default.writeJsonSync(this.filePath, this.after, { spaces: 2 });
125
+ } else {
126
+ import_fs_extra.default.writeFileSync(this.filePath, this.after);
127
+ }
128
+ }
129
+ }
130
+ additions() {
131
+ return this.changes.filter((c) => c.added).length;
132
+ }
133
+ deletions() {
134
+ return this.changes.filter((c) => c.removed).length;
135
+ }
136
+ hasChanges() {
137
+ return this.additions() > 0 || this.deletions() > 0;
138
+ }
139
+ log(args) {
140
+ if (args.diff) {
141
+ this.changes.forEach((part) => {
142
+ if (part.added) {
143
+ process.stdout.write(import_chalk.default.green(part.value));
144
+ } else if (part.removed) {
145
+ process.stdout.write(import_chalk.default.red(part.value));
139
146
  } else {
140
- const newJson = { ...pkgJson, packageManager: pkgManagerString };
141
- if (flags.print) {
142
- console.log(JSON.stringify(newJson, null, 2));
143
- }
144
- if (!flags.dry) {
145
- import_fs_extra.default.writeJsonSync(packageJsonPath, newJson, {
146
- spaces: 2
147
- });
148
- ok(relPackageJsonPath);
149
- modifiedCount++;
150
- unmodifiedCount--;
151
- } else {
152
- skip(relPackageJsonPath, import_chalk2.default.dim(`(dry run)`));
147
+ process.stdout.write(import_chalk.default.dim(part.value));
148
+ }
149
+ });
150
+ console.log(import_os.default.EOL);
151
+ } else {
152
+ console.log(this.after);
153
+ }
154
+ }
155
+ };
156
+
157
+ // src/utils/logger.ts
158
+ var import_chalk2 = __toESM(require("chalk"));
159
+ var Logger = class {
160
+ constructor(args) {
161
+ this.transform = args.transformer;
162
+ this.dry = args.dry;
163
+ }
164
+ modified(...args) {
165
+ console.log(import_chalk2.default.green(` MODIFIED `), ...args, this.dry ? import_chalk2.default.dim(`(dry run)`) : "");
166
+ }
167
+ unchanged(...args) {
168
+ console.log(import_chalk2.default.gray(` UNCHANGED `), ...args, this.dry ? import_chalk2.default.dim(`(dry run)`) : "");
169
+ }
170
+ skipped(...args) {
171
+ console.log(import_chalk2.default.yellow(` SKIPPED `), ...args, this.dry ? import_chalk2.default.dim(`(dry run)`) : "");
172
+ }
173
+ error(...args) {
174
+ console.log(import_chalk2.default.red(` ERROR `), ...args, this.dry ? import_chalk2.default.dim(`(dry run)`) : "");
175
+ }
176
+ info(...args) {
177
+ console.log(import_chalk2.default.bold(` INFO `), ...args, this.dry ? import_chalk2.default.dim(`(dry run)`) : "");
178
+ }
179
+ };
180
+
181
+ // src/runner/Runner.ts
182
+ var Runner = class {
183
+ constructor(options) {
184
+ this.modifications = {};
185
+ this.transform = options.transformer;
186
+ this.rootPath = options.rootPath;
187
+ this.dry = options.dry;
188
+ this.print = options.print;
189
+ this.logger = new Logger(options);
190
+ }
191
+ abortTransform(args) {
192
+ this.logger.error(args.reason);
193
+ return {
194
+ fatalError: new Error(args.reason),
195
+ changes: args.changes || {}
196
+ };
197
+ }
198
+ modifyFile(args) {
199
+ this.modifications[args.filePath] = new FileTransform({
200
+ rootPath: this.rootPath,
201
+ ...args
202
+ });
203
+ }
204
+ finish() {
205
+ const results = { changes: {} };
206
+ Object.keys(this.modifications).forEach((filePath) => {
207
+ const mod = this.modifications[filePath];
208
+ const result = {
209
+ action: "unchanged",
210
+ additions: mod.additions(),
211
+ deletions: mod.deletions()
212
+ };
213
+ if (mod.hasChanges()) {
214
+ if (this.dry) {
215
+ result.action = "skipped";
216
+ this.logger.skipped(import_chalk3.default.dim(mod.fileName()));
217
+ } else {
218
+ try {
219
+ mod.write();
220
+ result.action = "modified";
221
+ this.logger.modified(import_chalk3.default.bold(mod.fileName()));
222
+ } catch (err) {
223
+ let message = "Unknown error";
224
+ if (err instanceof Error) {
225
+ message = err.message;
226
+ }
227
+ result.error = new Error(message);
228
+ result.action = "error";
229
+ this.logger.error(mod.fileName(), message);
153
230
  }
154
231
  }
155
- } catch (err) {
156
- console.error(error);
157
- error(relPackageJsonPath);
232
+ if (this.print) {
233
+ mod.log({ diff: true });
234
+ }
235
+ } else {
236
+ this.logger.unchanged(import_chalk3.default.dim(mod.fileName()));
158
237
  }
238
+ results.changes[mod.fileName()] = result;
239
+ });
240
+ const encounteredError = Object.keys(results.changes).some((fileName) => {
241
+ return results.changes[fileName].action === "error";
242
+ });
243
+ if (encounteredError) {
244
+ return this.abortTransform({
245
+ reason: "Encountered an error while transforming files",
246
+ changes: results.changes
247
+ });
159
248
  }
160
- console.log("All done.");
161
- console.log("Results:");
162
- console.log(import_chalk2.default.red(`${errorCount} errors`));
163
- console.log(import_chalk2.default.yellow(`${skippedCount} skipped`));
164
- console.log(import_chalk2.default.yellow(`${unmodifiedCount} unmodified`));
165
- console.log(import_chalk2.default.green(`${modifiedCount} modified`));
249
+ return results;
166
250
  }
251
+ static logResults(results) {
252
+ const changedFiles = Object.keys(results.changes);
253
+ console.log();
254
+ if (changedFiles.length > 0) {
255
+ console.log(import_chalk3.default.bold(`Results:`));
256
+ const table = {};
257
+ changedFiles.forEach((fileName) => {
258
+ var _a;
259
+ const fileChanges = results.changes[fileName];
260
+ table[fileName] = {
261
+ action: fileChanges.action,
262
+ additions: fileChanges.additions,
263
+ deletions: fileChanges.deletions,
264
+ error: ((_a = fileChanges.error) == null ? void 0 : _a.message) || "None"
265
+ };
266
+ });
267
+ console.table(table);
268
+ console.log();
269
+ }
270
+ }
271
+ };
272
+ var Runner_default = Runner;
273
+
274
+ // src/utils/getTransformerHelpers.ts
275
+ function getTransformerHelpers({
276
+ transformer: transformer2,
277
+ rootPath,
278
+ options
279
+ }) {
280
+ const utilArgs = {
281
+ transformer: transformer2,
282
+ rootPath,
283
+ ...options
284
+ };
285
+ const log = new Logger(utilArgs);
286
+ const runner = new Runner_default(utilArgs);
287
+ return { log, runner };
167
288
  }
289
+
290
+ // src/transforms/add-package-manager.ts
291
+ var TRANSFORMER = "add-package-manager";
292
+ var DESCRIPTION = "Set the `packageManager` key in root `package.json` file";
293
+ var INTRODUCED_IN = "1.1.0";
294
+ function transformer({
295
+ root,
296
+ options
297
+ }) {
298
+ const { log, runner } = getTransformerHelpers({
299
+ transformer: TRANSFORMER,
300
+ rootPath: root,
301
+ options
302
+ });
303
+ log.info(`Set "packageManager" key in root "package.json" file...`);
304
+ const packageManager = getPackageManager({ directory: root });
305
+ if (!packageManager) {
306
+ return runner.abortTransform({
307
+ reason: `Unable to determine package manager for ${root}`
308
+ });
309
+ }
310
+ let version = null;
311
+ try {
312
+ version = getPackageManagerVersion(packageManager, root);
313
+ } catch (err) {
314
+ return runner.abortTransform({
315
+ reason: `Unable to determine package manager version for ${root}`
316
+ });
317
+ }
318
+ const pkgManagerString = `${packageManager}@${version}`;
319
+ const rootPackageJsonPath = import_path3.default.join(root, "package.json");
320
+ const rootPackageJson = import_fs_extra2.default.readJsonSync(rootPackageJsonPath);
321
+ const allWorkspaces = [
322
+ {
323
+ name: "package.json",
324
+ path: root,
325
+ packageJson: {
326
+ ...rootPackageJson,
327
+ packageJsonPath: rootPackageJsonPath
328
+ }
329
+ }
330
+ ];
331
+ for (const workspace of allWorkspaces) {
332
+ const { packageJsonPath, ...pkgJson } = workspace.packageJson;
333
+ const newJson = { ...pkgJson, packageManager: pkgManagerString };
334
+ runner.modifyFile({
335
+ filePath: packageJsonPath,
336
+ after: newJson
337
+ });
338
+ }
339
+ return runner.finish();
340
+ }
341
+ var transformerMeta = {
342
+ name: `${TRANSFORMER}: ${DESCRIPTION}`,
343
+ value: TRANSFORMER,
344
+ introducedIn: INTRODUCED_IN,
345
+ transformer
346
+ };
347
+ var add_package_manager_default = transformerMeta;
168
348
  // Annotate the CommonJS export names for ESM import in node:
169
- 0 && (module.exports = {});
349
+ 0 && (module.exports = {
350
+ transformer
351
+ });