diff --git a/cli/internal/backends/backends.go b/cli/internal/backends/backends.go index aed258fdc7ebb..69d5e41613a39 100644 --- a/cli/internal/backends/backends.go +++ b/cli/internal/backends/backends.go @@ -26,5 +26,5 @@ func GetBackend(cwd string, pkg *fs.PackageJSON) (*api.LanguageBackend, error) { } } - return nil, errors.New(util.Sprintf("could not determine language / package management backend. Please set the \"packageManager\" property in your package.json (${UNDERLINE}https://nodejs.org/api/packages.html#packagemanager)${RESET}")) + return nil, errors.New(util.Sprintf("could not determine package manager. Please set the \"packageManager\" property in your root package.json (${UNDERLINE}https://nodejs.org/api/packages.html#packagemanager)${RESET} or run `npx @turbo/codemod add-package-manager` in the root of your monorepo.")) } diff --git a/docs/pages/docs/reference/codemods.mdx b/docs/pages/docs/reference/codemods.mdx new file mode 100644 index 0000000000000..95f7b9fa89ec2 --- /dev/null +++ b/docs/pages/docs/reference/codemods.mdx @@ -0,0 +1,71 @@ +--- +title: Turborepo Codemods +--- + +# Turborepo Codemods + +Turborepo provides Codemod transformations and automatic migration scripts to help upgrade your Turborepo codebase when a feature is deprecated. + +Codemods are transformations that run on your codebase programmatically. This allows for a large amount of changes to be applied without having to manually go through every file. + +## Usage + +```sh +npx @turbo/codemod +``` + +- `transform` - name of transform, see available transforms below. +- `path` - files or directory to transform +- `--dry` - Do a dry-run, no code will be edited +- `--print` - Prints the changed output for comparison + +## Turborepo 1.x + +### `add-package-manager` + +Transforms the root `package.json` so that `packageManager` key as the detected package manager (`yarn`, `npm`, `pnpm`) and version (e.g. `yarn@1.22.17`). This key is now [supported by Node.js](https://nodejs.org/dist/latest-v17.x/docs/api/packages.html#packagemanager) and is used by Turborepo for faster package manager detection (vs. inferring from just the filesystem alone). + +For example, for Yarn v1: + +```json +// Before +{ + "name": "turborepo-basic", + "version": "0.0.0", + "private": true, + "workspaces": [ + "apps/*", + "packages/*" + ], + ... +} +``` + +```json +// After +{ + "name": "turborepo-basic", + "version": "0.0.0", + "private": true, + "packageManager": "yarn@1.22.17", + "workspaces": [ + "apps/*", + "packages/*" + ], + ... +} +``` + +#### Usage + +Go to your project: + +```sh +cd path-to-your-turborepo/ +``` + +Run the codemod: + +```sh +npx @turbo/codemod add-package-manager +``` diff --git a/docs/pages/docs/reference/meta.json b/docs/pages/docs/reference/meta.json index e1888e1ef5243..9ed1477e0dec6 100644 --- a/docs/pages/docs/reference/meta.json +++ b/docs/pages/docs/reference/meta.json @@ -1,4 +1,5 @@ { "configuration": "Configuration Options", - "command-line-reference": "CLI Usage" + "command-line-reference": "CLI Usage", + "codemods": "Codemods" } diff --git a/package.json b/package.json index a481b7940421c..a8386ed6917fa 100644 --- a/package.json +++ b/package.json @@ -4,10 +4,10 @@ "private": true, "workspaces": { "packages": [ - "packages/*", "docs", "cli", - "create-turbo" + "create-turbo", + "turbo-codemod" ] }, "scripts": { diff --git a/turbo-codemod/LICENSE b/turbo-codemod/LICENSE new file mode 100644 index 0000000000000..fa0086a952236 --- /dev/null +++ b/turbo-codemod/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. \ No newline at end of file diff --git a/turbo-codemod/README.md b/turbo-codemod/README.md new file mode 100644 index 0000000000000..2cbbd6c8789ea --- /dev/null +++ b/turbo-codemod/README.md @@ -0,0 +1,5 @@ +# Turbrepo Codemods + +Turbrepo provides Codemod transformations to help upgrade your Turbrepo codebase when a feature is deprecated. + +Codemods are transformations that run on your codebase programmatically. This allows for a large amount of changes to be applied without having to manually go through every file. diff --git a/turbo-codemod/index.d.ts b/turbo-codemod/index.d.ts new file mode 100644 index 0000000000000..c3a4874cc105c --- /dev/null +++ b/turbo-codemod/index.d.ts @@ -0,0 +1 @@ +declare module "is-git-clean"; diff --git a/turbo-codemod/jest.config.js b/turbo-codemod/jest.config.js new file mode 100644 index 0000000000000..917deee446673 --- /dev/null +++ b/turbo-codemod/jest.config.js @@ -0,0 +1,6 @@ +/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ +module.exports = { + preset: "ts-jest/presets/js-with-ts", + testEnvironment: "node", + transformIgnorePatterns: ["/node_modules/(?!(strip-ansi|ansi-regex)/)"], +}; diff --git a/turbo-codemod/package.json b/turbo-codemod/package.json new file mode 100644 index 0000000000000..8ad378089b701 --- /dev/null +++ b/turbo-codemod/package.json @@ -0,0 +1,56 @@ +{ + "name": "@turbo/codemod", + "version": "1.0.26", + "description": "Provides Codemod transformations to help upgrade your Turborepo codebase when a feature is deprecated.", + "homepage": "https://turborepo.org", + "license": "MPL-2.0", + "repository": { + "type": "git", + "url": "https://github.com/vercel/turborepo", + "directory": "turbo-codemod" + }, + "bugs": { + "url": "https://github.com/vercel/turborepo/issues" + }, + "bin": "dist/index.js", + "scripts": { + "build": "tsup src/*.ts src/transforms/*.ts --format cjs", + "test": "jest", + "lint": "eslint src/**/*.ts" + }, + "dependencies": { + "chalk": "2.4.2", + "execa": "5.0.0", + "find-up": "4.1.0", + "fs-extra": "^10.0.0", + "gradient-string": "^2.0.0", + "inquirer": "^8.0.0", + "is-git-clean": "^1.1.0", + "meow": "^7.1.1", + "ora": "4.0.4", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "update-check": "^1.5.4" + }, + "devDependencies": { + "@types/chalk-animation": "^1.6.0", + "@types/fs-extra": "^9.0.13", + "@types/gradient-string": "^1.1.2", + "@types/inquirer": "^7.3.1", + "@types/jest": "^27.4.0", + "@types/node": "^16.11.12", + "@types/semver": "^7.3.9", + "jest": "^27.4.3", + "semver": "^7.3.5", + "strip-ansi": "^7.0.1", + "ts-jest": "^27.1.1", + "tsup": "^5.10.3", + "typescript": "^4.5.3" + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + } +} diff --git a/turbo-codemod/src/getPackageManagerVersion.ts b/turbo-codemod/src/getPackageManagerVersion.ts new file mode 100644 index 0000000000000..f671a68ea0895 --- /dev/null +++ b/turbo-codemod/src/getPackageManagerVersion.ts @@ -0,0 +1,17 @@ +import { execSync } from "child_process"; +import { WorkspaceImplementations } from "./getWorkspaceImplementation"; + +export const getPackageManagerVersion = ( + ws: WorkspaceImplementations +): string => { + switch (ws) { + case "yarn": + return execSync("yarn --version").toString().trim(); + case "pnpm": + return execSync("pnpm --version").toString().trim(); + case "npm": + return execSync("npm --version").toString().trim(); + default: + throw new Error(`${ws} is not supported`); + } +}; diff --git a/turbo-codemod/src/getWorkspaceImplementation.ts b/turbo-codemod/src/getWorkspaceImplementation.ts new file mode 100644 index 0000000000000..d667795f87d21 --- /dev/null +++ b/turbo-codemod/src/getWorkspaceImplementation.ts @@ -0,0 +1,62 @@ +import findUp from "find-up"; +import path from "path"; + +export type WorkspaceImplementations = "yarn" | "pnpm" | "npm"; + +export interface ImplementationAndLockFile { + implementation: WorkspaceImplementations | undefined; + lockFile: string; +} +const cache: { [cwd: string]: ImplementationAndLockFile } = {}; + +export function getWorkspaceImplementationAndLockFile( + cwd: string +): + | { implementation: WorkspaceImplementations | undefined; lockFile: string } + | undefined { + if (cache[cwd]) { + return cache[cwd]; + } + + const lockFile = findUp.sync( + ["yarn.lock", "pnpm-workspace.yaml", "package-lock.json"], + { + cwd, + } + ); + + if (!lockFile) { + return; + } + + switch (path.basename(lockFile)) { + case "yarn.lock": + cache[cwd] = { + implementation: "yarn", + lockFile, + }; + break; + + case "pnpm-workspace.yaml": + cache[cwd] = { + implementation: "pnpm", + lockFile, + }; + break; + + case "package-lock.json": + cache[cwd] = { + implementation: "npm", + lockFile, + }; + break; + } + + return cache[cwd]; +} + +export function getWorkspaceImplementation( + cwd: string +): WorkspaceImplementations | undefined { + return getWorkspaceImplementationAndLockFile(cwd)?.implementation; +} diff --git a/turbo-codemod/src/git.ts b/turbo-codemod/src/git.ts new file mode 100644 index 0000000000000..c7bdc10bf0570 --- /dev/null +++ b/turbo-codemod/src/git.ts @@ -0,0 +1,32 @@ +import chalk from "chalk"; +import isGitClean from "is-git-clean"; + +export function checkGitStatus(force: boolean) { + let clean = false; + let errorMessage = "Unable to determine if git directory is clean"; + try { + clean = isGitClean.sync(process.cwd()); + errorMessage = "Git directory is not clean"; + } catch (err: any) { + if (err && err.stderr && err.stderr.indexOf("Not a git repository") >= 0) { + clean = true; + } + } + + if (!clean) { + if (force) { + console.log(`WARNING: ${errorMessage}. Forcibly continuing...`); + } else { + console.log("Thank you for using turbo-migrate!"); + console.log( + chalk.yellow( + "\nBut before we continue, please stash or commit your git changes." + ) + ); + console.log( + "\nYou may use the --force flag to override this safety check." + ); + process.exit(1); + } + } +} diff --git a/turbo-codemod/src/index.ts b/turbo-codemod/src/index.ts new file mode 100644 index 0000000000000..97734a0287d21 --- /dev/null +++ b/turbo-codemod/src/index.ts @@ -0,0 +1,159 @@ +#!/usr/bin/env node + +import chalk from "chalk"; +import globby from "globby"; +import inquirer from "inquirer"; +import meow from "meow"; +import checkForUpdate from "update-check"; +import cliPkgJson from "../package.json"; +import { getWorkspaceImplementation } from "./getWorkspaceImplementation"; +import { checkGitStatus } from "./git"; +import { runTransform } from "./runTransform"; + +const help = ` + Usage: + $ npx turbo-migrate <...options> + + If is not provided up front you will be prompted for it. + + Options: + --force Bypass Git safety checks and forcibly run codemods + --dry Dry run (no changes are made to files) + --print Print transformed files to your terminal + --help, -h Show this help message + --version, -v Show the version of this script +`; + +const TRANSFORMER_INQUIRER_CHOICES = [ + { + name: "add-package-manager: Set the `packageManager` key in root package.json file", + value: "add-package-manager", + }, +]; + +run() + .then(notifyUpdate) + .catch(async (reason) => { + console.log(); + console.log("Aborting installation."); + if (reason.command) { + console.log(` ${chalk.cyan(reason.command)} has failed.`); + } else { + console.log(chalk.red("Unexpected error. Please report it as a bug:")); + console.log(reason); + } + console.log(); + + await notifyUpdate(); + + process.exit(1); + }); + +async function run() { + let cli = meow(help, { + booleanDefault: undefined, + flags: { + help: { type: "boolean", default: false, alias: "h" }, + force: { type: "boolean", default: false }, + dry: { type: "boolean", default: false }, + print: { type: "boolean", default: false }, + version: { type: "boolean", default: false, alias: "v" }, + }, + description: "Codemods for updating Turborepo codebases.", + }); + + if (cli.flags.help) cli.showHelp(); + if (cli.flags.version) cli.showVersion(); + + // check git status + if (!cli.flags.dry) { + checkGitStatus(cli.flags.force); + } + + if ( + cli.input[0] && + !TRANSFORMER_INQUIRER_CHOICES.find((x) => x.value === cli.input[0]) + ) { + console.error("Invalid transform choice, pick one of:"); + console.error( + TRANSFORMER_INQUIRER_CHOICES.map((x) => "- " + x.value).join("\n") + ); + process.exit(1); + } + const answers = await inquirer.prompt([ + { + type: "input", + name: "files", + message: "On which directory should the codemods be applied?", + when: !cli.input[1], + default: ".", + // validate: () => + filter: (files) => files.trim(), + }, + { + type: "list", + name: "transformer", + message: "Which transform would you like to apply?", + when: !cli.input[0], + pageSize: TRANSFORMER_INQUIRER_CHOICES.length, + choices: TRANSFORMER_INQUIRER_CHOICES, + }, + ]); + + const { files, transformer } = answers; + + const filesBeforeExpansion = cli.input[1] || files; + const filesExpanded = expandFilePathsIfNeeded([filesBeforeExpansion]); + + const selectedTransformer = cli.input[0] || transformer; + + if (!filesExpanded.length) { + console.log(`No files found matching ${filesBeforeExpansion.join(" ")}`); + return null; + } + + return runTransform({ + files: filesExpanded, + flags: cli.flags, + transformer: selectedTransformer, + }); +} + +const update = checkForUpdate(cliPkgJson).catch(() => null); + +async function notifyUpdate(): Promise { + try { + const res = await update; + if (res?.latest) { + const ws = getWorkspaceImplementation(process.cwd()); + + console.log(); + console.log( + chalk.yellow.bold("A new version of `@turbo/codemod` is available!") + ); + console.log( + "You can update by running: " + + chalk.cyan( + ws === "yarn" + ? "yarn global add @turbo/codemod" + : ws === "pnpm" + ? "pnpm i -g @turbo/codemod" + : "npm i -g @turbo/codemod" + ) + ); + console.log(); + } + process.exit(); + } catch (_e: any) { + // ignore error + } +} + +function expandFilePathsIfNeeded(filesBeforeExpansion: string[]) { + const shouldExpandFiles = filesBeforeExpansion.some((file) => + file.includes("*") + ); + return shouldExpandFiles + ? globby.sync(filesBeforeExpansion) + : filesBeforeExpansion; +} diff --git a/turbo-codemod/src/runTransform.ts b/turbo-codemod/src/runTransform.ts new file mode 100644 index 0000000000000..841a216252157 --- /dev/null +++ b/turbo-codemod/src/runTransform.ts @@ -0,0 +1,20 @@ +import path from "path"; + +import { Flags } from "./types"; + +export const transformerDirectory = path.join(__dirname, "transforms"); + +export interface RunTransformOptions { + files: string[]; + flags: Flags; + transformer: string; +} + +export function runTransform({ + files, + flags, + transformer, +}: RunTransformOptions) { + const transformerPath = path.join(transformerDirectory, `${transformer}.js`); + return require(transformerPath).default(files, flags); +} diff --git a/turbo-codemod/src/transforms/add-package-manager.ts b/turbo-codemod/src/transforms/add-package-manager.ts new file mode 100644 index 0000000000000..e8f83933c7fac --- /dev/null +++ b/turbo-codemod/src/transforms/add-package-manager.ts @@ -0,0 +1,87 @@ +import { Flags } from "../types"; +import path from "path"; +import { getWorkspaceImplementation } from "../getWorkspaceImplementation"; +import { getPackageManagerVersion } from "../getPackageManagerVersion"; +import fs from "fs-extra"; +import chalk from "chalk"; + +export default function addPackageManager(files: string[], flags: Flags) { + if (files.length === 1) { + const dir = files[0]; + const root = path.resolve(process.cwd(), dir); + console.log(`Set "packageManager" key in root "package.json" file...`); + const packageManager = getWorkspaceImplementation(root); + if (!packageManager) { + error(`Unable to determine package manager for ${dir}`); + process.exit(1); + } + // handle workspaces... + const version = getPackageManagerVersion(packageManager); + const pkgManagerString = `${packageManager}@${version}`; + const rootPackageJsonPath = path.join(root, "package.json"); + const rootPackageJson = fs.readJsonSync(rootPackageJsonPath); + const allWorkspaces = [ + { + name: "package.json", + path: root, + packageJson: { + ...rootPackageJson, + packageJsonPath: rootPackageJsonPath, + }, + }, + ]; + + let modifiedCount = 0; + let skippedCount = 0; + let errorCount = 0; + let unmodifiedCount = allWorkspaces.length; + console.log(`Found ${unmodifiedCount} files for modification...`); + for (const workspace of allWorkspaces) { + const { packageJsonPath, ...pkgJson } = workspace.packageJson; + const relPackageJsonPath = path.relative(root, packageJsonPath); + try { + if (pkgJson.packageManager === pkgManagerString) { + skip( + relPackageJsonPath, + chalk.dim(`(already set to ${pkgManagerString})`) + ); + } else { + const newJson = { ...pkgJson, packageManager: pkgManagerString }; + if (flags.print) { + console.log(JSON.stringify(newJson, null, 2)); + } + if (!flags.dry) { + fs.writeJsonSync(packageJsonPath, newJson, { + spaces: 2, + }); + + ok(relPackageJsonPath); + modifiedCount++; + unmodifiedCount--; + } else { + skip(relPackageJsonPath, chalk.dim(`(dry run)`)); + } + } + } catch (err) { + console.error(error); + error(relPackageJsonPath); + } + } + console.log("All done."); + console.log("Results:"); + console.log(chalk.red(`${errorCount} errors`)); + console.log(chalk.yellow(`${skippedCount} skipped`)); + console.log(chalk.yellow(`${unmodifiedCount} unmodified`)); + console.log(chalk.green(`${modifiedCount} modified`)); + } +} + +function skip(...args: any[]) { + console.log(chalk.yellow.inverse(` SKIP `), ...args); +} +function error(...args: any[]) { + console.log(chalk.red.inverse(` ERROR `), ...args); +} +function ok(...args: any[]) { + console.log(chalk.green.inverse(` OK `), ...args); +} diff --git a/turbo-codemod/src/types.ts b/turbo-codemod/src/types.ts new file mode 100644 index 0000000000000..c5515804b2c0f --- /dev/null +++ b/turbo-codemod/src/types.ts @@ -0,0 +1,5 @@ +export interface Flags { + dry: boolean; + force: boolean; + print: boolean; +} diff --git a/turbo-codemod/tsconfig.json b/turbo-codemod/tsconfig.json new file mode 100644 index 0000000000000..f097aac870ff1 --- /dev/null +++ b/turbo-codemod/tsconfig.json @@ -0,0 +1,17 @@ +{ + "exclude": ["templates"], + "compilerOptions": { + "lib": ["ES2019"], + "target": "ES2019", + "moduleResolution": "node", + "allowSyntheticDefaultImports": true, + "strict": true, + "declaration": true, + "emitDeclarationOnly": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "outDir": "dist", + "rootDir": ".", + "allowJs": true + } +} diff --git a/yarn.lock b/yarn.lock index 81b169d5106e9..473fee5d9be9f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1749,6 +1749,11 @@ aria-query@^4.2.2: "@babel/runtime" "^7.10.2" "@babel/runtime-corejs3" "^7.10.2" +array-differ@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/array-differ/-/array-differ-1.0.0.tgz#eff52e3758249d33be402b8bb8e564bb2b5d4031" + integrity sha1-7/UuN1gknTO+QCuLuOVkuytdQDE= + array-includes@^3.1.3, array-includes@^3.1.4: version "3.1.4" resolved "https://registry.yarnpkg.com/array-includes/-/array-includes-3.1.4.tgz#f5b493162c760f3539631f005ba2bb46acb45ba9" @@ -1760,11 +1765,23 @@ array-includes@^3.1.3, array-includes@^3.1.4: get-intrinsic "^1.1.1" is-string "^1.0.7" +array-union@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39" + integrity sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk= + dependencies: + array-uniq "^1.0.1" + array-union@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/array-union/-/array-union-2.1.0.tgz#b798420adbeb1de828d84acd8a2e23d3efe85e8d" integrity sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw== +array-uniq@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/array-uniq/-/array-uniq-1.0.3.tgz#af6ac877a25cc7f74e058894753858dfdb24fdb6" + integrity sha1-r2rId6Jcx/dOBYiUdThY39sk/bY= + array.prototype.flat@^1.2.5: version "1.2.5" resolved "https://registry.yarnpkg.com/array.prototype.flat/-/array.prototype.flat-1.2.5.tgz#07e0975d84bbc7c48cd1879d609e682598d33e13" @@ -1783,7 +1800,7 @@ array.prototype.flatmap@^1.2.5: define-properties "^1.1.3" es-abstract "^1.19.0" -arrify@^1.0.1: +arrify@^1.0.0, arrify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d" integrity sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0= @@ -2632,6 +2649,14 @@ cross-env@^7.0.3: dependencies: cross-spawn "^7.0.1" +cross-spawn-async@^2.1.1: + version "2.2.5" + resolved "https://registry.yarnpkg.com/cross-spawn-async/-/cross-spawn-async-2.2.5.tgz#845ff0c0834a3ded9d160daca6d390906bb288cc" + integrity sha1-hF/wwINKPe2dFg2sptOQkGuyiMw= + dependencies: + lru-cache "^4.0.0" + which "^1.2.8" + cross-spawn@^5.0.1: version "5.1.0" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-5.1.0.tgz#e8bd0efee58fcff6f8f94510a0a554bbfa235449" @@ -3583,6 +3608,18 @@ execa@5.0.0: signal-exit "^3.0.3" strip-final-newline "^2.0.0" +execa@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/execa/-/execa-0.4.0.tgz#4eb6467a36a095fabb2970ff9d5e3fb7bce6ebc3" + integrity sha1-TrZGejaglfq7KXD/nV4/t7zm68M= + dependencies: + cross-spawn-async "^2.1.1" + is-stream "^1.1.0" + npm-run-path "^1.0.0" + object-assign "^4.0.1" + path-key "^1.0.0" + strip-eof "^1.0.0" + execa@^0.8.0: version "0.8.0" resolved "https://registry.yarnpkg.com/execa/-/execa-0.8.0.tgz#d8d76bbc1b55217ed190fd6dd49d3c774ecfc8da" @@ -3780,14 +3817,7 @@ find-cache-dir@3.3.1: make-dir "^3.0.2" pkg-dir "^4.1.0" -find-up@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" - integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= - dependencies: - locate-path "^2.0.0" - -find-up@^4.0.0, find-up@^4.1.0: +find-up@4.1.0, find-up@^4.0.0, find-up@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== @@ -3795,6 +3825,13 @@ find-up@^4.0.0, find-up@^4.1.0: locate-path "^5.0.0" path-exists "^4.0.0" +find-up@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7" + integrity sha1-RdG35QbHF93UgndaK3eSCjwMV6c= + dependencies: + locate-path "^2.0.0" + flat-cache@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-3.0.4.tgz#61b0338302b2fe9f957dcc32fc2a87f1c3048b11" @@ -4534,6 +4571,15 @@ is-generator-function@^1.0.7: resolved "https://registry.yarnpkg.com/is-generator-function/-/is-generator-function-1.0.9.tgz#e5f82c2323673e7fcad3d12858c83c4039f6399c" integrity sha512-ZJ34p1uvIfptHCN7sFTjGibB9/oBg17sHqzDLfuwhvmN/qLVvIQXRQ8licZQ35WJ8KuEQt/etnnzQFI9C9Ue/A== +is-git-clean@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-git-clean/-/is-git-clean-1.1.0.tgz#13abd6dda711bb08aafd42604da487845ddcf88d" + integrity sha1-E6vW3acRuwiq/UJgTaSHhF3c+I0= + dependencies: + execa "^0.4.0" + is-obj "^1.0.1" + multimatch "^2.1.0" + is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3, is-glob@~4.0.1: version "4.0.3" resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" @@ -4584,6 +4630,11 @@ is-number@^7.0.0: resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== +is-obj@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" + integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= + is-object@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/is-object/-/is-object-1.0.2.tgz#a56552e1c665c9e950b4a025461da87e72f86fcf" @@ -5477,7 +5528,7 @@ lowercase-keys@1.0.0, lowercase-keys@^1.0.0: resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-1.0.0.tgz#4e3366b39e7f5457e35f1324bdf6f88d0bfc7306" integrity sha1-TjNms55/VFfjXxMkvfb4jQv8cwY= -lru-cache@^4.0.1: +lru-cache@^4.0.0, lru-cache@^4.0.1: version "4.1.5" resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.5.tgz#8bbe50ea85bed59bc9e33dcab8235ee9bcf443cd" integrity sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g== @@ -6164,7 +6215,7 @@ minimalistic-crypto-utils@^1.0.1: resolved "https://registry.yarnpkg.com/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz#f6c00c1c0b082246e5c4d99dfb8c7c083b2b582a" integrity sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo= -minimatch@^3.0.4: +minimatch@^3.0.0, minimatch@^3.0.4: version "3.0.4" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== @@ -6205,6 +6256,16 @@ ms@2.1.2, ms@^2.1.1: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== +multimatch@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/multimatch/-/multimatch-2.1.0.tgz#9c7906a22fb4c02919e2f5f75161b4cdbd4b2a2b" + integrity sha1-nHkGoi+0wCkZ4vX3UWG0zb1LKis= + dependencies: + array-differ "^1.0.0" + array-union "^1.0.1" + arrify "^1.0.0" + minimatch "^3.0.0" + mute-stream@0.0.8: version "0.0.8" resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-0.0.8.tgz#1630c42b2251ff81e2a283de96a5497ea92e5e0d" @@ -6384,6 +6445,13 @@ normalize-url@2.0.1: query-string "^5.0.1" sort-keys "^2.0.0" +npm-run-path@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-1.0.0.tgz#f5c32bf595fe81ae927daec52e82f8b000ac3c8f" + integrity sha1-9cMr9ZX+ga6Sfa7FLoL4sACsPI8= + dependencies: + path-key "^1.0.0" + npm-run-path@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f" @@ -6716,6 +6784,11 @@ path-is-absolute@^1.0.0: resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= +path-key@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/path-key/-/path-key-1.0.0.tgz#5d53d578019646c0d68800db4e146e6bdc2ac7af" + integrity sha1-XVPVeAGWRsDWiADbThRua9wqx68= + path-key@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/path-key/-/path-key-2.0.1.tgz#411cadb574c5a140d3a4b1910d40d80cc9f40b40" @@ -8777,7 +8850,7 @@ which-typed-array@^1.1.2: has-symbols "^1.0.1" is-typed-array "^1.1.3" -which@^1.2.9: +which@^1.2.8, which@^1.2.9: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==