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

Package manager pnpm #4920

Closed
wants to merge 8 commits into from
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 214 additions & 0 deletions packages/core/package-manager/src/Pnpm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
// @flow strict-local

import type {PackageInstaller, InstallerOptions} from './types';

import commandExists from 'command-exists';
import spawn from 'cross-spawn';
import logger from '@parcel/logger';
import promiseFromProcess from './promiseFromProcess';
import {registerSerializableClass} from '@parcel/core';
import {npmSpecifierFromModuleRequest} from './utils';
import split from 'split2';
import JSONParseStream from './JSONParseStream';

// $FlowFixMe
import pkg from '../package.json';

const PNPM_CMD = 'pnpm';

let hasPnpm: ?boolean;
export class Pnpm implements PackageInstaller {
static async exists(): Promise<boolean> {
if (hasPnpm != null) {
return hasPnpm;
}

try {
hasPnpm = Boolean(await commandExists('pnpm'));
} catch (err) {
hasPnpm = false;
}

return hasPnpm;
}

async install({
modules,
cwd,
saveDev = true,
}: InstallerOptions): Promise<void> {
let args = ['add', '--reporter', 'ndjson', saveDev ? '-D' : ''].concat(
modules.map(npmSpecifierFromModuleRequest),
);

let addedCount = 0;
let removedCount = 0;
let installProcess = spawn(PNPM_CMD, args, {
cwd,
env: {...process.env, NODE_ENV: 'development'},
});

installProcess.stdout
.pipe(split())
.pipe(new JSONParseStream())
.on('error', e => {
logger.warn({
origin: '@parcel/package-manager',
message: e.chunk,
stack: e.stack,
});
})
.on('data', (json: PNPMResults) => {
if (json.level === 'error') {
logger.error({
origin: '@parcel/package-manager',
message: json.err.message,
stack: json.err.stack,
});
return;
}
if (json.level === 'info' && typeof json.message === 'string') {
logger.info({
origin: '@parcel/package-manager',
message: prefix(json.message),
});
return;
}

switch (json.name) {
case 'pnpm:importing':
logger.progress(prefix(`[importing] ${json.to}`));
return;
case 'pnpm:link':
logger.progress(prefix(`[link] ${json.link}`));
return;
case 'pnpm:progress':
logger.info({
origin: '@parcel/package-manager',
message: prefix(`[${json.status}] ${json.packageId}`),
});
return;
case 'pnpm:root':
if (json.added) {
logger.info({
origin: '@parcel/package-manager',
message: prefix(
`[added] ${json.added.name} (${json.added.version || ''})`,
),
});
}
if (json.removed) {
logger.info({
origin: '@parcel/package-manager',
message: prefix(
`[added] ${json.removed.name} (${json.removed.version ||
''})`,
),
});
}
return;
case 'pnpm:stats':
addedCount += json.added || 0;
removedCount += json.removed || 0;

logger.info({
origin: '@parcel/package-manager',
message: prefix(JSON.stringify(json)),
});
return;
}
});

let stderr = [];
installProcess.stderr
.on('data', str => {
stderr.push(str.toString());
})
.on('error', e => {
logger.warn({
origin: '@parcel/package-manager',
message: e.message,
});
});

try {
await promiseFromProcess(installProcess);

if (addedCount > 0) {
logger.log({
origin: '@parcel/package-manager',
message: `Added ${addedCount} packages via pnpm`,
});
}
if (removedCount > 0) {
logger.log({
origin: '@parcel/package-manager',
message: `Removed ${removedCount} packages via pnpm`,
});
}

// Since we succeeded, stderr might have useful information not included
// in the json written to stdout. It's also not necessary to log these as
// errors as they often aren't.
for (let message of stderr) {
logger.log({
origin: '@parcel/package-manager',
message,
});
}
} catch (e) {
throw new Error('pnpm failed to install modules');
}
}
}

type LogLevel = 'error' | 'warn' | 'info' | 'debug';

type ErrorLog = {|
err: {|
message: string,
code: string,
stack: string,
|},
|};

type PNPMLog =
| {|
+name: 'pnpm:progress',
packageId: string,
status: 'fetched' | 'found_in_store' | 'resolved',
|}
| {|
+name: 'pnpm:root',
added?: {|
id?: string,
name: string,
realName: string,
version?: string,
dependencyType?: 'prod' | 'dev' | 'optional',
latest?: string,
linkedFrom?: string,
|},
removed?: {|
name: string,
version?: string,
dependencyType?: 'prod' | 'dev' | 'optional',
|},
|}
| {|+name: 'pnpm:importing', from: string, method: string, to: string|}
| {|+name: 'pnpm:link', target: string, link: string|}
| {|+name: 'pnpm:stats', prefix: string, removed?: number, added?: number|};

type PNPMResults = {|
level: LogLevel,
prefix?: string,
message?: string,
...ErrorLog,
...PNPMLog,
|};

function prefix(message: string): string {
return 'pnpm: ' + message;
}

registerSerializableClass(`${pkg.version}:Pnpm`, Pnpm);
1 change: 1 addition & 0 deletions packages/core/package-manager/src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @flow
export * from './types';
export * from './Npm';
export * from './Pnpm';
export * from './Yarn';
export * from './MockPackageInstaller';
export * from './NodePackageManager';
28 changes: 23 additions & 5 deletions packages/core/package-manager/src/installPackage.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import WorkerFarm from '@parcel/workers';

import {Npm} from './Npm';
import {Yarn} from './Yarn';
import {Pnpm} from './Pnpm.js';
import {getConflictingLocalDependencies} from './utils';
import validateModuleSpecifier from './validateModuleSpecifier';

Expand Down Expand Up @@ -126,18 +127,35 @@ async function determinePackageInstaller(
filepath: FilePath,
): Promise<PackageInstaller> {
let configFile = await resolveConfig(fs, filepath, [
'pnpm-lock.yaml',
'yarn.lock',
'package-lock.json',
]);
let hasYarn = await Yarn.exists();

// If Yarn isn't available, or there is a package-lock.json file, use npm.
let configName = configFile && path.basename(configFile);
if (!hasYarn || configName === 'package-lock.json') {
return new Npm();

switch (configName) {
case 'pnpm-lock.yaml':
if (await Pnpm.exists()) {
return new Pnpm();
}
break;
case 'yarn.lock':
if (await Yarn.exists()) {
return new Yarn();
}
break;
case 'package-lock.json':
return new Npm();
}

return new Yarn();
if (await Pnpm.exists()) {
return new Pnpm();
}
if (await Yarn.exists()) {
return new Yarn();
}
return new Npm();
}

let queue = new PromiseQueue({maxConcurrent: 1});
Expand Down
24 changes: 23 additions & 1 deletion packages/core/parcel-bundler/src/utils/installPackage.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const fs = require('@parcel/fs');
const WorkerFarm = require('@parcel/workers').default;

const YARN_LOCK = 'yarn.lock';
const PNPM_LOCK = 'pnpm_lock.yaml';

async function install(modules, filepath, options = {}) {
let {installPeers = true, saveDev = true, packageManager} = options;
Expand Down Expand Up @@ -76,10 +77,15 @@ async function determinePackageManager(filepath) {
const yarnLockFile = await config.resolve(filepath, [YARN_LOCK]);

/**
* no yarn.lock => use npm
* no yarn.lock => try pnpm then use npm
* yarn.lock => Use yarn, fallback to npm
*/
if (!yarnLockFile) {
if (await config.resolve(filepath, [PNPM_LOCK])) {
if (await checkForPnpmCommand()) {
return 'pnpm';
}
}
return 'npm';
}

Expand All @@ -106,6 +112,22 @@ async function checkForYarnCommand() {
return hasYarn;
}

let hasPnpm = null;

async function checkForPnpmCommand() {
if (hasPnpm != null) {
return hasPnpm;
}

try {
hasPnpm = await commandExists('pnpm');
} catch (err) {
hasPnpm = false;
}

return hasPnpm;
}

let queue = new PromiseQueue(install, {maxConcurrent: 1, retry: false});
module.exports = async function(...args) {
// Ensure that this function is always called on the master process so we
Expand Down