Skip to content

Commit

Permalink
fix(init): use locally installed version of given package (#7721)
Browse files Browse the repository at this point in the history
`npm init` calls `libnpmexec` with path and runPath, for most cases it
would not matter but when we have a package installed locally on root
and we want to run `npm init that-package -w workspace` it should
identify that-package is installed and use that to init new workspace
package. here the `path` is where node_modules are and `runPath` is cwd
to run the command.
Fixes: #7700
  • Loading branch information
milaninfy authored Aug 13, 2024
1 parent 4e81a6a commit 91e46a3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
5 changes: 2 additions & 3 deletions lib/commands/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ class Init extends BaseCommand {
await this.update(workspacesPaths)
}

async execCreate (args, path = process.cwd()) {
async execCreate (args, runPath = process.cwd()) {
const [initerName, ...otherArgs] = args
let packageName = initerName

Expand Down Expand Up @@ -129,7 +129,6 @@ class Init extends BaseCommand {
globalBin,
chalk,
} = this.npm
const runPath = path
const scriptShell = this.npm.config.get('script-shell') || undefined
const yes = this.npm.config.get('yes')

Expand All @@ -140,7 +139,7 @@ class Init extends BaseCommand {
globalBin,
output,
chalk,
path,
path: this.npm.localPrefix,
runPath,
scriptShell,
yes,
Expand Down
30 changes: 30 additions & 0 deletions test/lib/commands/init.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const t = require('tap')
const fs = require('node:fs/promises')
const nodePath = require('node:path')
const { resolve, basename } = require('node:path')
const _mockNpm = require('../../fixtures/mock-npm')
const { cleanTime } = require('../../fixtures/clean-snapshot')
Expand Down Expand Up @@ -428,4 +429,33 @@ t.test('workspaces', async t => {
t.equal(ws.version, '1.0.0')
t.equal(ws.license, 'ISC')
})
t.test('init pkg - installed workspace package', async t => {
const { npm } = await mockNpm(t, {
prefixDir: {
'package.json': JSON.stringify({
name: 'init-ws-test',
dependencies: {
'@npmcli/create': '1.0.0',
},
workspaces: ['test/workspace-init-a'],
}),
'test/workspace-init-a': {
'package.json': JSON.stringify({
version: '1.0.0',
name: '@npmcli/create',
bin: { 'init-create': 'index.js' },
}),
'index.js': `#!/usr/bin/env node
require('fs').writeFileSync('npm-init-test-success', '')
console.log('init-create ran')`,
},
},
})
await npm.exec('install', []) // reify
npm.config.set('workspace', ['test/workspace-init-b'])
await npm.exec('init', ['@npmcli'])
const exists = await fs.stat(nodePath.join(
npm.prefix, 'test/workspace-init-b', 'npm-init-test-success'))
t.ok(exists.isFile(), 'bin ran, creating file inside workspace')
})
})

0 comments on commit 91e46a3

Please sign in to comment.