Skip to content

Commit

Permalink
Merge pull request #264 from Mairu/npm-fix
Browse files Browse the repository at this point in the history
fix(npm8+): refactor symlinking to support npm 9+
  • Loading branch information
Mairu authored Nov 22, 2023
2 parents f392264 + 9ee704e commit 89f7226
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
1 change: 1 addition & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ on:
- '**'
tags-ignore:
- '**'
pull_request:

jobs:
run-tests:
Expand Down
37 changes: 21 additions & 16 deletions lib/npm.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,30 @@ var NPMIST = npmist.prototype
*/
async function resolveLinkedWorkspaces(dirPath) {
let fixedLinks = 0;
const files = await fs.readdirAsync(dirPath, { withFileTypes: true });
const dirPromises = [];
for (const file of files) {
const filePath = path.join(dirPath, file.name);
if (file.isSymbolicLink()) {
const linkTarget = await fs.readlinkAsync(filePath);
debug('Fix symlink for ', filePath, 'with target', linkTarget);
await fs.unlinkAsync(filePath);
const packageLockJson = JSON.parse(fs.readFileSync(path.join(dirPath, 'package-lock.json')).toString());
await Promise.all(Object.entries(packageLockJson.packages)
.filter(([pkgPath, pkg]) => pkg.link === true)
.map(async ([pkgPath, pkg]) => {
const linkTarget = path.join(
...pkgPath.split('/').slice(0, -1).map(() => '..'),
pkg.resolved
);
const linkPath = path.join(dirPath, pkgPath);

debug('Create symlink for ', linkPath, 'with target', linkTarget);
if (await fs.accessAsync(linkPath, fs.constants.F_OK).then(() => true).catch(() => false)) {
await fs.unlinkAsync(linkPath);
}

try {
await fs.symlinkAsync(linkTarget, filePath, 'junction');
await fs.symlinkAsync(linkTarget, linkPath, 'junction');
} catch (e) {
await fs.renameAsync(path.join(dirPath, linkTarget), filePath);
await fs.renameAsync(path.join(dirPath, linkTarget), linkPath);
}
fixedLinks++;
} else if (file.isDirectory()) {
dirPromises.push(resolveLinkedWorkspaces(filePath));
}
}
return (await Promise.all(dirPromises)).reduce((sum, num) => sum + num, fixedLinks);
}));

return fixedLinks;
}

/**
Expand Down Expand Up @@ -326,7 +331,7 @@ NPMIST.install = function(v,done){
.then(() => {
if (semver.gte(version, '8.0.0')) {
debug('Fix symlinks for npm version >= 8');
return resolveLinkedWorkspaces(path.join(archivePath, 'node_modules'))
return resolveLinkedWorkspaces(path.join(archivePath))
.then(fixedLinks => {
debug(`Fixed ${fixedLinks} symlinks for npm node_modules`);
});
Expand Down

0 comments on commit 89f7226

Please sign in to comment.