Skip to content
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 Yarn Berry & pnpm support #876

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://editorconfig.org/

root = true

[*]
end_of_line = lf
insert_final_newline = true
11 changes: 11 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"arrowParens": "avoid",
"endOfLine": "lf",
"printWidth": 120,
"quoteProps": "as-needed",
"semi": true,
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "es5",
"useTabs": true
}
5 changes: 4 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ module.exports = function (argv: string[]): void {
program
.command('package [version]')
.description('Packages an extension')
.option('-o, --out <path>', 'Output .vsix extension file to <path> location (defaults to <name>-<version>.vsix)')
.option(
'-o, --out <path>',
'Output .vsix extension file to <path> location (defaults to <name>-<version>.vsix)'
)
.option('-t, --target <target>', `Target architecture. Valid targets: ${ValidTargets}`)
.option('-m, --message <commit message>', 'Commit message used when calling `npm version`.')
.option(
Expand Down
108 changes: 92 additions & 16 deletions src/npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ const exists = (file: string) =>
_ => false
);

export enum VersionedPackageManager {
Npm,
Pnpm,
YarnBerry,
YarnClassic,
None,
}

interface IOptions {
cwd?: string;
stdio?: any;
Expand All @@ -32,17 +40,21 @@ function exec(
return new Promise((c, e) => {
let disposeCancellationListener: Function | null = null;

const child = cp.exec(command, { ...options, encoding: 'utf8' } as any, (err, stdout: string, stderr: string) => {
if (disposeCancellationListener) {
disposeCancellationListener();
disposeCancellationListener = null;
}
const child = cp.exec(
command,
{ ...options, encoding: 'utf8' } as any,
(err, stdout: string, stderr: string) => {
if (disposeCancellationListener) {
disposeCancellationListener();
disposeCancellationListener = null;
}

if (err) {
return e(err);
if (err) {
return e(err);
}
c({ stdout, stderr });
}
c({ stdout, stderr });
});
);

if (cancellationToken) {
disposeCancellationListener = cancellationToken.subscribe((err: any) => {
Expand Down Expand Up @@ -154,7 +166,10 @@ function selectYarnDependencies(deps: YarnDependency[], packagedDependencies: st
return reached.values;
}

async function getYarnProductionDependencies(cwd: string, packagedDependencies?: string[]): Promise<YarnDependency[]> {
async function getYarnBerryProductionDependencies(
cwd: string,
packagedDependencies?: string[]
): Promise<YarnDependency[]> {
const raw = await new Promise<string>((c, e) =>
cp.exec(
'yarn list --prod --json',
Expand Down Expand Up @@ -182,10 +197,48 @@ async function getYarnProductionDependencies(cwd: string, packagedDependencies?:
return result;
}

async function getYarnDependencies(cwd: string, packagedDependencies?: string[]): Promise<string[]> {
async function getYarnClassicProductionDependencies(
cwd: string,
packagedDependencies?: string[]
): Promise<YarnDependency[]> {
const raw = await new Promise<string>((c, e) =>
cp.exec(
'yarn list --prod --json',
{ cwd, encoding: 'utf8', env: { ...process.env }, maxBuffer: 5000 * 1024 },
(err, stdout) => (err ? e(err) : c(stdout))
)
);
const match = /^{"type":"tree".*$/m.exec(raw);

if (!match || match.length !== 1) {
throw new Error('Could not parse result of `yarn list --json`');
}

const usingPackagedDependencies = Array.isArray(packagedDependencies);
const trees = JSON.parse(match[0]).data.trees as YarnTreeNode[];

let result = trees
.map(tree => asYarnDependency(path.join(cwd, 'node_modules'), tree, !usingPackagedDependencies))
.filter(nonnull);

if (usingPackagedDependencies) {
result = selectYarnDependencies(result, packagedDependencies!);
}

return result;
}

async function getYarnDependencies(
cwd: string,
packageManager: VersionedPackageManager.YarnBerry | VersionedPackageManager.YarnClassic,
packagedDependencies?: string[]
): Promise<string[]> {
const result = new Set([cwd]);

const deps = await getYarnProductionDependencies(cwd, packagedDependencies);
const deps =
packageManager === VersionedPackageManager.YarnBerry
? await getYarnBerryProductionDependencies(cwd, packagedDependencies)
: await getYarnClassicProductionDependencies(cwd, packagedDependencies);
const flatten = (dep: YarnDependency) => {
result.add(dep.path);
dep.children.forEach(flatten);
Expand All @@ -195,6 +248,29 @@ async function getYarnDependencies(cwd: string, packagedDependencies?: string[])
return [...result];
}

export async function detectPackageManager(cwd: string): Promise<VersionedPackageManager> {
const cwdFiles = await fs.promises.readdir(cwd);

switch (true) {
case cwdFiles.includes('yarn.lock'):
const yarnLockFileSource = await fs.promises.readFile(path.normalize(`${cwd}/yarn.lock`), 'utf-8');

// We use the lockfile introduction comment and not `.yarn/` / `.yarnrc.yml` to detect Yarn Classic
// because Yarn v3 also generates those when set to `classic` version
return yarnLockFileSource.includes('yarn lockfile v1')
? VersionedPackageManager.YarnClassic
: VersionedPackageManager.YarnBerry;

case cwdFiles.includes('pnpm-lock.yaml'):
return VersionedPackageManager.Pnpm;

case cwdFiles.includes('package-lock.json'):
return VersionedPackageManager.Npm;
}

return VersionedPackageManager.None;
}

export async function detectYarn(cwd: string): Promise<boolean> {
for (const name of ['yarn.lock', '.yarnrc', '.yarnrc.yaml', '.pnp.cjs', '.yarn']) {
if (await exists(path.join(cwd, name))) {
Expand All @@ -211,13 +287,13 @@ export async function detectYarn(cwd: string): Promise<boolean> {

export async function getDependencies(
cwd: string,
dependencies: 'npm' | 'yarn' | 'none' | undefined,
packageManager: VersionedPackageManager | undefined,
packagedDependencies?: string[]
): Promise<string[]> {
if (dependencies === 'none') {
if (packageManager === VersionedPackageManager.None) {
return [cwd];
} else if (dependencies === 'yarn' || (dependencies === undefined && (await detectYarn(cwd)))) {
return await getYarnDependencies(cwd, packagedDependencies);
} else if (packageManager === VersionedPackageManager.YarnBerry) {
return await getYarnDependencies(cwd, packageManager, packagedDependencies);
} else {
return await getNpmDependencies(cwd);
}
Expand Down