feat: replace tilde with homedir (#9337)

close #9217
This commit is contained in:
Khải
2025-03-30 05:34:14 +07:00
committed by GitHub
parent a54d3adbd5
commit e57f1df3cf
5 changed files with 63 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
---
"@pnpm/config": minor
"pnpm": minor
---
Replace leading `~/` in a path in `.npmrc` with the home directory [#9217](https://github.com/pnpm/pnpm/issues/9217).

View File

@@ -203,6 +203,7 @@ export interface Config extends OptionsFromRootManifest {
dedupeDirectDeps?: boolean
extendNodePath?: boolean
gitBranchLockfile?: boolean
globalBinDir?: string
globalDir?: string
globalPkgDir: string
lockfile?: boolean

View File

@@ -20,6 +20,7 @@ import which from 'which'
import { inheritAuthConfig } from './auth'
import { checkGlobalBinDir } from './checkGlobalBinDir'
import { getNetworkConfigs } from './getNetworkConfigs'
import { transformPathKeys } from './transformPath'
import { getCacheDir, getConfigDir, getDataDir, getStateDir } from './dirs'
import {
type Config,
@@ -517,6 +518,8 @@ export async function getConfig (opts: {
pnpmConfig.dev = true
}
transformPathKeys(pnpmConfig, os.homedir())
return { config: pnpmConfig, warnings }
}

View File

@@ -0,0 +1,23 @@
import { join } from 'path'
import { type Config } from './Config'
const REGEX = /^~[/\\]/
export const transformPath = (path: string, homedir: string): string =>
REGEX.test(path) ? join(homedir, path.replace(REGEX, '')) : path
const PATH_KEYS = [
'cacheDir',
'globalBinDir',
'globalDir',
'pnpmHomeDir',
'storeDir',
] as const satisfies Array<keyof Config>
export function transformPathKeys (config: Partial<Pick<Config, typeof PATH_KEYS[number]>>, homedir: string): void {
for (const key of PATH_KEYS) {
if (config[key]) {
config[key] = transformPath(config[key], homedir)
}
}
}

View File

@@ -0,0 +1,30 @@
import path from 'path'
import { type Config } from '../src/Config'
import { transformPath, transformPathKeys } from '../src/transformPath'
describe('transformPath', () => {
test('replaces starting tilde with homedir', () => {
expect(transformPath('~/.local/share/pnpm', '/home/user')).toBe(path.join('/home/user', '.local/share/pnpm'))
expect(transformPath('~\\.local\\share\\pnpm', 'C:\\Users\\user')).toBe(path.join('C:\\Users\\user', '.local\\share\\pnpm'))
})
test('leaves non leading tilde as-is', () => {
expect(transformPath('foo/bar/~/baz', '/home/user')).toBe('foo/bar/~/baz')
})
test('leaves leading tilde not being followed by separator as-is', () => {
expect(transformPath('~foo/bar/baz', '/home/user')).toBe('~foo/bar/baz')
})
})
test('transformPathKeys', () => {
const config: Partial<Config> = {
cacheDir: '~/.cache/pnpm',
storeDir: '~/.local/share/pnpm',
}
transformPathKeys(config, '/home/user')
expect(config).toStrictEqual({
cacheDir: path.join('/home/user', '.cache/pnpm'),
storeDir: path.join('/home/user', '.local/share/pnpm'),
})
})