-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add @yarnpkg/tools
package with detectPackageManager
function
#3408
Draft
paul-soporan
wants to merge
1
commit into
master
Choose a base branch
from
paul/feat/detectPm
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
{ | ||
"name": "@yarnpkg/tools", | ||
"version": "1.0.0", | ||
"license": "BSD-2-Clause", | ||
"main": "./sources/index.ts", | ||
"scripts": { | ||
"postpack": "rm -rf lib", | ||
"prepack": "run build:compile \"$(pwd)\"", | ||
"release": "yarn npm publish", | ||
"test": "run test:unit \"$(pwd)\"" | ||
}, | ||
"publishConfig": { | ||
"main": "./lib/index.js", | ||
"typings": "./lib/index.d.ts" | ||
}, | ||
"files": [ | ||
"/lib/**/*" | ||
], | ||
"repository": { | ||
"type": "git", | ||
"url": "ssh://[email protected]/yarnpkg/berry.git", | ||
"directory": "packages/yarnpkg-tools" | ||
}, | ||
"engines": { | ||
"node": ">=12 <14 || 14.2 - 14.9 || >14.10.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,293 @@ | ||
import fs from 'fs'; | ||
import path from 'path'; | ||
|
||
const MANIFEST_FILENAME = `package.json`; | ||
const NODE_MODULES_FILENAME = `node_modules`; | ||
const PNP_JS_FILENAME = `.pnp.js`; | ||
|
||
const nodeModulesRegExp = /[\\/]node_modules[\\/](@[^\\/]*[\\/])?([^@\\/][^\\/]*)$/; | ||
|
||
class AmbiguousPackageManagerChoiceError extends Error { | ||
constructor(message: string, cwd: string) { | ||
super(`${message} Please specify your package manager choice using the "packageManager" field in ${path.join(cwd, MANIFEST_FILENAME)}.`); | ||
this.name = `AmbiguousPackageManagerChoiceError`; | ||
} | ||
} | ||
|
||
export enum PackageManager { | ||
YARN = `yarn`, | ||
PNPM = `pnpm`, | ||
NPM = `npm`, | ||
} | ||
|
||
export const Lockfile = { | ||
[PackageManager.YARN]: `yarn.lock`, | ||
[PackageManager.PNPM]: `pnpm-lock.yaml`, | ||
[PackageManager.NPM]: `package-lock.json`, | ||
}; | ||
|
||
type BasePackageManagerSpec<T extends PackageManager> = { | ||
name: T; | ||
reason: string; | ||
}; | ||
|
||
type MakePackageManagerSpec<T extends PackageManager, O extends object = {}> = BasePackageManagerSpec<T> & O; | ||
|
||
export type PackageManagerSpec = | ||
| MakePackageManagerSpec<PackageManager.YARN, {isClassic: boolean}> | ||
| MakePackageManagerSpec<PackageManager.PNPM> | ||
| MakePackageManagerSpec<PackageManager.NPM>; | ||
|
||
/** | ||
* Tries to detect the package manager from the user-agent. | ||
*/ | ||
function detectPackageManagerFromUserAgent(env: NodeJS.ProcessEnv): PackageManagerSpec | null { | ||
const userAgent = env.npm_config_user_agent; | ||
if (typeof userAgent === `undefined`) | ||
return null; | ||
|
||
const fields = userAgent.split(` `); | ||
|
||
for (const field of fields) { | ||
const [name, value] = field.split(`/`); | ||
|
||
if (name === PackageManager.YARN) { | ||
return { | ||
name: PackageManager.YARN, | ||
reason: `Found "${field}" in npm_config_user_agent`, | ||
isClassic: value.startsWith(`0`) || value.startsWith(`1`), | ||
}; | ||
} | ||
|
||
for (const pm of [PackageManager.PNPM, PackageManager.NPM] as const) { | ||
if (name === pm) { | ||
return { | ||
name, | ||
reason: `Found "${field}" in npm_config_user_agent`, | ||
}; | ||
} | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
|
||
/** | ||
* Tries to detect the package manager by going up the directory tree and searching for install artifacts. | ||
* | ||
* Yarn modern can't hit this codepath because it always generates a lockfile. | ||
*/ | ||
function detectPackageManagerFromInstallArtifacts(initialCwd: string): PackageManagerSpec | null { | ||
let nextCwd = initialCwd; | ||
let currCwd = ``; | ||
|
||
const packageManagerSpecs: Array<PackageManagerSpec> = []; | ||
|
||
while (nextCwd !== currCwd && packageManagerSpecs.length === 0) { | ||
currCwd = nextCwd; | ||
nextCwd = path.dirname(currCwd); | ||
|
||
if (nodeModulesRegExp.test(currCwd)) | ||
continue; | ||
|
||
const nodeModulesFolder = path.join(currCwd, NODE_MODULES_FILENAME); | ||
if (fs.existsSync(nodeModulesFolder)) { | ||
// Only generated by Yarn classic when operating in NM mode | ||
if (fs.existsSync(path.join(nodeModulesFolder, `.yarn-integrity`))) { | ||
packageManagerSpecs.push({ | ||
name: PackageManager.YARN, | ||
reason: `Found .yarn-integrity in ${nodeModulesFolder}`, | ||
isClassic: true, | ||
}); | ||
} | ||
|
||
// Only generated by PNPM when operating in any mode | ||
if (fs.existsSync(path.join(nodeModulesFolder, `.modules.yaml`))) { | ||
packageManagerSpecs.push({ | ||
name: PackageManager.PNPM, | ||
reason: `Found .modules.yaml in ${nodeModulesFolder}`, | ||
}); | ||
} | ||
|
||
// Only generated by npm@7 | ||
if (fs.existsSync(path.join(nodeModulesFolder, `.package-lock.json`))) { | ||
packageManagerSpecs.push({ | ||
name: PackageManager.NPM, | ||
reason: `Found .package-lock.json in ${nodeModulesFolder}`, | ||
}); | ||
} | ||
} | ||
|
||
// - Yarn modern can't hit this codepath because it always has a lockfile | ||
// - PNPM can't hit this codepath because it always generates node_modules/.modules.yaml | ||
// - Because of this, it's safe to assume it's Yarn classic operating in PnP mode | ||
if (fs.existsSync(path.join(currCwd, PNP_JS_FILENAME)) && !fs.existsSync(path.join(nodeModulesFolder, `.modules.yaml`))) { | ||
packageManagerSpecs.push({ | ||
name: PackageManager.YARN, | ||
reason: `Found .pnp.js in ${currCwd}`, | ||
isClassic: true, | ||
}); | ||
} | ||
} | ||
|
||
|
||
if (packageManagerSpecs.length === 0) | ||
return null; | ||
|
||
if (packageManagerSpecs.length > 1) | ||
throw new AmbiguousPackageManagerChoiceError(`Multiple install artifacts corresponding to the following package managers found: ${packageManagerSpecs.map(({name}) => JSON.stringify(name)).join(`, `)}`, currCwd); | ||
|
||
return packageManagerSpecs[0]; | ||
} | ||
|
||
/** | ||
* Tries to detect the package manager by going up the directory tree and searching for lockfiles. | ||
*/ | ||
function detectPackageManagerFromLockfiles(initialCwd: string): PackageManagerSpec | null { | ||
let nextCwd = initialCwd; | ||
let currCwd = ``; | ||
|
||
const packageManagerSpecs: Array<PackageManagerSpec> = []; | ||
|
||
while (nextCwd !== currCwd && packageManagerSpecs.length === 0) { | ||
currCwd = nextCwd; | ||
nextCwd = path.dirname(currCwd); | ||
|
||
if (nodeModulesRegExp.test(currCwd)) | ||
continue; | ||
|
||
if (fs.existsSync(path.join(currCwd, Lockfile[PackageManager.YARN]))) { | ||
const lockfile = fs.readFileSync(path.join(currCwd, Lockfile[PackageManager.YARN]), `utf8`); | ||
// Modern lockfiles always have a "__metadata" key. | ||
if (lockfile.match(/^__metadata:$/m)) { | ||
packageManagerSpecs.push({ | ||
name: PackageManager.YARN, | ||
isClassic: false, | ||
reason: `Found ${Lockfile[PackageManager.YARN]} containing "__metadata:" key in ${currCwd}`, | ||
}); | ||
} else { | ||
packageManagerSpecs.push({ | ||
name: PackageManager.YARN, | ||
isClassic: true, | ||
reason: `Found ${Lockfile[PackageManager.YARN]} not containing "__metadata:" key in ${currCwd}`, | ||
}); | ||
} | ||
} | ||
|
||
for (const pm of [PackageManager.PNPM, PackageManager.NPM] as const) { | ||
if (fs.existsSync(path.join(currCwd, Lockfile[pm]))) { | ||
packageManagerSpecs.push({ | ||
name: pm, | ||
reason: `Found ${Lockfile[pm]} in ${currCwd}`, | ||
}); | ||
} | ||
} | ||
} | ||
|
||
if (packageManagerSpecs.length === 0) | ||
return null; | ||
|
||
if (packageManagerSpecs.length > 1) | ||
throw new AmbiguousPackageManagerChoiceError(`Multiple lockfiles found: ${packageManagerSpecs.map(({name}) => JSON.stringify(Lockfile[name])).join(`, `)}`, currCwd); | ||
|
||
return packageManagerSpecs[0]; | ||
} | ||
|
||
/** | ||
* Tries to detect the package manager from the closest manifest going up the directory tree by reading the "packageManager" field. | ||
*/ | ||
function detectPackageManagerFromManifest(initialCwd: string): PackageManagerSpec | null { | ||
let nextCwd = initialCwd; | ||
let currCwd = ``; | ||
|
||
let selection: { | ||
data: any; | ||
manifestPath: string; | ||
} | null = null; | ||
|
||
while (nextCwd !== currCwd && (!selection || !selection.data.packageManager)) { | ||
currCwd = nextCwd; | ||
nextCwd = path.dirname(currCwd); | ||
|
||
if (nodeModulesRegExp.test(currCwd)) | ||
continue; | ||
|
||
const manifestPath = path.join(currCwd, MANIFEST_FILENAME); | ||
if (!fs.existsSync(manifestPath)) | ||
continue; | ||
|
||
const content = fs.readFileSync(manifestPath, `utf8`); | ||
|
||
let data; | ||
try { | ||
data = JSON.parse(content); | ||
} catch {} | ||
|
||
if (typeof data !== `object` || data === null) | ||
throw new Error(`Invalid package.json in ${path.relative(initialCwd, manifestPath)}`); | ||
|
||
selection = {data, manifestPath}; | ||
} | ||
|
||
if (selection === null) | ||
return null; | ||
|
||
const rawPmSpec = selection.data.packageManager; | ||
if (typeof rawPmSpec !== `string`) | ||
return null; | ||
|
||
const [name, value] = rawPmSpec.split(`@`); | ||
if (name === PackageManager.YARN) { | ||
return { | ||
name: PackageManager.YARN, | ||
reason: `Found "${rawPmSpec}" in the "packageManager" field of ${selection.manifestPath}`, | ||
isClassic: value.startsWith(`0`) || value.startsWith(`1`), | ||
}; | ||
} | ||
|
||
for (const pm of [PackageManager.PNPM, PackageManager.NPM] as const) { | ||
if (name === pm) { | ||
return { | ||
name, | ||
reason: `Found "${rawPmSpec}" in the "packageManager" field of ${selection.manifestPath}`, | ||
}; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
|
||
/** | ||
* Tries to detect the package manager from the current project. | ||
* | ||
* _**Important:**_ You likely want to use `detectPackageManager` instead. | ||
* | ||
* @internal | ||
*/ | ||
export function detectPackageManagerFromProject(cwd: string): PackageManagerSpec | null { | ||
const manifestPm = detectPackageManagerFromManifest(cwd); | ||
if (manifestPm !== null) | ||
return manifestPm; | ||
|
||
const lockfilePm = detectPackageManagerFromLockfiles(cwd); | ||
if (lockfilePm !== null) | ||
return lockfilePm; | ||
|
||
const installArtifactPm = detectPackageManagerFromInstallArtifacts(cwd); | ||
if (installArtifactPm !== null) | ||
return installArtifactPm; | ||
|
||
return null; | ||
} | ||
|
||
export function detectPackageManager(cwd: string, env: NodeJS.ProcessEnv = process.env): PackageManagerSpec | null { | ||
const projectPm = detectPackageManagerFromProject(cwd); | ||
if (projectPm !== null) | ||
return projectPm; | ||
|
||
const userAgentPm = detectPackageManagerFromUserAgent(env); | ||
if (userAgentPm !== null) | ||
return userAgentPm; | ||
|
||
return null; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This will be a problem with Yarn 10 😆