Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,7 @@ export const INSTALL_PAGE: Record<Agent, string> = {
'yarn@berry': 'https://yarnpkg.com/getting-started/install',
'npm': 'https://docs.npmjs.com/cli/configuring-npm/install',
}

export const WORKSPACE_ROOTS: string[] = [
'pnpm-workspace.yaml',
]
Comment thread
luxass marked this conversation as resolved.
Resolved
27 changes: 24 additions & 3 deletions src/detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Agent, AgentName, DetectOptions, DetectResult } from './types'
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import { AGENTS, INSTALL_METADATA, LOCKS } from './constants'
import { AGENTS, INSTALL_METADATA, LOCKS, WORKSPACE_ROOTS } from './constants'

async function pathExists(path: string, type: 'file' | 'dir') {
try {
Expand Down Expand Up @@ -40,6 +40,22 @@ function* lookup(cwd: string = process.cwd()): Generator<string> {
}
}

/**
* Get the root directory of a pnpm workspace
* @param {string} cwd The directory to start looking from
* @returns {Promise<string | null>} The absolute path to the workspace root or null if not found
*/
export async function getWorkspaceRoot(cwd: string = process.cwd()): Promise<string | null> {
for (const directory of lookup(cwd)) {
for (const workspaceRoot of WORKSPACE_ROOTS) {
if (await pathExists(path.join(directory, workspaceRoot), 'file')) {
return directory
}
}
}
return null
}

async function parsePackageJson(
filepath: string,
onUnknown: DetectOptions['onUnknown'],
Expand All @@ -55,7 +71,8 @@ async function parsePackageJson(
* @returns {Promise<DetectResult | null>} The detected package manager or `null` if not found.
*/
export async function detect(options: DetectOptions = {}): Promise<DetectResult | null> {
const { cwd, strategies = ['lockfile', 'packageManager-field', 'devEngines-field'], onUnknown } = options
const { cwd, strategies = ['lockfile', 'packageManager-field', 'devEngines-field'], onUnknown, stop } = options
const resolvedStop = stop ? path.resolve(stop) : undefined

for (const directory of lookup(cwd)) {
for (const strategy of strategies) {
Expand Down Expand Up @@ -98,6 +115,10 @@ export async function detect(options: DetectOptions = {}): Promise<DetectResult
}
}
}

// Stop the traversing if the stop directory is reached
if (resolvedStop && directory === resolvedStop)
break
}

return null
Expand Down Expand Up @@ -150,7 +171,7 @@ async function handlePackageManager(
}
}
}
catch {}
catch { }
return null
}

Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { COMMANDS, constructCommand, resolveCommand } from './commands'
export * from './constants'
export { detect, getUserAgent } from './detect'
export { detect, getUserAgent, getWorkspaceRoot } from './detect'
export * from './types'
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ export interface DetectOptions {
* @param packageManager - The `packageManager` value from package.json file.
*/
onUnknown?: (packageManager: string) => DetectResult | null | undefined
/**
* The path to stop traversing up the directory.
*/
stop?: string

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps a discussion point for others if we should consider stopDir instead (used by lilconfig)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would this be better as a function that takes each dir and call it shouldStop(dir: string)? A static path can have many edge cases of path normalization, tailing slash, etc.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it should be safe since path.resolve(stop) was called so it normalizes it. We could reference how lilconfig handles it though, but I think a string is easier to understand and configure.

}

export interface DetectResult {
Expand Down
59 changes: 58 additions & 1 deletion test/detect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import path from 'node:path'
import fs from 'fs-extra'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { detect } from '../src'
import { detect, getWorkspaceRoot } from '../src'

let basicLog: MockInstance, errorLog: MockInstance, warnLog: MockInstance, infoLog: MockInstance

Expand Down Expand Up @@ -55,3 +55,60 @@ function getFixtureDirs(fixture: string) {
const items = fs.readdirSync(fixtureDir)
return items.filter(item => fs.statSync(path.join(fixtureDir, item)).isDirectory())
}

it('stops at specified directory', async () => {
const cwd = await fs.mkdtemp(path.join(tmpdir(), 'ni-'))

const noFilesDir = path.join(cwd, 'no-files')
const nestedNoFilesDir = path.join(noFilesDir, 'nested')
const parentDir = cwd

await fs.mkdirp(noFilesDir)
await fs.mkdirp(nestedNoFilesDir)

await fs.copy(
path.join(__dirname, 'fixtures', 'lockfile', 'npm'),
parentDir,
)

const resultWithStop = await detect({
cwd: nestedNoFilesDir,
stop: noFilesDir,
})

expect(resultWithStop).toBe(null)

const resultWithoutStop = await detect({
cwd: nestedNoFilesDir,
})

expect(resultWithoutStop).toMatchObject({
name: 'npm',
agent: 'npm',
})
})

it('detects pnpm workspace root', async () => {
const cwd = await fs.mkdtemp(path.join(tmpdir(), 'ni-'))

// setup a pnpm workspace structure
const workspaceDir = path.join(cwd, 'workspace')
const packageDir = path.join(workspaceDir, 'packages', 'foo')

await fs.copy(
path.join(__dirname, 'fixtures', 'workspace', 'pnpm'),
workspaceDir,
)

// should find workspace root from package directory
const rootFromPackage = await getWorkspaceRoot(packageDir)
expect(rootFromPackage).toBe(workspaceDir)

// should find workspace root from workspace directory
const rootFromWorkspace = await getWorkspaceRoot(workspaceDir)
expect(rootFromWorkspace).toBe(workspaceDir)

// should return null when no workspace root
const rootFromOutside = await getWorkspaceRoot(cwd)
expect(rootFromOutside).toBe(null)
})
4 changes: 4 additions & 0 deletions test/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ it('exports-snapshot', async () => {
"INSTALL_METADATA": "object",
"INSTALL_PAGE": "object",
"LOCKS": "object",
"WORKSPACE_ROOTS": "object",
"constructCommand": "function",
"detect": "function",
"getUserAgent": "function",
"getWorkspaceRoot": "function",
"resolveCommand": "function",
},
"./commands": {
Expand All @@ -30,10 +32,12 @@ it('exports-snapshot', async () => {
"INSTALL_METADATA": "object",
"INSTALL_PAGE": "object",
"LOCKS": "object",
"WORKSPACE_ROOTS": "object",
},
"./detect": {
"detect": "function",
"getUserAgent": "function",
"getWorkspaceRoot": "function",
},
}
`)
Expand Down
Empty file.