diff options
Diffstat (limited to 'packages/turbo-workspaces')
55 files changed, 3539 insertions, 0 deletions
diff --git a/packages/turbo-workspaces/LICENSE b/packages/turbo-workspaces/LICENSE new file mode 100644 index 0000000..fa0086a --- /dev/null +++ b/packages/turbo-workspaces/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/packages/turbo-workspaces/README.md b/packages/turbo-workspaces/README.md new file mode 100644 index 0000000..60d8024 --- /dev/null +++ b/packages/turbo-workspaces/README.md @@ -0,0 +1,49 @@ +# `@turbo/workspaces` + +Easily convert your repo between package managers. Supports both non-monorepos and monorepos (using package manager workspaces). + +## CLI + +```sh +Usage: @turbo/workspaces [options] [command] + +Tools for working with package manager workspaces + +Options: + -v, --version output the current version + -h, --help display help for command + +Commands: + convert [options] [path] [package-manager] Convert project between workspace managers + summary [path] Display a summary of the specified project + help [command] display help for command +``` + +## Node API + +Methods are also available via the Node API: + +```js +import { convert, getWorkspaceDetails } from "@turbo/workspaces"; + +// detect the package manager +const project = getWorkspaceDetails({ + root: process.cwd(), +}); + +// if the package manager is not pnpm, convert to pnpm +if (project.packageManager !== "pnpm") { + await convert({ + root: process.cwd(), + to: "pnpm", + options: { + dry: false, + install: true, + }, + }); +} +``` + +--- + +For more information about Turborepo, visit [turbo.build/repo](https://turbo.build/repo) and follow us on Twitter ([@turborepo](https://twitter.com/turborepo))! diff --git a/packages/turbo-workspaces/__fixtures__/invalid/index.js b/packages/turbo-workspaces/__fixtures__/invalid/index.js new file mode 100644 index 0000000..cd01831 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/invalid/index.js @@ -0,0 +1 @@ +// nothing here diff --git a/packages/turbo-workspaces/__fixtures__/npm/monorepo/apps/docs/package.json b/packages/turbo-workspaces/__fixtures__/npm/monorepo/apps/docs/package.json new file mode 100644 index 0000000..e488bc3 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/monorepo/apps/docs/package.json @@ -0,0 +1,11 @@ +{ + "name": "docs", + "version": "1.0.0", + "private": true, + "dependencies": { + "ui": "*" + }, + "devDependencies": { + "tsconfig": "1.0.0" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/monorepo/apps/web/package.json b/packages/turbo-workspaces/__fixtures__/npm/monorepo/apps/web/package.json new file mode 100644 index 0000000..163cee3 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/monorepo/apps/web/package.json @@ -0,0 +1,11 @@ +{ + "name": "web", + "version": "0.0.0", + "private": true, + "dependencies": { + "ui": "*" + }, + "devDependencies": { + "tsconfig": "*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/monorepo/package-lock.json b/packages/turbo-workspaces/__fixtures__/npm/monorepo/package-lock.json new file mode 100644 index 0000000..6b6842b --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/monorepo/package-lock.json @@ -0,0 +1,385 @@ +{ + "name": "npm-workspaces", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "npm-workspaces", + "version": "0.0.0", + "workspaces": [ + "apps/*", + "packages/*" + ], + "engines": { + "node": ">=14.0.0" + } + }, + "apps/docs": { + "version": "1.0.0", + "dependencies": { + "ui": "*" + }, + "devDependencies": { + "tsconfig": "1.0.0" + } + }, + "apps/docs/node_modules/tsconfig": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-1.0.0.tgz", + "integrity": "sha512-26lVKF/0MdkCnaU9t45wH8bsVH8nRKRt0zrvku/j/dD5uE+8v9vDfBS8/sVRs6ZjADXbcFvirN93kOpxdIszqQ==", + "dev": true, + "dependencies": { + "globby": "^2.1.0", + "xtend": "^4.0.0" + } + }, + "apps/web": { + "version": "0.0.0", + "dependencies": { + "ui": "*" + }, + "devDependencies": { + "tsconfig": "*" + } + }, + "node_modules/array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha512-Dxr6QJj/RdU/hCaBjOfxW+q6lyuVE6JFWIrAUpuOOhoJJoQ99cUn3igRaHVB5P9WrgFVN0FfArM3x0cueOU8ng==", + "dev": true, + "dependencies": { + "array-uniq": "^1.0.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/async": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha512-nSVgobk4rv61R9PUSDtYt7mPVB2olxNR5RWJcAsH676/ef11bUZwvu7+RGYrYauVdDPcO519v68wRhXQtxsV9w==", + "dev": true + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "node_modules/docs": { + "resolved": "apps/docs", + "link": true + }, + "node_modules/glob": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", + "integrity": "sha512-c9IPMazfRITpmAAKi22dK1VKxGDX9ehhqfABDriL/lzO92xcUKEJPQHrVA/2YHSNFB4iFlykVmWvwo48nr3OxA==", + "dev": true, + "dependencies": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/globby": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-2.1.0.tgz", + "integrity": "sha512-CqRID2dMaN4Zi9PANiQHhmKaGu7ZASehBLnaDogjR9L3L1EqAGFhflafT0IrSN/zm9xFk+KMTXZCN8pUYOiO/Q==", + "dev": true, + "dependencies": { + "array-union": "^1.0.1", + "async": "^1.2.1", + "glob": "^5.0.3", + "object-assign": "^3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/object-assign": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", + "integrity": "sha512-jHP15vXVGeVh1HuaA2wY6lxk+whK/x4KBG88VXeRma7CCun7iGD5qPc4eYykQ9sdQvg8jkwFKsSxHln2ybW3xQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tsconfig": { + "resolved": "packages/tsconfig", + "link": true + }, + "node_modules/ui": { + "resolved": "packages/ui", + "link": true + }, + "node_modules/web": { + "resolved": "apps/web", + "link": true + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true, + "engines": { + "node": ">=0.4" + } + }, + "packages/tsconfig": { + "version": "1.0.0" + }, + "packages/ui": { + "version": "0.0.0", + "devDependencies": { + "tsconfig": "*" + } + } + }, + "dependencies": { + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha512-Dxr6QJj/RdU/hCaBjOfxW+q6lyuVE6JFWIrAUpuOOhoJJoQ99cUn3igRaHVB5P9WrgFVN0FfArM3x0cueOU8ng==", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha512-MNha4BWQ6JbwhFhj03YK552f7cb3AzoE8SzeljgChvL1dl3IcvggXVz1DilzySZkCja+CXuZbdW7yATchWn8/Q==", + "dev": true + }, + "async": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/async/-/async-1.5.2.tgz", + "integrity": "sha512-nSVgobk4rv61R9PUSDtYt7mPVB2olxNR5RWJcAsH676/ef11bUZwvu7+RGYrYauVdDPcO519v68wRhXQtxsV9w==", + "dev": true + }, + "balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "docs": { + "version": "file:apps/docs", + "requires": { + "tsconfig": "1.0.0", + "ui": "*" + }, + "dependencies": { + "tsconfig": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tsconfig/-/tsconfig-1.0.0.tgz", + "integrity": "sha512-26lVKF/0MdkCnaU9t45wH8bsVH8nRKRt0zrvku/j/dD5uE+8v9vDfBS8/sVRs6ZjADXbcFvirN93kOpxdIszqQ==", + "dev": true, + "requires": { + "globby": "^2.1.0", + "xtend": "^4.0.0" + } + } + } + }, + "glob": { + "version": "5.0.15", + "resolved": "https://registry.npmjs.org/glob/-/glob-5.0.15.tgz", + "integrity": "sha512-c9IPMazfRITpmAAKi22dK1VKxGDX9ehhqfABDriL/lzO92xcUKEJPQHrVA/2YHSNFB4iFlykVmWvwo48nr3OxA==", + "dev": true, + "requires": { + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "2 || 3", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "globby": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-2.1.0.tgz", + "integrity": "sha512-CqRID2dMaN4Zi9PANiQHhmKaGu7ZASehBLnaDogjR9L3L1EqAGFhflafT0IrSN/zm9xFk+KMTXZCN8pUYOiO/Q==", + "dev": true, + "requires": { + "array-union": "^1.0.1", + "async": "^1.2.1", + "glob": "^5.0.3", + "object-assign": "^3.0.0" + } + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "object-assign": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-3.0.0.tgz", + "integrity": "sha512-jHP15vXVGeVh1HuaA2wY6lxk+whK/x4KBG88VXeRma7CCun7iGD5qPc4eYykQ9sdQvg8jkwFKsSxHln2ybW3xQ==", + "dev": true + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true + }, + "tsconfig": { + "version": "file:packages/tsconfig" + }, + "ui": { + "version": "file:packages/ui", + "requires": { + "tsconfig": "*" + } + }, + "web": { + "version": "file:apps/web", + "requires": { + "tsconfig": "*", + "ui": "*" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, + "xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "dev": true + } + } +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/monorepo/package.json b/packages/turbo-workspaces/__fixtures__/npm/monorepo/package.json new file mode 100644 index 0000000..b1242c7 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/monorepo/package.json @@ -0,0 +1,14 @@ +{ + "name": "npm-workspaces", + "version": "0.0.0", + "private": true, + "workspaces": [ + "apps/*", + "packages/*" + ], + "engines": { + "node": ">=14.0.0" + }, + "dependencies": {}, + "packageManager": "npm@8.19.4" +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/monorepo/packages/tsconfig/package.json b/packages/turbo-workspaces/__fixtures__/npm/monorepo/packages/tsconfig/package.json new file mode 100644 index 0000000..0d32af3 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/monorepo/packages/tsconfig/package.json @@ -0,0 +1,5 @@ +{ + "name": "tsconfig", + "version": "1.0.0", + "private": true +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/monorepo/packages/ui/package.json b/packages/turbo-workspaces/__fixtures__/npm/monorepo/packages/ui/package.json new file mode 100644 index 0000000..1e05d1a --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/monorepo/packages/ui/package.json @@ -0,0 +1,7 @@ +{ + "name": "ui", + "version": "0.0.0", + "devDependencies": { + "tsconfig": "*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/non-monorepo/package-lock.json b/packages/turbo-workspaces/__fixtures__/npm/non-monorepo/package-lock.json new file mode 100644 index 0000000..067bf21 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/non-monorepo/package-lock.json @@ -0,0 +1,12 @@ +{ + "name": "npm", + "version": "0.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "npm", + "version": "0.0.0" + } + } +} diff --git a/packages/turbo-workspaces/__fixtures__/npm/non-monorepo/package.json b/packages/turbo-workspaces/__fixtures__/npm/non-monorepo/package.json new file mode 100644 index 0000000..47f30c6 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/npm/non-monorepo/package.json @@ -0,0 +1,6 @@ +{ + "name": "npm", + "version": "0.0.0", + "private": true, + "packageManager": "npm@8.19.4" +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/apps/docs/package.json b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/apps/docs/package.json new file mode 100644 index 0000000..835a58f --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/apps/docs/package.json @@ -0,0 +1,11 @@ +{ + "name": "docs", + "version": "0.0.0", + "private": true, + "dependencies": { + "ui": "workspace:*" + }, + "devDependencies": { + "tsconfig": "workspace:*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/apps/web/package.json b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/apps/web/package.json new file mode 100644 index 0000000..77c2e0f --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/apps/web/package.json @@ -0,0 +1,11 @@ +{ + "name": "web", + "version": "0.0.0", + "private": true, + "dependencies": { + "ui": "workspace:*" + }, + "devDependencies": { + "tsconfig": "workspace:*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/package.json b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/package.json new file mode 100644 index 0000000..e3627d8 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/package.json @@ -0,0 +1,10 @@ +{ + "name": "pnpm-workspaces", + "version": "0.0.0", + "private": true, + "engines": { + "node": ">=14.0.0" + }, + "dependencies": {}, + "packageManager": "pnpm@7.12.1" +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/packages/tsconfig/package.json b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/packages/tsconfig/package.json new file mode 100644 index 0000000..3f40629 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/packages/tsconfig/package.json @@ -0,0 +1,5 @@ +{ + "name": "tsconfig", + "version": "0.0.0", + "private": true +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/packages/ui/package.json b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/packages/ui/package.json new file mode 100644 index 0000000..601ca4a --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/packages/ui/package.json @@ -0,0 +1,7 @@ +{ + "name": "ui", + "version": "0.0.0", + "devDependencies": { + "tsconfig": "workspace:*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/pnpm-lock.yaml b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/pnpm-lock.yaml new file mode 100644 index 0000000..84c04af --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/pnpm-lock.yaml @@ -0,0 +1,33 @@ +lockfileVersion: 5.4 + +importers: + + .: + specifiers: {} + + apps/docs: + specifiers: + tsconfig: workspace:* + ui: workspace:* + dependencies: + ui: link:../../packages/ui + devDependencies: + tsconfig: link:../../packages/tsconfig + + apps/web: + specifiers: + tsconfig: workspace:* + ui: workspace:* + dependencies: + ui: link:../../packages/ui + devDependencies: + tsconfig: link:../../packages/tsconfig + + packages/tsconfig: + specifiers: {} + + packages/ui: + specifiers: + tsconfig: workspace:* + devDependencies: + tsconfig: link:../tsconfig diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/pnpm-workspace.yaml b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/pnpm-workspace.yaml new file mode 100644 index 0000000..3ff5faa --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/monorepo/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +packages: + - "apps/*" + - "packages/*" diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/non-monorepo/package.json b/packages/turbo-workspaces/__fixtures__/pnpm/non-monorepo/package.json new file mode 100644 index 0000000..00885fa --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/non-monorepo/package.json @@ -0,0 +1,8 @@ +{ + "name": "pnpm", + "version": "0.0.0", + "private": true, + "dependencies": {}, + "devDependencies": {}, + "packageManager": "pnpm@7.12.1" +} diff --git a/packages/turbo-workspaces/__fixtures__/pnpm/non-monorepo/pnpm-lock.yaml b/packages/turbo-workspaces/__fixtures__/pnpm/non-monorepo/pnpm-lock.yaml new file mode 100644 index 0000000..84c04af --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/pnpm/non-monorepo/pnpm-lock.yaml @@ -0,0 +1,33 @@ +lockfileVersion: 5.4 + +importers: + + .: + specifiers: {} + + apps/docs: + specifiers: + tsconfig: workspace:* + ui: workspace:* + dependencies: + ui: link:../../packages/ui + devDependencies: + tsconfig: link:../../packages/tsconfig + + apps/web: + specifiers: + tsconfig: workspace:* + ui: workspace:* + dependencies: + ui: link:../../packages/ui + devDependencies: + tsconfig: link:../../packages/tsconfig + + packages/tsconfig: + specifiers: {} + + packages/ui: + specifiers: + tsconfig: workspace:* + devDependencies: + tsconfig: link:../tsconfig diff --git a/packages/turbo-workspaces/__fixtures__/yarn/monorepo/apps/docs/package.json b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/apps/docs/package.json new file mode 100644 index 0000000..d3a490c --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/apps/docs/package.json @@ -0,0 +1,11 @@ +{ + "name": "docs", + "version": "0.0.0", + "private": true, + "dependencies": { + "ui": "*" + }, + "devDependencies": { + "tsconfig": "*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/yarn/monorepo/apps/web/package.json b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/apps/web/package.json new file mode 100644 index 0000000..163cee3 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/apps/web/package.json @@ -0,0 +1,11 @@ +{ + "name": "web", + "version": "0.0.0", + "private": true, + "dependencies": { + "ui": "*" + }, + "devDependencies": { + "tsconfig": "*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/yarn/monorepo/package.json b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/package.json new file mode 100644 index 0000000..002944b --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/package.json @@ -0,0 +1,14 @@ +{ + "name": "yarn-workspaces", + "version": "0.0.0", + "private": true, + "workspaces": [ + "apps/*", + "packages/*" + ], + "engines": { + "node": ">=14.0.0" + }, + "dependencies": {}, + "packageManager": "yarn@1.22.19" +} diff --git a/packages/turbo-workspaces/__fixtures__/yarn/monorepo/packages/tsconfig/package.json b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/packages/tsconfig/package.json new file mode 100644 index 0000000..3f40629 --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/packages/tsconfig/package.json @@ -0,0 +1,5 @@ +{ + "name": "tsconfig", + "version": "0.0.0", + "private": true +} diff --git a/packages/turbo-workspaces/__fixtures__/yarn/monorepo/packages/ui/package.json b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/packages/ui/package.json new file mode 100644 index 0000000..1e05d1a --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/packages/ui/package.json @@ -0,0 +1,7 @@ +{ + "name": "ui", + "version": "0.0.0", + "devDependencies": { + "tsconfig": "*" + } +} diff --git a/packages/turbo-workspaces/__fixtures__/yarn/monorepo/yarn.lock b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/yarn.lock new file mode 100644 index 0000000..fb57ccd --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/monorepo/yarn.lock @@ -0,0 +1,4 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + diff --git a/packages/turbo-workspaces/__fixtures__/yarn/non-monorepo/package.json b/packages/turbo-workspaces/__fixtures__/yarn/non-monorepo/package.json new file mode 100644 index 0000000..970aa3e --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/non-monorepo/package.json @@ -0,0 +1,8 @@ +{ + "name": "yarn", + "version": "0.0.0", + "private": true, + "dependencies": {}, + "devDependencies": {}, + "packageManager": "yarn@1.22.19" +} diff --git a/packages/turbo-workspaces/__fixtures__/yarn/non-monorepo/yarn.lock b/packages/turbo-workspaces/__fixtures__/yarn/non-monorepo/yarn.lock new file mode 100644 index 0000000..fb57ccd --- /dev/null +++ b/packages/turbo-workspaces/__fixtures__/yarn/non-monorepo/yarn.lock @@ -0,0 +1,4 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + diff --git a/packages/turbo-workspaces/__tests__/index.test.ts b/packages/turbo-workspaces/__tests__/index.test.ts new file mode 100644 index 0000000..21753be --- /dev/null +++ b/packages/turbo-workspaces/__tests__/index.test.ts @@ -0,0 +1,85 @@ +import path from "path"; +import * as turboUtils from "@turbo/utils"; +import { setupTestFixtures } from "@turbo/test-utils"; +import { getWorkspaceDetails, convert } from "../src"; +import { generateConvertMatrix } from "./test-utils"; +import execa from "execa"; + +jest.mock("execa", () => jest.fn()); + +describe("Node entrypoint", () => { + const { useFixture } = setupTestFixtures({ + directory: path.join(__dirname, "../"), + }); + + describe("convert", () => { + test.each(generateConvertMatrix())( + "detects $fixtureType project using $fixtureManager and converts to $toManager (interactive=$interactive dry=$dry install=$install)", + async ({ + fixtureManager, + fixtureType, + toManager, + interactive, + dry, + install, + }) => { + const mockedGetAvailablePackageManagers = jest + .spyOn(turboUtils, "getAvailablePackageManagers") + .mockResolvedValue({ + npm: { + available: true, + version: "8.19.2", + }, + yarn: { + available: true, + version: "1.22.19", + }, + pnpm: { + available: true, + version: "7.29.1", + }, + }); + + const { root } = useFixture({ + fixture: `./${fixtureManager}/${fixtureType}`, + }); + + // read + const details = await getWorkspaceDetails({ root }); + expect(details.packageManager).toBe(fixtureManager); + + // convert + const convertWrapper = () => + convert({ + root, + to: toManager, + options: { interactive, dry, skipInstall: !install }, + }); + + if (fixtureManager === toManager) { + await expect(convertWrapper()).rejects.toThrowError( + "You are already using this package manager" + ); + } else { + await expect(convertWrapper()).resolves.toBeUndefined(); + // read again + const convertedDetails = await getWorkspaceDetails({ + root, + }); + expect(mockedGetAvailablePackageManagers).toHaveBeenCalled(); + + if (dry) { + expect(convertedDetails.packageManager).toBe(fixtureManager); + } else { + if (install) { + expect(execa).toHaveBeenCalled(); + } + expect(convertedDetails.packageManager).toBe(toManager); + } + } + + mockedGetAvailablePackageManagers.mockRestore(); + } + ); + }); +}); diff --git a/packages/turbo-workspaces/__tests__/managers.test.ts b/packages/turbo-workspaces/__tests__/managers.test.ts new file mode 100644 index 0000000..73c5073 --- /dev/null +++ b/packages/turbo-workspaces/__tests__/managers.test.ts @@ -0,0 +1,285 @@ +import path from "path"; +import { setupTestFixtures } from "@turbo/test-utils"; +import { Logger } from "../src/logger"; +import MANAGERS from "../src/managers"; +import { PackageJson } from "../src/types"; +import fs from "fs-extra"; +import { + generateDetectMatrix, + generateCreateMatrix, + generateRemoveMatrix, + generateReadMatrix, + generateCleanMatrix, + generateConvertLockMatrix, +} from "./test-utils"; + +jest.mock("execa", () => jest.fn()); + +describe("managers", () => { + const { useFixture } = setupTestFixtures({ + directory: path.join(__dirname, "../"), + }); + + describe("detect", () => { + test.each(generateDetectMatrix())( + "$project $type project detected by $manager manager - (expect: $result)", + async ({ project, manager, type, result }) => { + const { root } = useFixture({ fixture: `./${project}/${type}` }); + + const detectResult = await MANAGERS[manager].detect({ + workspaceRoot: root, + }); + + expect(detectResult).toEqual(result); + } + ); + }); + + describe("create", () => { + test.each(generateCreateMatrix())( + "creates $manager project from $project $type project (interactive=$interactive, dry=$dry)", + async ({ project, manager, type, interactive, dry }) => { + expect.assertions(2); + + const { root } = useFixture({ fixture: `./${project}/${type}` }); + const testProject = await MANAGERS[project].read({ + workspaceRoot: root, + }); + + expect(testProject.packageManager).toEqual(project); + + await MANAGERS[manager].create({ + project: testProject, + to: { name: manager, version: "1.2.3" }, + logger: new Logger({ interactive, dry }), + options: { + interactive, + dry, + }, + }); + + if (dry) { + expect( + await MANAGERS[project].detect({ workspaceRoot: root }) + ).toEqual(true); + } else { + expect( + await MANAGERS[manager].detect({ workspaceRoot: root }) + ).toEqual(true); + } + } + ); + }); + + describe("remove", () => { + test.each(generateRemoveMatrix())( + "removes $fixtureManager from $fixtureManager $fixtureType project when moving to $toManager (withNodeModules=$withNodeModules, interactive=$interactive, dry=$dry)", + async ({ + fixtureManager, + fixtureType, + toManager, + withNodeModules, + interactive, + dry, + }) => { + const { root, readJson, readYaml } = useFixture({ + fixture: `./${fixtureManager}/${fixtureType}`, + }); + const project = await MANAGERS[fixtureManager].read({ + workspaceRoot: root, + }); + expect(project.packageManager).toEqual(fixtureManager); + + if (withNodeModules) { + fs.ensureDirSync(project.paths.nodeModules); + } + + await MANAGERS[fixtureManager].remove({ + project, + to: { name: toManager, version: "1.2.3" }, + logger: new Logger({ interactive, dry }), + options: { + interactive, + dry, + }, + }); + + if (withNodeModules) { + expect(fs.existsSync(project.paths.nodeModules)).toEqual(dry); + } + + const packageJson = readJson<PackageJson>(project.paths.packageJson); + if (dry) { + expect(packageJson?.packageManager).toBeDefined(); + expect(packageJson?.packageManager?.split("@")[0]).toEqual( + fixtureManager + ); + if (fixtureType === "basic") { + if (fixtureManager === "pnpm") { + expect(project.paths.workspaceConfig).toBeDefined(); + if (project.paths.workspaceConfig) { + const workspaceConfig = readYaml<{ packages: Array<string> }>( + project.paths.workspaceConfig + ); + expect(workspaceConfig?.packages).toBeDefined(); + expect(workspaceConfig?.packages).toEqual( + project.workspaceData.globs + ); + } + } else { + expect(packageJson?.workspaces).toBeDefined(); + expect(packageJson?.workspaces).toEqual( + project.workspaceData.globs + ); + } + } + } else { + expect(packageJson?.packageManager).toBeUndefined(); + if (fixtureType === "basic") { + expect(packageJson?.workspaces).toBeUndefined(); + + if (fixtureManager === "pnpm") { + expect(project.paths.workspaceConfig).toBeDefined(); + if (project.paths.workspaceConfig) { + const workspaceConfig = readYaml<{ packages: Array<string> }>( + project.paths.workspaceConfig + ); + expect(workspaceConfig).toBeUndefined(); + } + } + } + } + } + ); + }); + + describe("read", () => { + test.each(generateReadMatrix())( + "reads $toManager workspaces from $fixtureManager $fixtureType project - (shouldThrow: $shouldThrow)", + async ({ fixtureManager, fixtureType, toManager, shouldThrow }) => { + const { root, directoryName } = useFixture({ + fixture: `./${fixtureManager}/${fixtureType}`, + }); + + const read = async () => + MANAGERS[toManager].read({ workspaceRoot: path.join(root) }); + if (shouldThrow) { + if (toManager === "pnpm") { + expect(read).rejects.toThrow(`Not a pnpm project`); + } else if (toManager === "yarn") { + expect(read).rejects.toThrow(`Not a yarn project`); + } else if (toManager === "npm") { + expect(read).rejects.toThrow(`Not an npm project`); + } + return; + } + const project = await MANAGERS[toManager].read({ + workspaceRoot: path.join(root), + }); + + expect(project.name).toEqual( + fixtureType === "monorepo" ? `${toManager}-workspaces` : toManager + ); + expect(project.packageManager).toEqual(toManager); + + // paths + expect(project.paths.root).toMatch( + new RegExp(`^.*\/${directoryName}$`) + ); + expect(project.paths.packageJson).toMatch( + new RegExp(`^.*\/${directoryName}\/package.json$`) + ); + + if (fixtureManager === "pnpm") { + new RegExp(`^.*\/${directoryName}\/pnpm-lock.yaml$`); + } else if (fixtureManager === "yarn") { + new RegExp(`^.*\/${directoryName}\/yarn.lock$`); + } else if (fixtureManager === "npm") { + new RegExp(`^.*\/${directoryName}\/package-lock.json$`); + } else { + throw new Error("Invalid fixtureManager"); + } + + if (fixtureType === "non-monorepo") { + expect(project.workspaceData.workspaces).toEqual([]); + expect(project.workspaceData.globs).toEqual([]); + } else { + expect(project.workspaceData.globs).toEqual(["apps/*", "packages/*"]); + project.workspaceData.workspaces.forEach((workspace) => { + const type = ["web", "docs"].includes(workspace.name) + ? "apps" + : "packages"; + expect(workspace.paths.packageJson).toMatch( + new RegExp( + `^.*${directoryName}\/${type}\/${workspace.name}\/package.json$` + ) + ); + expect(workspace.paths.root).toMatch( + new RegExp(`^.*${directoryName}\/${type}\/${workspace.name}$`) + ); + }); + } + } + ); + }); + + describe("clean", () => { + test.each(generateCleanMatrix())( + "cleans $fixtureManager $fixtureType project (interactive=$interactive, dry=$dry)", + async ({ fixtureManager, fixtureType, interactive, dry }) => { + const { root } = useFixture({ + fixture: `./${fixtureManager}/${fixtureType}`, + }); + + const project = await MANAGERS[fixtureManager].read({ + workspaceRoot: root, + }); + + expect(project.packageManager).toEqual(fixtureManager); + + await MANAGERS[fixtureManager].clean({ + project, + logger: new Logger({ interactive, dry }), + options: { + interactive, + dry, + }, + }); + + expect(fs.existsSync(project.paths.lockfile)).toEqual(dry); + } + ); + }); + + describe("convertLock", () => { + test.each(generateConvertLockMatrix())( + "converts lockfile for $fixtureManager $fixtureType project to $toManager format (interactive=$interactive, dry=$dry)", + async ({ fixtureManager, fixtureType, toManager, interactive, dry }) => { + const { root, exists } = useFixture({ + fixture: `./${fixtureManager}/${fixtureType}`, + }); + + const project = await MANAGERS[fixtureManager].read({ + workspaceRoot: root, + }); + + expect(project.packageManager).toEqual(fixtureManager); + + await MANAGERS[toManager].convertLock({ + project, + logger: new Logger(), + options: { + interactive, + dry, + }, + }); + + if (fixtureManager !== toManager) { + expect(exists(project.paths.lockfile)).toEqual(dry); + } else { + expect(exists(project.paths.lockfile)).toEqual(true); + } + } + ); + }); +}); diff --git a/packages/turbo-workspaces/__tests__/test-utils.ts b/packages/turbo-workspaces/__tests__/test-utils.ts new file mode 100644 index 0000000..4d6c7c9 --- /dev/null +++ b/packages/turbo-workspaces/__tests__/test-utils.ts @@ -0,0 +1,153 @@ +import { PackageManager } from "../src/types"; + +const PACKAGE_MANAGERS: Array<PackageManager> = ["pnpm", "npm", "yarn"]; +const REPO_TYPES = ["monorepo", "non-monorepo"]; +const BOOLEAN_OPTIONS = [true, false]; + +export function generateConvertMatrix() { + const matrix = []; + for (const fixtureManager of PACKAGE_MANAGERS) { + for (const fixtureType of REPO_TYPES) { + for (const toManager of PACKAGE_MANAGERS) { + for (const interactive of BOOLEAN_OPTIONS) { + for (const dry of BOOLEAN_OPTIONS) { + for (const install of BOOLEAN_OPTIONS) { + matrix.push({ + fixtureManager, + fixtureType, + toManager, + interactive, + dry, + install, + }); + } + } + } + } + } + } + return matrix; +} + +export function generateDetectMatrix() { + const matrix = []; + for (const project of PACKAGE_MANAGERS) { + for (const manager of PACKAGE_MANAGERS) { + for (const type of REPO_TYPES) { + matrix.push({ + project, + manager, + type, + result: project === manager, + }); + } + } + } + return matrix; +} + +export function generateCreateMatrix() { + const matrix = []; + for (const project of PACKAGE_MANAGERS) { + for (const manager of PACKAGE_MANAGERS) { + for (const type of REPO_TYPES) { + for (const interactive of BOOLEAN_OPTIONS) { + for (const dry of BOOLEAN_OPTIONS) { + matrix.push({ + project, + manager, + type, + interactive, + dry, + }); + } + } + } + } + } + return matrix; +} + +export function generateReadMatrix() { + const matrix = []; + for (const fixtureManager of PACKAGE_MANAGERS) { + for (const fixtureType of REPO_TYPES) { + for (const toManager of PACKAGE_MANAGERS) { + matrix.push({ + fixtureManager, + fixtureType, + toManager, + shouldThrow: fixtureManager !== toManager, + }); + } + } + } + + return matrix; +} + +export function generateRemoveMatrix() { + const matrix = []; + for (const fixtureManager of PACKAGE_MANAGERS) { + for (const fixtureType of REPO_TYPES) { + for (const toManager of PACKAGE_MANAGERS) { + for (const withNodeModules of BOOLEAN_OPTIONS) { + for (const interactive of BOOLEAN_OPTIONS) { + for (const dry of BOOLEAN_OPTIONS) { + matrix.push({ + fixtureManager, + fixtureType, + withNodeModules, + toManager, + interactive, + dry, + }); + } + } + } + } + } + } + return matrix; +} + +export function generateCleanMatrix() { + const matrix = []; + for (const fixtureManager of PACKAGE_MANAGERS) { + for (const fixtureType of REPO_TYPES) { + for (const interactive of BOOLEAN_OPTIONS) { + for (const dry of BOOLEAN_OPTIONS) { + matrix.push({ + fixtureManager, + fixtureType, + interactive, + dry, + }); + } + } + } + } + return matrix; +} + +export function generateConvertLockMatrix() { + const matrix = []; + for (const fixtureManager of PACKAGE_MANAGERS) { + for (const fixtureType of REPO_TYPES) { + for (const toManager of PACKAGE_MANAGERS) { + for (const interactive of BOOLEAN_OPTIONS) { + for (const dry of BOOLEAN_OPTIONS) { + matrix.push({ + fixtureManager, + fixtureType, + toManager, + interactive, + dry, + }); + } + } + } + } + } + return matrix; +} diff --git a/packages/turbo-workspaces/jest.config.js b/packages/turbo-workspaces/jest.config.js new file mode 100644 index 0000000..2658950 --- /dev/null +++ b/packages/turbo-workspaces/jest.config.js @@ -0,0 +1,19 @@ +/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ +module.exports = { + preset: "ts-jest/presets/js-with-ts", + testEnvironment: "node", + testPathIgnorePatterns: ["/__fixtures__/", "/__tests__/test-utils.ts"], + coveragePathIgnorePatterns: ["/__fixtures__/", "/__tests__/test-utils.ts"], + transformIgnorePatterns: ["/node_modules/(?!(ansi-regex)/)"], + modulePathIgnorePatterns: ["<rootDir>/node_modules", "<rootDir>/dist"], + collectCoverage: true, + verbose: true, + coverageThreshold: { + global: { + branches: 83, + functions: 87, + lines: 93, + statements: 93, + }, + }, +}; diff --git a/packages/turbo-workspaces/package.json b/packages/turbo-workspaces/package.json new file mode 100644 index 0000000..5dd2490 --- /dev/null +++ b/packages/turbo-workspaces/package.json @@ -0,0 +1,66 @@ +{ + "name": "@turbo/workspaces", + "version": "1.9.4-canary.2", + "description": "Tools for working with package managers", + "homepage": "https://turbo.build/repo", + "license": "MPL-2.0", + "repository": { + "type": "git", + "url": "https://github.com/vercel/turbo", + "directory": "packages/turbo-workspaces" + }, + "bugs": { + "url": "https://github.com/vercel/turbo/issues" + }, + "bin": "dist/cli.js", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "test": "jest", + "lint": "eslint src/**/*.ts", + "check-types": "tsc --noEmit" + }, + "dependencies": { + "chalk": "2.4.2", + "commander": "^10.0.0", + "execa": "5.1.1", + "fast-glob": "^3.2.12", + "fs-extra": "^10.1.0", + "gradient-string": "^2.0.0", + "inquirer": "^8.0.0", + "js-yaml": "^4.1.0", + "ora": "4.1.1", + "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/js-yaml": "^4.0.5", + "@types/node": "^16.11.12", + "@types/rimraf": "^3.0.2", + "@types/semver": "^7.3.9", + "eslint": "^7.23.0", + "jest": "^27.4.3", + "semver": "^7.3.5", + "strip-ansi": "^6.0.1", + "ts-jest": "^27.1.1", + "@turbo/tsconfig": "workspace:*", + "tsup": "^5.10.3", + "@turbo/test-utils": "workspace:*", + "@turbo/utils": "workspace:*", + "typescript": "^4.5.5" + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + } +} diff --git a/packages/turbo-workspaces/src/cli.ts b/packages/turbo-workspaces/src/cli.ts new file mode 100644 index 0000000..3ae7a45 --- /dev/null +++ b/packages/turbo-workspaces/src/cli.ts @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +import chalk from "chalk"; +import { Command } from "commander"; + +import { summary, convert } from "./commands"; +import cliPkg from "../package.json"; +import { ConvertError } from "./errors"; + +const workspacesCli = new Command(); + +workspacesCli + .name("@turbo/workspaces") + .description("Tools for working with package manager workspaces") + .version(cliPkg.version, "-v, --version", "output the current version"); + +// convert +workspacesCli + .command("convert") + .description("Convert project between workspace managers") + .argument("[path]", "Project root") + .argument("[package-manager]", "Package manager to convert to") + .option( + "--skip-install", + "Do not run a package manager install after conversion", + false + ) + .option("--dry", "Dry run (no changes are made to files)", false) + .option( + "--force", + "Bypass Git safety checks and forcibly run conversion", + false + ) + .action(convert); + +// summary +workspacesCli + .command("summary") + .description("Display a summary of the specified project") + .argument("[path]", "Project root") + .action(summary); + +workspacesCli.parseAsync().catch((error) => { + console.log(); + if (error instanceof ConvertError) { + console.log(chalk.red(error.message)); + } else { + console.log(chalk.red("Unexpected error. Please report it as a bug:")); + console.log(error.message); + } + console.log(); + process.exit(1); +}); diff --git a/packages/turbo-workspaces/src/commands/convert/index.ts b/packages/turbo-workspaces/src/commands/convert/index.ts new file mode 100644 index 0000000..6cc82fc --- /dev/null +++ b/packages/turbo-workspaces/src/commands/convert/index.ts @@ -0,0 +1,109 @@ +import { ConvertCommandArgument, ConvertCommandOptions } from "./types"; +import inquirer from "inquirer"; +import { Logger } from "../../logger"; +import chalk from "chalk"; +import { getAvailablePackageManagers } from "@turbo/utils"; +import { directoryInfo } from "../../utils"; +import getWorkspaceDetails from "../../getWorkspaceDetails"; +import { PackageManager } from "../../types"; +import { convertProject } from "../../convert"; + +function isPackageManagerDisabled({ + packageManager, + currentWorkspaceManger, + availablePackageManagers, +}: { + packageManager: PackageManager; + currentWorkspaceManger: PackageManager; + availablePackageManagers: Record<PackageManager, { available: boolean }>; +}) { + if (currentWorkspaceManger === packageManager) { + return "already in use"; + } + + if (!availablePackageManagers[packageManager].available) { + return "not installed"; + } + + return false; +} + +export default async function convertCommand( + directory: ConvertCommandArgument, + packageManager: ConvertCommandArgument, + options: ConvertCommandOptions +) { + const logger = new Logger(options); + + logger.hero(); + logger.header("Welcome, let's convert your project."); + logger.blankLine(); + + const directoryAnswer = await inquirer.prompt<{ + directoryInput: string; + }>({ + type: "input", + name: "directoryInput", + message: "Where is the root of your repo?", + when: !directory, + default: ".", + validate: (directory: string) => { + const { exists, absolute } = directoryInfo({ directory }); + if (exists) { + return true; + } else { + return `Directory ${chalk.dim(`(${absolute})`)} does not exist`; + } + }, + filter: (directory: string) => directory.trim(), + }); + + const { directoryInput: selectedDirectory = directory } = directoryAnswer; + const { exists, absolute: root } = directoryInfo({ + directory: selectedDirectory, + }); + if (!exists) { + console.error(`Directory ${chalk.dim(`(${root})`)} does not exist`); + return process.exit(1); + } + + const [project, availablePackageManagers] = await Promise.all([ + getWorkspaceDetails({ root }), + getAvailablePackageManagers(), + ]); + + const packageManagerAnswer = await inquirer.prompt<{ + packageManagerInput?: PackageManager; + }>({ + name: "packageManagerInput", + type: "list", + message: `Convert from ${project.packageManager} workspaces to:`, + when: + !packageManager || + !Object.keys(availablePackageManagers).includes(packageManager), + choices: ["npm", "pnpm", "yarn"].map((p) => ({ + name: `${p} workspaces`, + value: p, + disabled: isPackageManagerDisabled({ + packageManager: p as PackageManager, + currentWorkspaceManger: project.packageManager, + availablePackageManagers, + }), + })), + }); + const { + packageManagerInput: + selectedPackageManager = packageManager as PackageManager, + } = packageManagerAnswer; + + await convertProject({ + project, + to: { + name: selectedPackageManager, + version: availablePackageManagers[selectedPackageManager] + .version as string, + }, + logger, + options, + }); +} diff --git a/packages/turbo-workspaces/src/commands/convert/types.ts b/packages/turbo-workspaces/src/commands/convert/types.ts new file mode 100644 index 0000000..a7b9deb --- /dev/null +++ b/packages/turbo-workspaces/src/commands/convert/types.ts @@ -0,0 +1,6 @@ +export type ConvertCommandArgument = string; +export type ConvertCommandOptions = { + dry: boolean; + force: boolean; + skipInstall: boolean; +}; diff --git a/packages/turbo-workspaces/src/commands/index.ts b/packages/turbo-workspaces/src/commands/index.ts new file mode 100644 index 0000000..423e959 --- /dev/null +++ b/packages/turbo-workspaces/src/commands/index.ts @@ -0,0 +1,8 @@ +export { default as summary } from "./summary"; +export { default as convert } from "./convert"; + +export type { SummaryCommandArgument } from "./summary/types"; +export type { + ConvertCommandArgument, + ConvertCommandOptions, +} from "./convert/types"; diff --git a/packages/turbo-workspaces/src/commands/summary/index.ts b/packages/turbo-workspaces/src/commands/summary/index.ts new file mode 100644 index 0000000..9696a14 --- /dev/null +++ b/packages/turbo-workspaces/src/commands/summary/index.ts @@ -0,0 +1,98 @@ +import inquirer from "inquirer"; +import path from "path"; +import { Logger } from "../../logger"; +import chalk from "chalk"; +import { SummaryCommandArgument } from "./types"; +import { directoryInfo } from "../../utils"; +import getWorkspaceDetails from "../../getWorkspaceDetails"; +import { Workspace } from "../../types"; + +export default async function summary(directory: SummaryCommandArgument) { + const logger = new Logger(); + logger.hero(); + + const answer = await inquirer.prompt<{ + directoryInput?: string; + }>({ + type: "input", + name: "directoryInput", + message: "Where is the root of the repo?", + when: !directory, + default: ".", + validate: (directory: string) => { + const { exists, absolute } = directoryInfo({ directory }); + if (exists) { + return true; + } else { + return `Directory ${chalk.dim(`(${absolute})`)} does not exist`; + } + }, + filter: (directory: string) => directory.trim(), + }); + + const { directoryInput: selectedDirectory = directory as string } = answer; + const { exists, absolute: root } = directoryInfo({ + directory: selectedDirectory, + }); + if (!exists) { + console.error(`Directory ${chalk.dim(`(${root})`)} does not exist`); + return process.exit(1); + } + + const project = await getWorkspaceDetails({ root }); + + const numWorkspaces = project.workspaceData.workspaces.length; + const hasWorkspaces = numWorkspaces > 0; + // group workspaces + const workspacesByDirectory: Record<string, Array<Workspace>> = {}; + project.workspaceData.workspaces.forEach((workspace) => { + const workspacePath = path.relative(root, workspace.paths.root); + const rootDirectory = workspacePath.split(path.sep)[0]; + if (!workspacesByDirectory[rootDirectory]) { + workspacesByDirectory[rootDirectory] = []; + } + workspacesByDirectory[rootDirectory].push(workspace); + }); + + const renderWorkspace = (w: Workspace) => { + return `${w.name} (${chalk.italic( + `./${path.relative(root, w.paths.root)}` + )})`; + }; + + const renderDirectory = ({ + number, + directory, + workspaces, + }: { + number: number; + directory: string; + workspaces: Array<Workspace>; + }) => { + logger.indented(2, `${number}. ${chalk.bold(directory)}`); + workspaces.forEach((workspace, idx) => { + logger.indented(3, `${idx + 1}. ${renderWorkspace(workspace)}`); + }); + }; + + // repo header + logger.header(`Repository Summary`); + logger.indented(1, `${chalk.underline(project.name)}:`); + // workspace manager header + logger.indented( + 1, + `Package Manager: ${chalk.bold(chalk.italic(project.packageManager))}` + ); + if (hasWorkspaces) { + // workspaces header + logger.indented(1, `Workspaces (${chalk.bold(numWorkspaces.toString())}):`); + Object.keys(workspacesByDirectory).forEach((directory, idx) => { + renderDirectory({ + number: idx + 1, + directory, + workspaces: workspacesByDirectory[directory], + }); + }); + logger.blankLine(); + } +} diff --git a/packages/turbo-workspaces/src/commands/summary/types.ts b/packages/turbo-workspaces/src/commands/summary/types.ts new file mode 100644 index 0000000..0cc5830 --- /dev/null +++ b/packages/turbo-workspaces/src/commands/summary/types.ts @@ -0,0 +1 @@ +export type SummaryCommandArgument = string; diff --git a/packages/turbo-workspaces/src/convert.ts b/packages/turbo-workspaces/src/convert.ts new file mode 100644 index 0000000..9f481c1 --- /dev/null +++ b/packages/turbo-workspaces/src/convert.ts @@ -0,0 +1,61 @@ +import chalk from "chalk"; +import managers from "./managers"; +import { Project, Options, PackageManagerDetails } from "./types"; +import install from "./install"; +import { Logger } from "./logger"; +import { ConvertError } from "./errors"; + +/* + * Convert a project using workspaces from one package manager to another. + + Steps are run in the following order: + 1. managerFrom.remove + 2. managerTo.create + 3. managerTo.convertLock + 3. install + 4. managerFrom.clean + +*/ +export async function convertProject({ + project, + to, + logger, + options, +}: { + project: Project; + to: PackageManagerDetails; + logger: Logger; + options?: Options; +}) { + logger.header( + `Converting project from ${project.packageManager} to ${to.name}.` + ); + + if (project.packageManager == to.name) { + throw new ConvertError("You are already using this package manager", { + type: "package_manager-already_in_use", + }); + } + + // remove old workspace data + await managers[project.packageManager].remove({ + project, + to, + logger, + options, + }); + + // create new workspace data + await managers[to.name].create({ project, to, logger, options }); + + logger.mainStep("Installing dependencies"); + if (!options?.skipInstall) { + await managers[to.name].convertLock({ project, logger, options }); + await install({ project, to, logger, options }); + } else { + logger.subStep(chalk.yellow("Skipping install")); + } + + logger.mainStep(`Cleaning up ${project.packageManager} workspaces`); + await managers[project.packageManager].clean({ project, logger }); +} diff --git a/packages/turbo-workspaces/src/errors.ts b/packages/turbo-workspaces/src/errors.ts new file mode 100644 index 0000000..aa2fabe --- /dev/null +++ b/packages/turbo-workspaces/src/errors.ts @@ -0,0 +1,31 @@ +export type ConvertErrorType = + // package manager general + | "package_manager-unexpected" + | "package_manager-already_in_use" + | "package_manager-unable_to_detect" + | "package_manager-unsupported_version" + // package manager specific + | "pnpm-workspace_parse_error" + // package.json + | "package_json-parse_error" + | "package_json-missing" + // other + | "invalid_directory" + | "error_removing_node_modules" + // default + | "unknown"; + +export type ConvertErrorOptions = { + type?: ConvertErrorType; +}; + +export class ConvertError extends Error { + public type: ConvertErrorType; + + constructor(message: string, opts?: ConvertErrorOptions) { + super(message); + this.name = "ConvertError"; + this.type = opts?.type ?? "unknown"; + Error.captureStackTrace(this, ConvertError); + } +} diff --git a/packages/turbo-workspaces/src/getWorkspaceDetails.ts b/packages/turbo-workspaces/src/getWorkspaceDetails.ts new file mode 100644 index 0000000..ad86a97 --- /dev/null +++ b/packages/turbo-workspaces/src/getWorkspaceDetails.ts @@ -0,0 +1,35 @@ +import { ConvertError } from "./errors"; +import managers from "./managers"; +import { Project } from "./types"; +import { directoryInfo } from "./utils"; + +export default async function getWorkspaceDetails({ + root, +}: { + root: string; +}): Promise<Project> { + const { exists, absolute: workspaceRoot } = directoryInfo({ + directory: root, + }); + if (!exists) { + throw new ConvertError( + `Could not find directory at ${workspaceRoot}. Ensure the directory exists.`, + { + type: "invalid_directory", + } + ); + } + + for (const { detect, read } of Object.values(managers)) { + if (await detect({ workspaceRoot })) { + return read({ workspaceRoot }); + } + } + + throw new ConvertError( + "Could not determine package manager. Add `packageManager` to `package.json` or ensure a lockfile is present.", + { + type: "package_manager-unable_to_detect", + } + ); +} diff --git a/packages/turbo-workspaces/src/index.ts b/packages/turbo-workspaces/src/index.ts new file mode 100644 index 0000000..c7fc6b8 --- /dev/null +++ b/packages/turbo-workspaces/src/index.ts @@ -0,0 +1,58 @@ +import { getAvailablePackageManagers } from "@turbo/utils"; +import getWorkspaceDetails from "./getWorkspaceDetails"; +import { convertProject } from "./convert"; +import { Logger } from "./logger"; +import install, { getPackageManagerMeta } from "./install"; +import { ConvertError } from "./errors"; +import MANAGERS from "./managers"; + +import type { + PackageManager, + Options, + InstallArgs, + Workspace, + Project, +} from "./types"; +import type { ConvertErrorType } from "./errors"; + +async function convert({ + root, + to, + options, +}: { + root: string; + to: PackageManager; + options?: Options; +}) { + const logger = new Logger({ ...options, interactive: false }); + const [project, availablePackageManagers] = await Promise.all([ + getWorkspaceDetails({ root }), + getAvailablePackageManagers(), + ]); + await convertProject({ + project, + to: { + name: to, + version: availablePackageManagers[to].version as PackageManager, + }, + logger, + options, + }); +} + +export type { + PackageManager, + Options, + InstallArgs, + Workspace, + Project, + ConvertErrorType, +}; +export { + convert, + getWorkspaceDetails, + install, + MANAGERS, + getPackageManagerMeta, + ConvertError, +}; diff --git a/packages/turbo-workspaces/src/install.ts b/packages/turbo-workspaces/src/install.ts new file mode 100644 index 0000000..ad5f741 --- /dev/null +++ b/packages/turbo-workspaces/src/install.ts @@ -0,0 +1,125 @@ +import execa from "execa"; +import ora from "ora"; +import { satisfies } from "semver"; +import { ConvertError } from "./errors"; +import { Logger } from "./logger"; +import { + PackageManager, + PackageManagerDetails, + PackageManagerInstallDetails, + InstallArgs, +} from "./types"; + +export const PACKAGE_MANAGERS: Record< + PackageManager, + Array<PackageManagerInstallDetails> +> = { + npm: [ + { + name: "npm", + template: "npm", + command: "npm", + installArgs: ["install"], + version: "latest", + executable: "npx", + semver: "*", + default: true, + }, + ], + pnpm: [ + { + name: "pnpm6", + template: "pnpm", + command: "pnpm", + installArgs: ["install"], + version: "latest-6", + executable: "pnpx", + semver: "6.x", + }, + { + name: "pnpm", + template: "pnpm", + command: "pnpm", + installArgs: ["install"], + version: "latest", + executable: "pnpm dlx", + semver: ">=7", + default: true, + }, + ], + yarn: [ + { + name: "yarn", + template: "yarn", + command: "yarn", + installArgs: ["install"], + version: "1.x", + executable: "npx", + semver: "<2", + default: true, + }, + { + name: "berry", + template: "berry", + command: "yarn", + installArgs: ["install", "--no-immutable"], + version: "stable", + executable: "yarn dlx", + semver: ">=2", + }, + ], +}; + +export function getPackageManagerMeta(packageManager: PackageManagerDetails) { + const { version, name } = packageManager; + if (version) { + return PACKAGE_MANAGERS[name].find((manager) => + satisfies(version, manager.semver) + ); + } else { + return PACKAGE_MANAGERS[name].find((manager) => { + return manager.default; + }); + } +} + +export default async function install(args: InstallArgs) { + const { to, logger, options } = args; + + const installLogger = logger ?? new Logger(options); + const packageManager = getPackageManagerMeta(to); + + if (!packageManager) { + throw new ConvertError("Unsupported package manager version.", { + type: "package_manager-unsupported_version", + }); + } + + installLogger.subStep( + `running "${packageManager.command} ${packageManager.installArgs}"` + ); + if (!options?.dry) { + let spinner; + if (installLogger?.interactive) { + spinner = ora({ + text: "installing dependencies...", + spinner: { + frames: installLogger.installerFrames(), + }, + }).start(); + } + + try { + await execa(packageManager.command, packageManager.installArgs, { + cwd: args.project.paths.root, + }); + if (spinner) { + spinner.stop(); + } + installLogger.subStep(`dependencies installed`); + } catch (err) { + installLogger.subStepFailure(`failed to install dependencies`); + throw err; + } + } +} diff --git a/packages/turbo-workspaces/src/logger.ts b/packages/turbo-workspaces/src/logger.ts new file mode 100644 index 0000000..222c89a --- /dev/null +++ b/packages/turbo-workspaces/src/logger.ts @@ -0,0 +1,109 @@ +import chalk from "chalk"; +import gradient from "gradient-string"; + +const INDENTATION = 2; + +export class Logger { + interactive: boolean; + dry: boolean; + step: number; + + constructor({ + interactive, + dry, + }: { interactive?: boolean; dry?: boolean } = {}) { + this.interactive = interactive ?? true; + this.dry = dry ?? false; + this.step = 1; + } + + logger(...args: any[]) { + if (this.interactive) { + console.log(...args); + } + } + + indented(level: number, ...args: any[]) { + this.logger(" ".repeat(INDENTATION * level), ...args); + } + + header(title: string) { + this.blankLine(); + this.logger(chalk.bold(title)); + } + + installerFrames() { + const prefix = `${" ".repeat(INDENTATION)} - ${ + this.dry ? chalk.yellow("SKIPPED | ") : chalk.green("OK | ") + }`; + return [`${prefix} `, `${prefix}> `, `${prefix}>> `, `${prefix}>>>`]; + } + + gradient(text: string | number) { + const turboGradient = gradient("#0099F7", "#F11712"); + return turboGradient(text.toString()); + } + + hero() { + this.logger(chalk.bold(this.gradient(`\n>>> TURBOREPO\n`))); + } + + info(...args: any[]) { + this.logger(...args); + } + + mainStep(title: string) { + this.blankLine(); + this.logger(`${this.step}. ${chalk.underline(title)}`); + this.step += 1; + } + + subStep(...args: any[]) { + this.logger( + " ".repeat(INDENTATION), + `-`, + this.dry ? chalk.yellow("SKIPPED |") : chalk.green("OK |"), + ...args + ); + } + + subStepFailure(...args: any[]) { + this.logger(" ".repeat(INDENTATION), `-`, chalk.red("ERROR |"), ...args); + } + + rootHeader() { + this.blankLine(); + this.indented(2, "Root:"); + } + + rootStep(...args: any[]) { + this.logger( + " ".repeat(INDENTATION * 3), + `-`, + this.dry ? chalk.yellow("SKIPPED |") : chalk.green("OK |"), + ...args + ); + } + + workspaceHeader() { + this.blankLine(); + this.indented(2, "Workspaces:"); + } + + workspaceStep(...args: any[]) { + this.logger( + " ".repeat(INDENTATION * 3), + `-`, + this.dry ? chalk.yellow("SKIPPED |") : chalk.green("OK |"), + ...args + ); + } + + blankLine() { + this.logger(); + } + + error(...args: any[]) { + console.error(...args); + } +} diff --git a/packages/turbo-workspaces/src/managers/index.ts b/packages/turbo-workspaces/src/managers/index.ts new file mode 100644 index 0000000..e026aed --- /dev/null +++ b/packages/turbo-workspaces/src/managers/index.ts @@ -0,0 +1,11 @@ +import pnpm from "./pnpm"; +import npm from "./npm"; +import yarn from "./yarn"; +import { ManagerHandler, PackageManager } from "../types"; + +const MANAGERS: Record<PackageManager, ManagerHandler> = { + pnpm, + yarn, + npm, +}; +export default MANAGERS; diff --git a/packages/turbo-workspaces/src/managers/npm.ts b/packages/turbo-workspaces/src/managers/npm.ts new file mode 100644 index 0000000..26fd76a --- /dev/null +++ b/packages/turbo-workspaces/src/managers/npm.ts @@ -0,0 +1,223 @@ +import fs from "fs-extra"; +import path from "path"; +import { ConvertError } from "../errors"; +import updateDependencies from "../updateDependencies"; +import { + DetectArgs, + ReadArgs, + CreateArgs, + RemoveArgs, + CleanArgs, + Project, + ConvertArgs, + ManagerHandler, +} from "../types"; +import { + getMainStep, + getWorkspaceInfo, + getPackageJson, + expandWorkspaces, + getWorkspacePackageManager, + expandPaths, +} from "../utils"; + +/** + * Check if a given project is using npm workspaces + * Verify by checking for the existence of: + * 1. package-lock.json + * 2. packageManager field in package.json + */ +async function detect(args: DetectArgs): Promise<boolean> { + const lockFile = path.join(args.workspaceRoot, "package-lock.json"); + const packageManager = getWorkspacePackageManager({ + workspaceRoot: args.workspaceRoot, + }); + return fs.existsSync(lockFile) || packageManager === "npm"; +} + +/** + Read workspace data from npm workspaces into generic format +*/ +async function read(args: ReadArgs): Promise<Project> { + const isNpm = await detect(args); + if (!isNpm) { + throw new ConvertError("Not an npm project", { + type: "package_manager-unexpected", + }); + } + + const packageJson = getPackageJson(args); + const { name, description } = getWorkspaceInfo(args); + return { + name, + description, + packageManager: "npm", + paths: expandPaths({ + root: args.workspaceRoot, + lockFile: "package-lock.json", + }), + workspaceData: { + globs: packageJson.workspaces || [], + workspaces: expandWorkspaces({ + workspaceGlobs: packageJson.workspaces, + ...args, + }), + }, + }; +} + +/** + * Create npm workspaces from generic format + * + * Creating npm workspaces involves: + * 1. Adding the workspaces field in package.json + * 2. Setting the packageManager field in package.json + * 3. Updating all workspace package.json dependencies to ensure correct format + */ +async function create(args: CreateArgs): Promise<void> { + const { project, options, to, logger } = args; + const hasWorkspaces = project.workspaceData.globs.length > 0; + + logger.mainStep( + getMainStep({ packageManager: "npm", action: "create", project }) + ); + const packageJson = getPackageJson({ workspaceRoot: project.paths.root }); + logger.rootHeader(); + + // package manager + logger.rootStep( + `adding "packageManager" field to ${path.relative( + project.paths.root, + project.paths.packageJson + )}` + ); + packageJson.packageManager = `${to.name}@${to.version}`; + + if (hasWorkspaces) { + // workspaces field + logger.rootStep( + `adding "workspaces" field to ${path.relative( + project.paths.root, + project.paths.packageJson + )}` + ); + packageJson.workspaces = project.workspaceData.globs; + + // write package.json here instead of deferring to avoid negating the changes made by updateDependencies + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + } + + // root dependencies + updateDependencies({ + workspace: { name: "root", paths: project.paths }, + project, + to, + logger, + options, + }); + + // workspace dependencies + logger.workspaceHeader(); + project.workspaceData.workspaces.forEach((workspace) => + updateDependencies({ workspace, project, to, logger, options }) + ); + } else { + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + } + } +} + +/** + * Remove npm workspace data + * Removing npm workspaces involves: + * 1. Removing the workspaces field from package.json + * 2. Removing the node_modules directory + */ +async function remove(args: RemoveArgs): Promise<void> { + const { project, logger, options } = args; + const hasWorkspaces = project.workspaceData.globs.length > 0; + + logger.mainStep( + getMainStep({ packageManager: "npm", action: "remove", project }) + ); + const packageJson = getPackageJson({ workspaceRoot: project.paths.root }); + + if (hasWorkspaces) { + logger.subStep( + `removing "workspaces" field in ${project.name} root "package.json"` + ); + delete packageJson.workspaces; + } + + logger.subStep( + `removing "packageManager" field in ${project.name} root "package.json"` + ); + delete packageJson.packageManager; + + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + + // collect all workspace node_modules directories + const allModulesDirs = [ + project.paths.nodeModules, + ...project.workspaceData.workspaces.map((w) => w.paths.nodeModules), + ]; + try { + logger.subStep(`removing "node_modules"`); + await Promise.all( + allModulesDirs.map((dir) => + fs.rm(dir, { recursive: true, force: true }) + ) + ); + } catch (err) { + throw new ConvertError("Failed to remove node_modules", { + type: "error_removing_node_modules", + }); + } + } +} + +/** + * Clean is called post install, and is used to clean up any files + * from this package manager that were needed for install, + * but not required after migration + */ +async function clean(args: CleanArgs): Promise<void> { + const { project, logger, options } = args; + + logger.subStep( + `removing ${path.relative(project.paths.root, project.paths.lockfile)}` + ); + if (!options?.dry) { + fs.rmSync(project.paths.lockfile, { force: true }); + } +} + +/** + * Attempts to convert an existing, non npm lockfile to an npm lockfile + * + * If this is not possible, the non npm lockfile is removed + */ +async function convertLock(args: ConvertArgs): Promise<void> { + const { project, options } = args; + + if (project.packageManager !== "npm") { + // remove the lockfile + if (!options?.dry) { + fs.rmSync(project.paths.lockfile, { force: true }); + } + } +} + +const npm: ManagerHandler = { + detect, + read, + create, + remove, + clean, + convertLock, +}; + +export default npm; diff --git a/packages/turbo-workspaces/src/managers/pnpm.ts b/packages/turbo-workspaces/src/managers/pnpm.ts new file mode 100644 index 0000000..747e578 --- /dev/null +++ b/packages/turbo-workspaces/src/managers/pnpm.ts @@ -0,0 +1,238 @@ +import fs from "fs-extra"; +import path from "path"; +import execa from "execa"; +import { ConvertError } from "../errors"; +import updateDependencies from "../updateDependencies"; +import { + DetectArgs, + ReadArgs, + CreateArgs, + RemoveArgs, + ConvertArgs, + CleanArgs, + Project, + ManagerHandler, +} from "../types"; +import { + getMainStep, + expandPaths, + getWorkspaceInfo, + expandWorkspaces, + getPnpmWorkspaces, + getPackageJson, + getWorkspacePackageManager, +} from "../utils"; + +/** + * Check if a given project is using pnpm workspaces + * Verify by checking for the existence of: + * 1. pnpm-workspace.yaml + * 2. pnpm-workspace.yaml + */ +async function detect(args: DetectArgs): Promise<boolean> { + const lockFile = path.join(args.workspaceRoot, "pnpm-lock.yaml"); + const workspaceFile = path.join(args.workspaceRoot, "pnpm-workspace.yaml"); + const packageManager = getWorkspacePackageManager({ + workspaceRoot: args.workspaceRoot, + }); + return ( + fs.existsSync(lockFile) || + fs.existsSync(workspaceFile) || + packageManager === "pnpm" + ); +} + +/** + Read workspace data from pnpm workspaces into generic format +*/ +async function read(args: ReadArgs): Promise<Project> { + const isPnpm = await detect(args); + if (!isPnpm) { + throw new ConvertError("Not a pnpm project", { + type: "package_manager-unexpected", + }); + } + + const { name, description } = getWorkspaceInfo(args); + return { + name, + description, + packageManager: "pnpm", + paths: expandPaths({ + root: args.workspaceRoot, + lockFile: "pnpm-lock.yaml", + workspaceConfig: "pnpm-workspace.yaml", + }), + workspaceData: { + globs: getPnpmWorkspaces(args), + workspaces: expandWorkspaces({ + workspaceGlobs: getPnpmWorkspaces(args), + ...args, + }), + }, + }; +} + +/** + * Create pnpm workspaces from generic format + * + * Creating pnpm workspaces involves: + * 1. Create pnpm-workspace.yaml + * 2. Setting the packageManager field in package.json + * 3. Updating all workspace package.json dependencies to ensure correct format + */ +async function create(args: CreateArgs): Promise<void> { + const { project, to, logger, options } = args; + const hasWorkspaces = project.workspaceData.globs.length > 0; + + logger.mainStep( + getMainStep({ action: "create", packageManager: "pnpm", project }) + ); + + const packageJson = getPackageJson({ workspaceRoot: project.paths.root }); + logger.rootHeader(); + packageJson.packageManager = `${to.name}@${to.version}`; + logger.rootStep( + `adding "packageManager" field to ${project.name} root "package.json"` + ); + + // write the changes + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + + if (hasWorkspaces) { + logger.rootStep(`adding "pnpm-workspace.yaml"`); + fs.writeFileSync( + path.join(project.paths.root, "pnpm-workspace.yaml"), + `packages:\n${project.workspaceData.globs + .map((w) => ` - "${w}"`) + .join("\n")}` + ); + } + } + + if (hasWorkspaces) { + // root dependencies + updateDependencies({ + workspace: { name: "root", paths: project.paths }, + project, + to, + logger, + options, + }); + + // workspace dependencies + logger.workspaceHeader(); + project.workspaceData.workspaces.forEach((workspace) => + updateDependencies({ workspace, project, to, logger, options }) + ); + } +} + +/** + * Remove pnpm workspace data + * + * Cleaning up from pnpm involves: + * 1. Removing the pnpm-workspace.yaml file + * 2. Removing the pnpm-lock.yaml file + * 3. Removing the node_modules directory + */ +async function remove(args: RemoveArgs): Promise<void> { + const { project, logger, options } = args; + const hasWorkspaces = project.workspaceData.globs.length > 0; + + logger.mainStep( + getMainStep({ action: "remove", packageManager: "pnpm", project }) + ); + const packageJson = getPackageJson({ workspaceRoot: project.paths.root }); + + if (project.paths.workspaceConfig && hasWorkspaces) { + logger.subStep(`removing "pnpm-workspace.yaml"`); + if (!options?.dry) { + fs.rmSync(project.paths.workspaceConfig, { force: true }); + } + } + + logger.subStep( + `removing "packageManager" field in ${project.name} root "package.json"` + ); + delete packageJson.packageManager; + + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + + // collect all workspace node_modules directories + const allModulesDirs = [ + project.paths.nodeModules, + ...project.workspaceData.workspaces.map((w) => w.paths.nodeModules), + ]; + + try { + logger.subStep(`removing "node_modules"`); + await Promise.all( + allModulesDirs.map((dir) => + fs.rm(dir, { recursive: true, force: true }) + ) + ); + } catch (err) { + throw new ConvertError("Failed to remove node_modules", { + type: "error_removing_node_modules", + }); + } + } +} + +/** + * Clean is called post install, and is used to clean up any files + * from this package manager that were needed for install, + * but not required after migration + */ +async function clean(args: CleanArgs): Promise<void> { + const { project, logger, options } = args; + + logger.subStep( + `removing ${path.relative(project.paths.root, project.paths.lockfile)}` + ); + if (!options?.dry) { + fs.rmSync(project.paths.lockfile, { force: true }); + } +} + +/** + * Attempts to convert an existing, non pnpm lockfile to a pnpm lockfile + * + * If this is not possible, the non pnpm lockfile is removed + */ +async function convertLock(args: ConvertArgs): Promise<void> { + const { project, logger, options } = args; + + if (project.packageManager !== "pnpm") { + logger.subStep( + `converting ${path.relative( + project.paths.root, + project.paths.lockfile + )} to pnpm-lock.yaml` + ); + if (!options?.dry && fs.existsSync(project.paths.lockfile)) { + try { + await execa("pnpm", ["import"], { + stdio: "ignore", + cwd: project.paths.root, + }); + } finally { + fs.rmSync(project.paths.lockfile, { force: true }); + } + } + } +} + +const pnpm: ManagerHandler = { + detect, + read, + create, + remove, + clean, + convertLock, +}; + +export default pnpm; diff --git a/packages/turbo-workspaces/src/managers/yarn.ts b/packages/turbo-workspaces/src/managers/yarn.ts new file mode 100644 index 0000000..9bef53f --- /dev/null +++ b/packages/turbo-workspaces/src/managers/yarn.ts @@ -0,0 +1,222 @@ +import fs from "fs-extra"; +import path from "path"; +import { ConvertError } from "../errors"; +import updateDependencies from "../updateDependencies"; +import { + DetectArgs, + ReadArgs, + CreateArgs, + RemoveArgs, + ConvertArgs, + CleanArgs, + Project, +} from "../types"; +import { + getMainStep, + getWorkspaceInfo, + getPackageJson, + expandPaths, + expandWorkspaces, + getWorkspacePackageManager, +} from "../utils"; + +/** + * Check if a given project is using yarn workspaces + * Verify by checking for the existence of: + * 1. yarn.lock + * 2. packageManager field in package.json + */ +async function detect(args: DetectArgs): Promise<boolean> { + const lockFile = path.join(args.workspaceRoot, "yarn.lock"); + const packageManager = getWorkspacePackageManager({ + workspaceRoot: args.workspaceRoot, + }); + return fs.existsSync(lockFile) || packageManager === "yarn"; +} + +/** + Read workspace data from yarn workspaces into generic format +*/ +async function read(args: ReadArgs): Promise<Project> { + const isYarn = await detect(args); + if (!isYarn) { + throw new ConvertError("Not a yarn project", { + type: "package_manager-unexpected", + }); + } + + const packageJson = getPackageJson(args); + const { name, description } = getWorkspaceInfo(args); + return { + name, + description, + packageManager: "yarn", + paths: expandPaths({ + root: args.workspaceRoot, + lockFile: "yarn.lock", + }), + workspaceData: { + globs: packageJson.workspaces || [], + workspaces: expandWorkspaces({ + workspaceGlobs: packageJson.workspaces, + ...args, + }), + }, + }; +} + +/** + * Create yarn workspaces from generic format + * + * Creating yarn workspaces involves: + * 1. Adding the workspaces field in package.json + * 2. Setting the packageManager field in package.json + * 3. Updating all workspace package.json dependencies to ensure correct format + */ +async function create(args: CreateArgs): Promise<void> { + const { project, to, logger, options } = args; + const hasWorkspaces = project.workspaceData.globs.length > 0; + + logger.mainStep( + getMainStep({ packageManager: "yarn", action: "create", project }) + ); + const packageJson = getPackageJson({ workspaceRoot: project.paths.root }); + logger.rootHeader(); + + // package manager + logger.rootStep( + `adding "packageManager" field to ${path.relative( + project.paths.root, + project.paths.packageJson + )}` + ); + packageJson.packageManager = `${to.name}@${to.version}`; + + if (hasWorkspaces) { + // workspaces field + logger.rootStep( + `adding "workspaces" field to ${path.relative( + project.paths.root, + project.paths.packageJson + )}` + ); + packageJson.workspaces = project.workspaceData.globs; + + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + } + + // root dependencies + updateDependencies({ + workspace: { name: "root", paths: project.paths }, + project, + to, + logger, + options, + }); + + // workspace dependencies + logger.workspaceHeader(); + project.workspaceData.workspaces.forEach((workspace) => + updateDependencies({ workspace, project, to, logger, options }) + ); + } else { + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + } + } +} + +/** + * Remove yarn workspace data + * + * Removing yarn workspaces involves: + * 1. Removing the workspaces field from package.json + * 2. Removing the node_modules directory + */ +async function remove(args: RemoveArgs): Promise<void> { + const { project, logger, options } = args; + const hasWorkspaces = project.workspaceData.globs.length > 0; + + logger.mainStep( + getMainStep({ packageManager: "yarn", action: "remove", project }) + ); + const packageJson = getPackageJson({ workspaceRoot: project.paths.root }); + + if (hasWorkspaces) { + logger.subStep( + `removing "workspaces" field in ${project.name} root "package.json"` + ); + delete packageJson.workspaces; + } + + logger.subStep( + `removing "packageManager" field in ${project.name} root "package.json"` + ); + delete packageJson.packageManager; + + if (!options?.dry) { + fs.writeJSONSync(project.paths.packageJson, packageJson, { spaces: 2 }); + + // collect all workspace node_modules directories + const allModulesDirs = [ + project.paths.nodeModules, + ...project.workspaceData.workspaces.map((w) => w.paths.nodeModules), + ]; + try { + logger.subStep(`removing "node_modules"`); + await Promise.all( + allModulesDirs.map((dir) => + fs.rm(dir, { recursive: true, force: true }) + ) + ); + } catch (err) { + throw new ConvertError("Failed to remove node_modules", { + type: "error_removing_node_modules", + }); + } + } +} + +/** + * Clean is called post install, and is used to clean up any files + * from this package manager that were needed for install, + * but not required after migration + */ +async function clean(args: CleanArgs): Promise<void> { + const { project, logger, options } = args; + + logger.subStep( + `removing ${path.relative(project.paths.root, project.paths.lockfile)}` + ); + if (!options?.dry) { + fs.rmSync(project.paths.lockfile, { force: true }); + } +} + +/** + * Attempts to convert an existing, non yarn lockfile to a yarn lockfile + * + * If this is not possible, the non yarn lockfile is removed + */ +async function convertLock(args: ConvertArgs): Promise<void> { + const { project, options } = args; + + if (project.packageManager !== "yarn") { + // remove the lockfile + if (!options?.dry) { + fs.rmSync(project.paths.lockfile, { force: true }); + } + } +} + +const yarn = { + detect, + read, + create, + remove, + clean, + convertLock, +}; + +export default yarn; diff --git a/packages/turbo-workspaces/src/types.ts b/packages/turbo-workspaces/src/types.ts new file mode 100644 index 0000000..9240f09 --- /dev/null +++ b/packages/turbo-workspaces/src/types.ts @@ -0,0 +1,127 @@ +import { Logger } from "./logger"; + +export type PackageManager = "npm" | "pnpm" | "yarn"; +export type PackageManagerDetails = { + name: PackageManager; + version?: string; +}; + +export type Project = { + name: string; + description?: string; + packageManager: PackageManager; + paths: { + root: string; + packageJson: string; + lockfile: string; + nodeModules: string; + // pnpm workspace config file + workspaceConfig?: string; + }; + workspaceData: { + globs: Array<string>; + workspaces: Array<Workspace>; + }; +}; + +export type Workspace = { + name: string; + description?: string; + paths: { + root: string; + packageJson: string; + nodeModules: string; + }; +}; + +export type WorkspaceInfo = Pick<Workspace, "name" | "description">; + +export type DependencyList = Record<string, string>; + +export type PackageJsonDependencies = { + dependencies?: DependencyList; + devDependencies?: DependencyList; + peerDependencies?: DependencyList; + optionalDependencies?: DependencyList; +}; + +export type PackageJson = PackageJsonDependencies & { + name?: string; + description?: string; + workspaces?: Array<string>; + packageManager?: string; +}; + +export type DetectArgs = { + workspaceRoot: string; +}; + +export type ReadArgs = { + workspaceRoot: string; +}; + +export type CreateArgs = { + project: Project; + to: PackageManagerDetails; + logger: Logger; + options?: Options; +}; + +export type RemoveArgs = { + project: Project; + to: PackageManagerDetails; + logger: Logger; + options?: Options; +}; + +export type CleanArgs = { + project: Project; + logger: Logger; + options?: Options; +}; + +export type ConvertArgs = { + project: Project; + logger: Logger; + options?: Options; +}; + +export type InstallArgs = { + project: Project; + to: PackageManagerDetails; + logger?: Logger; + options?: Options; +}; + +export type Options = { + dry?: boolean; + skipInstall?: boolean; + interactive?: boolean; +}; + +export type PackageManagerInstallDetails = { + name: string; + template: string; + command: PackageManager; + installArgs: string[]; + version: string; + executable: string; + semver: string; + default?: boolean; +}; + +export type ManagerDetect = (args: DetectArgs) => Promise<boolean>; +export type ManagerRead = (args: ReadArgs) => Promise<Project>; +export type ManagerCreate = (args: CreateArgs) => Promise<void>; +export type ManagerRemove = (args: RemoveArgs) => Promise<void>; +export type ManagerClean = (args: CleanArgs) => Promise<void>; +export type ManagerConvert = (args: ConvertArgs) => Promise<void>; + +export type ManagerHandler = { + detect: ManagerDetect; + read: ManagerRead; + create: ManagerCreate; + remove: ManagerRemove; + clean: ManagerClean; + convertLock: ManagerConvert; +}; diff --git a/packages/turbo-workspaces/src/updateDependencies.ts b/packages/turbo-workspaces/src/updateDependencies.ts new file mode 100644 index 0000000..5461ed0 --- /dev/null +++ b/packages/turbo-workspaces/src/updateDependencies.ts @@ -0,0 +1,135 @@ +import fs from "fs-extra"; +import chalk from "chalk"; +import path from "path"; +import { + Project, + Workspace, + DependencyList, + PackageManagerDetails, + Options, + PackageJsonDependencies, +} from "./types"; +import { Logger } from "./logger"; +import { getPackageJson } from "./utils"; + +function updateDependencyList({ + dependencyList, + project, + to, +}: { + dependencyList: DependencyList; + project: Project; + to: PackageManagerDetails; +}): { dependencyList: DependencyList; updated: Array<string> } { + const updated: Array<string> = []; + project.workspaceData.workspaces.forEach((workspace) => { + const { name } = workspace; + if (dependencyList[name]) { + const workspaceVersion = dependencyList[name]; + const version = workspaceVersion.startsWith("workspace:") + ? workspaceVersion.slice("workspace:".length) + : workspaceVersion; + dependencyList[name] = + to.name === "pnpm" ? `workspace:${version}` : version; + updated.push(name); + } + }); + + return { dependencyList, updated }; +} + +export default function updateDependencies({ + project, + workspace, + to, + logger, + options, +}: { + workspace: Workspace; + project: Project; + to: PackageManagerDetails; + logger: Logger; + options?: Options; +}): void { + // this step isn't required if moving between yarn / npm + if ( + ["yarn", "npm"].includes(to.name) && + ["yarn", "npm"].includes(project.packageManager) + ) { + return; + } + + // update all dependencies + const workspacePackageJson = getPackageJson({ + workspaceRoot: workspace.paths.root, + }); + + // collect stats as we go for consolidated output at the end + const stats: Record<keyof PackageJsonDependencies, Array<string>> = { + dependencies: [], + devDependencies: [], + peerDependencies: [], + optionalDependencies: [], + }; + + const allDependencyKeys: Array<keyof PackageJsonDependencies> = [ + "dependencies", + "devDependencies", + "peerDependencies", + "optionalDependencies", + ]; + + allDependencyKeys.forEach((depKey) => { + const depList = workspacePackageJson[depKey]; + if (depList) { + const { updated, dependencyList } = updateDependencyList({ + dependencyList: depList, + project, + to, + }); + + workspacePackageJson[depKey] = dependencyList; + stats[depKey] = updated; + } + }); + + const toLog = (key: keyof PackageJsonDependencies) => { + const total = stats[key].length; + if (total > 0) { + return `${chalk.green(total.toString())} ${key}`; + } + return undefined; + }; + + const allChanges = allDependencyKeys.map(toLog).filter(Boolean); + const workspaceLocation = `./${path.relative( + project.paths.root, + workspace.paths.packageJson + )}`; + if (allChanges.length >= 1) { + let logLine = "updating"; + allChanges.forEach((stat, idx) => { + if (allChanges.length === 1) { + logLine += ` ${stat} in ${workspaceLocation}`; + } else { + if (idx === allChanges.length - 1) { + logLine += `and ${stat} in ${workspaceLocation}`; + } else { + logLine += ` ${stat}, `; + } + } + }); + + logger.workspaceStep(logLine); + } else { + logger.workspaceStep( + `no workspace dependencies found in ${workspaceLocation}` + ); + } + + if (!options?.dry) { + fs.writeJSONSync(workspace.paths.packageJson, workspacePackageJson, { + spaces: 2, + }); + } +} diff --git a/packages/turbo-workspaces/src/utils.ts b/packages/turbo-workspaces/src/utils.ts new file mode 100644 index 0000000..8290203 --- /dev/null +++ b/packages/turbo-workspaces/src/utils.ts @@ -0,0 +1,197 @@ +import fs from "fs-extra"; +import path from "path"; +import glob from "fast-glob"; +import yaml from "js-yaml"; +import { + PackageJson, + PackageManager, + Project, + Workspace, + WorkspaceInfo, +} from "./types"; +import { ConvertError } from "./errors"; + +// adapted from https://github.com/nodejs/corepack/blob/cae770694e62f15fed33dd8023649d77d96023c1/sources/specUtils.ts#L14 +const PACKAGE_MANAGER_REGEX = /^(?!_)(.+)@(.+)$/; + +function getPackageJson({ + workspaceRoot, +}: { + workspaceRoot: string; +}): PackageJson { + const packageJsonPath = path.join(workspaceRoot, "package.json"); + try { + return fs.readJsonSync(packageJsonPath, "utf8"); + } catch (err) { + if (err && typeof err === "object" && "code" in err) { + if (err.code === "ENOENT") { + throw new ConvertError(`no "package.json" found at ${workspaceRoot}`, { + type: "package_json-missing", + }); + } + if (err.code === "EJSONPARSE") { + throw new ConvertError( + `failed to parse "package.json" at ${workspaceRoot}`, + { + type: "package_json-parse_error", + } + ); + } + } + throw new Error( + `unexpected error reading "package.json" at ${workspaceRoot}` + ); + } +} + +function getWorkspacePackageManager({ + workspaceRoot, +}: { + workspaceRoot: string; +}): string | undefined { + const { packageManager } = getPackageJson({ workspaceRoot }); + if (packageManager) { + try { + const match = packageManager.match(PACKAGE_MANAGER_REGEX); + if (match) { + const [_, manager] = match; + return manager; + } + } catch (err) { + // this won't always exist. + } + } + return undefined; +} + +function getWorkspaceInfo({ + workspaceRoot, +}: { + workspaceRoot: string; +}): WorkspaceInfo { + const packageJson = getPackageJson({ workspaceRoot }); + const workspaceDirectory = path.basename(workspaceRoot); + + const { name = workspaceDirectory, description } = packageJson; + + return { + name, + description, + }; +} + +function getPnpmWorkspaces({ + workspaceRoot, +}: { + workspaceRoot: string; +}): Array<string> { + const workspaceFile = path.join(workspaceRoot, "pnpm-workspace.yaml"); + if (fs.existsSync(workspaceFile)) { + try { + const workspaceConfig = yaml.load(fs.readFileSync(workspaceFile, "utf8")); + // validate it's the type we expect + if ( + workspaceConfig instanceof Object && + "packages" in workspaceConfig && + Array.isArray(workspaceConfig.packages) + ) { + return workspaceConfig.packages as Array<string>; + } + } catch (err) { + throw new ConvertError(`failed to parse ${workspaceFile}`, { + type: "pnpm-workspace_parse_error", + }); + } + } + + return []; +} + +function expandPaths({ + root, + lockFile, + workspaceConfig, +}: { + root: string; + lockFile: string; + workspaceConfig?: string; +}) { + const fromRoot = (p: string) => path.join(root, p); + const paths: Project["paths"] = { + root, + lockfile: fromRoot(lockFile), + packageJson: fromRoot("package.json"), + nodeModules: fromRoot("node_modules"), + }; + + if (workspaceConfig) { + paths.workspaceConfig = fromRoot(workspaceConfig); + } + + return paths; +} + +function expandWorkspaces({ + workspaceRoot, + workspaceGlobs, +}: { + workspaceRoot: string; + workspaceGlobs?: string[]; +}): Array<Workspace> { + if (!workspaceGlobs) { + return []; + } + return workspaceGlobs + .flatMap((workspaceGlob) => { + const workspacePackageJsonGlob = `${workspaceGlob}/package.json`; + return glob.sync(workspacePackageJsonGlob, { + onlyFiles: true, + absolute: true, + cwd: workspaceRoot, + }); + }) + .map((workspacePackageJson) => { + const workspaceRoot = path.dirname(workspacePackageJson); + const { name, description } = getWorkspaceInfo({ workspaceRoot }); + return { + name, + description, + paths: { + root: workspaceRoot, + packageJson: workspacePackageJson, + nodeModules: path.join(workspaceRoot, "node_modules"), + }, + }; + }); +} + +function directoryInfo({ directory }: { directory: string }) { + const dir = path.resolve(process.cwd(), directory); + return { exists: fs.existsSync(dir), absolute: dir }; +} + +function getMainStep({ + packageManager, + action, + project, +}: { + packageManager: PackageManager; + action: "create" | "remove"; + project: Project; +}) { + const hasWorkspaces = project.workspaceData.globs.length > 0; + return `${action === "remove" ? "Removing" : "Adding"} ${packageManager} ${ + hasWorkspaces ? "workspaces" : "" + } ${action === "remove" ? "from" : "to"} ${project.name}`; +} + +export { + getPackageJson, + getWorkspacePackageManager, + getWorkspaceInfo, + expandPaths, + expandWorkspaces, + getPnpmWorkspaces, + directoryInfo, + getMainStep, +}; diff --git a/packages/turbo-workspaces/tsconfig.json b/packages/turbo-workspaces/tsconfig.json new file mode 100644 index 0000000..0620a3c --- /dev/null +++ b/packages/turbo-workspaces/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@turbo/tsconfig/library.json", + "compilerOptions": { + "rootDir": "." + } +} diff --git a/packages/turbo-workspaces/tsup.config.ts b/packages/turbo-workspaces/tsup.config.ts new file mode 100644 index 0000000..168e1de --- /dev/null +++ b/packages/turbo-workspaces/tsup.config.ts @@ -0,0 +1,10 @@ +import { defineConfig, Options } from "tsup"; + +export default defineConfig((options: Options) => ({ + entry: ["src/index.ts", "src/cli.ts"], + format: ["cjs"], + dts: true, + clean: true, + minify: true, + ...options, +})); diff --git a/packages/turbo-workspaces/turbo.json b/packages/turbo-workspaces/turbo.json new file mode 100644 index 0000000..fc0bd3b --- /dev/null +++ b/packages/turbo-workspaces/turbo.json @@ -0,0 +1,9 @@ +{ + "$schema": "../../docs/public/schema.json", + "extends": ["//"], + "pipeline": { + "build": { + "dependsOn": ["^build"] + } + } +} |
