Fix terminal file links with tilde and spaces (#2971)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import type { IBufferLine, IBufferRange } from '@xterm/xterm'
|
||||
import { extractTerminalFileLinks, resolveTerminalFileLink } from '@/lib/terminal-links'
|
||||
import { extractTerminalFileLinkCandidates, resolveTerminalFileLink } from '@/lib/terminal-links'
|
||||
import { openDetectedFilePath } from './terminal-file-open-routing'
|
||||
import {
|
||||
buildHardWrappedPathLogicalLineCandidates,
|
||||
@@ -10,9 +10,11 @@ import {
|
||||
|
||||
type FileLinkHitTestDeps = {
|
||||
startupCwd: string
|
||||
terminalHomePath?: string | null
|
||||
worktreeId: string
|
||||
worktreePath: string
|
||||
runtimeEnvironmentId?: string | null
|
||||
pathExistsCache?: Map<string, boolean>
|
||||
}
|
||||
|
||||
export function openFilePathLinkAtBufferPosition(
|
||||
@@ -27,8 +29,17 @@ export function openFilePathLinkAtBufferPosition(
|
||||
}
|
||||
|
||||
for (const logicalLine of logicalLines) {
|
||||
for (const parsed of extractTerminalFileLinks(logicalLine.text)) {
|
||||
const resolved = deps.startupCwd ? resolveTerminalFileLink(parsed, deps.startupCwd) : null
|
||||
const matches: {
|
||||
absolutePath: string
|
||||
line: number | null
|
||||
column: number | null
|
||||
pathText: string
|
||||
cachedExists: boolean | undefined
|
||||
}[] = []
|
||||
for (const parsed of extractTerminalFileLinkCandidates(logicalLine.text)) {
|
||||
const resolved = deps.startupCwd
|
||||
? resolveTerminalFileLink(parsed, deps.startupCwd, deps.terminalHomePath)
|
||||
: null
|
||||
if (!resolved) {
|
||||
continue
|
||||
}
|
||||
@@ -36,7 +47,23 @@ export function openFilePathLinkAtBufferPosition(
|
||||
if (!range || !rangeContainsBufferPosition(range, position, terminalColumns)) {
|
||||
continue
|
||||
}
|
||||
openDetectedFilePath(resolved.absolutePath, resolved.line, resolved.column, deps)
|
||||
const cacheKey = `${deps.runtimeEnvironmentId ?? 'active'}\0${resolved.absolutePath}`
|
||||
matches.push({
|
||||
absolutePath: resolved.absolutePath,
|
||||
line: resolved.line,
|
||||
column: resolved.column,
|
||||
pathText: parsed.pathText,
|
||||
cachedExists: deps.pathExistsCache?.get(cacheKey)
|
||||
})
|
||||
}
|
||||
|
||||
const cachedMatch = matches
|
||||
.filter((match) => match.cachedExists)
|
||||
.sort((a, b) => b.pathText.length - a.pathText.length)[0]
|
||||
const uncachedMatch = matches.find((match) => match.cachedExists !== false)
|
||||
const match = cachedMatch ?? uncachedMatch
|
||||
if (match) {
|
||||
openDetectedFilePath(match.absolutePath, match.line, match.column, deps)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,6 +369,31 @@ describe('handleOscLink', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('opens tilde OSC file links against explicit terminal home when cwd is outside home', async () => {
|
||||
setPlatform('Macintosh')
|
||||
|
||||
handleOscLink(
|
||||
'~/file.ts',
|
||||
{ metaKey: true, ctrlKey: false },
|
||||
{
|
||||
...deps,
|
||||
startupCwd: '/workspace/project',
|
||||
terminalHomePath: '/home/alice'
|
||||
}
|
||||
)
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
expect(authorizeExternalPathMock).toHaveBeenCalledWith({
|
||||
targetPath: '/home/alice/file.ts'
|
||||
})
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
filePath: '/home/alice/file.ts'
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('stats remote-runtime file links through the active runtime environment', async () => {
|
||||
setPlatform('Macintosh')
|
||||
storeState.settings = { activeRuntimeEnvironmentId: 'env-1' }
|
||||
@@ -593,7 +618,9 @@ describe('createFilePathLinkProvider range bounds', () => {
|
||||
linkProviderDisposablesRef: { current: new Map<number, IDisposable>() },
|
||||
pathExistsCache: new Map<string, boolean>([
|
||||
['/repo/CLAUDE.md', true],
|
||||
['/repo/package.json', true]
|
||||
['/repo/package.json', true],
|
||||
['/repo/Folder With Space/content.js', true],
|
||||
['/repo/My Folder', true]
|
||||
])
|
||||
},
|
||||
{ textContent: '', style: { display: '' } } as unknown as HTMLElement,
|
||||
@@ -748,6 +775,51 @@ describe('createFilePathLinkProvider range bounds', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a tilde-prefixed path from a direct modifier-click fallback', async () => {
|
||||
setPlatform('Macintosh')
|
||||
|
||||
const opened = openFilePathLinkAtBufferPosition(
|
||||
makeBuffer([makeBufferLine('~/Documents/Path/file_name')]),
|
||||
{ x: 4, y: 1 },
|
||||
80,
|
||||
{
|
||||
startupCwd: '/Users/alice/project',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/Users/alice/project',
|
||||
runtimeEnvironmentId: null
|
||||
}
|
||||
)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(opened).toBe(true)
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filePath: '/Users/alice/Documents/Path/file_name' })
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a tilde path using explicit terminal home when cwd is outside home', async () => {
|
||||
setPlatform('Macintosh')
|
||||
|
||||
const opened = openFilePathLinkAtBufferPosition(
|
||||
makeBuffer([makeBufferLine('~/Documents/Path/file_name')]),
|
||||
{ x: 4, y: 1 },
|
||||
80,
|
||||
{
|
||||
startupCwd: '/workspace/project',
|
||||
terminalHomePath: '/home/alice',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/workspace/project',
|
||||
runtimeEnvironmentId: null
|
||||
}
|
||||
)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(opened).toBe(true)
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filePath: '/home/alice/Documents/Path/file_name' })
|
||||
)
|
||||
})
|
||||
|
||||
it('opens a wrapped continuation-row html path from a direct modifier-click fallback', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const rows = [
|
||||
@@ -776,6 +848,65 @@ describe('createFilePathLinkProvider range bounds', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('returns one file link for an absolute path containing spaces', async () => {
|
||||
const pathText = '/repo/Folder With Space/content.js'
|
||||
const links = await collectLinks(pathText)
|
||||
|
||||
expect(links.map((link) => link.text)).toEqual([pathText])
|
||||
expect(links[0].range).toEqual({
|
||||
start: { x: 1, y: 1 },
|
||||
end: { x: pathText.length, y: 1 }
|
||||
})
|
||||
})
|
||||
|
||||
it('returns one file link for an extensionless path ending in a spaced segment', async () => {
|
||||
const pathText = '/repo/My Folder'
|
||||
const links = await collectLinks(pathText)
|
||||
|
||||
expect(links.map((link) => link.text)).toEqual([pathText])
|
||||
expect(links[0].range).toEqual({
|
||||
start: { x: 1, y: 1 },
|
||||
end: { x: pathText.length, y: 1 }
|
||||
})
|
||||
})
|
||||
|
||||
it('returns an existing extensionless spaced prefix before trailing prose', async () => {
|
||||
vi.mocked(window.api.shell.pathExists).mockImplementation(async (pathValue) => {
|
||||
return pathValue === '/repo/My Folder'
|
||||
})
|
||||
|
||||
const links = await collectLinks('see /repo/My Folder now')
|
||||
|
||||
expect(links.map((link) => link.text)).toEqual(['/repo/My Folder'])
|
||||
})
|
||||
|
||||
it('opens an existing extensionless spaced prefix from direct fallback cache', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const line = 'see /repo/My Folder now'
|
||||
|
||||
const opened = openFilePathLinkAtBufferPosition(
|
||||
makeBuffer([makeBufferLine(line)]),
|
||||
{ x: line.indexOf('Folder') + 1, y: 1 },
|
||||
80,
|
||||
{
|
||||
startupCwd: '/repo',
|
||||
worktreeId: 'wt-1',
|
||||
worktreePath: '/repo',
|
||||
runtimeEnvironmentId: null,
|
||||
pathExistsCache: new Map<string, boolean>([
|
||||
['active\0/repo/My Folder now', false],
|
||||
['active\0/repo/My Folder', true]
|
||||
])
|
||||
}
|
||||
)
|
||||
await flushAsyncWork()
|
||||
|
||||
expect(opened).toBe(true)
|
||||
expect(openFileMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ filePath: '/repo/My Folder' })
|
||||
)
|
||||
})
|
||||
|
||||
it('retries a wrapped file click even when xterm already marked the link active', async () => {
|
||||
setPlatform('Macintosh')
|
||||
const rows = [
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import type { IDisposable, ILink, ILinkProvider, Terminal } from '@xterm/xterm'
|
||||
import { extractTerminalFileLinks, resolveTerminalFileLink } from '@/lib/terminal-links'
|
||||
import {
|
||||
extractTerminalFileLinkCandidates,
|
||||
extractTerminalFileLinks,
|
||||
resolveTerminalFileLink
|
||||
} from '@/lib/terminal-links'
|
||||
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import { isRemoteRuntimeFileOperation, runtimePathExists } from '@/runtime/runtime-file-client'
|
||||
import {
|
||||
@@ -30,6 +34,7 @@ export type LinkHandlerDeps = {
|
||||
linkProviderDisposablesRef: React.RefObject<Map<number, IDisposable>>
|
||||
pathExistsCache: Map<string, boolean>
|
||||
runtimeEnvironmentId?: string | null
|
||||
terminalHomePath?: string | null
|
||||
getRuntimeEnvironmentIdForPane?: (paneId: number) => string | null
|
||||
}
|
||||
|
||||
@@ -38,6 +43,33 @@ type ProvidedFileLink = {
|
||||
logicalLine: WrappedLogicalLine
|
||||
}
|
||||
|
||||
function rangesOverlap(left: ILink['range'], right: ILink['range']): boolean {
|
||||
const leftStartsAfterRightEnds =
|
||||
left.start.y > right.end.y || (left.start.y === right.end.y && left.start.x > right.end.x)
|
||||
const rightStartsAfterLeftEnds =
|
||||
right.start.y > left.end.y || (right.start.y === left.end.y && right.start.x > left.end.x)
|
||||
return !leftStartsAfterRightEnds && !rightStartsAfterLeftEnds
|
||||
}
|
||||
|
||||
function preferLongestNonOverlappingLinks(links: ProvidedFileLink[]): ProvidedFileLink[] {
|
||||
const selected: ProvidedFileLink[] = []
|
||||
const byLengthDescending = [...links].sort(
|
||||
(a, b) =>
|
||||
b.link.text.length - a.link.text.length ||
|
||||
a.link.range.start.y - b.link.range.start.y ||
|
||||
a.link.range.start.x - b.link.range.start.x
|
||||
)
|
||||
for (const link of byLengthDescending) {
|
||||
if (!selected.some((existing) => rangesOverlap(existing.link.range, link.link.range))) {
|
||||
selected.push(link)
|
||||
}
|
||||
}
|
||||
return selected.sort(
|
||||
(a, b) =>
|
||||
a.link.range.start.y - b.link.range.start.y || a.link.range.start.x - b.link.range.start.x
|
||||
)
|
||||
}
|
||||
|
||||
function isMacPlatform(): boolean {
|
||||
return navigator.userAgent.includes('Mac')
|
||||
}
|
||||
@@ -95,9 +127,11 @@ export function createFilePathLinkProvider(
|
||||
|
||||
void Promise.all(
|
||||
logicalLines.flatMap((logicalLine) =>
|
||||
extractTerminalFileLinks(logicalLine.text).map(
|
||||
extractTerminalFileLinkCandidates(logicalLine.text).map(
|
||||
async (parsed): Promise<ProvidedFileLink | null> => {
|
||||
const resolved = startupCwd ? resolveTerminalFileLink(parsed, startupCwd) : null
|
||||
const resolved = startupCwd
|
||||
? resolveTerminalFileLink(parsed, startupCwd, deps.terminalHomePath)
|
||||
: null
|
||||
if (!resolved) {
|
||||
return null
|
||||
}
|
||||
@@ -169,7 +203,7 @@ export function createFilePathLinkProvider(
|
||||
const providedLinks = resolvedLinks.filter(
|
||||
(link): link is ProvidedFileLink => link !== null
|
||||
)
|
||||
const links = providedLinks
|
||||
const links = preferLongestNonOverlappingLinks(providedLinks)
|
||||
.filter(({ logicalLine }) => latestFingerprints.has(logicalLine.fingerprint))
|
||||
.map(({ link }) => link)
|
||||
if (providedLinks.length > 0 && links.length === 0) {
|
||||
@@ -239,9 +273,11 @@ export function installFilePathLinkClickFallback(
|
||||
terminal.cols,
|
||||
{
|
||||
startupCwd: deps.startupCwd,
|
||||
terminalHomePath: deps.terminalHomePath,
|
||||
worktreeId: deps.worktreeId,
|
||||
worktreePath: deps.worktreePath,
|
||||
runtimeEnvironmentId
|
||||
runtimeEnvironmentId,
|
||||
pathExistsCache: deps.pathExistsCache
|
||||
}
|
||||
)
|
||||
if (opened) {
|
||||
|
||||
@@ -12,7 +12,7 @@ export function handleOscLink(
|
||||
rawText: string,
|
||||
event: TerminalLinkEvent | undefined,
|
||||
deps: Pick<LinkHandlerDeps, 'worktreeId' | 'worktreePath'> &
|
||||
Partial<Pick<LinkHandlerDeps, 'runtimeEnvironmentId' | 'startupCwd'>>
|
||||
Partial<Pick<LinkHandlerDeps, 'runtimeEnvironmentId' | 'startupCwd' | 'terminalHomePath'>>
|
||||
): void {
|
||||
if (!isTerminalLinkActivation(event)) {
|
||||
return
|
||||
@@ -33,7 +33,11 @@ export function handleOscLink(
|
||||
try {
|
||||
parsed = new URL(rawText)
|
||||
} catch {
|
||||
const resolved = resolveTerminalFileLinkText(rawText, deps.startupCwd || deps.worktreePath)
|
||||
const resolved = resolveTerminalFileLinkText(
|
||||
rawText,
|
||||
deps.startupCwd || deps.worktreePath,
|
||||
deps.terminalHomePath
|
||||
)
|
||||
if (resolved) {
|
||||
openDetectedFilePath(resolved.absolutePath, resolved.line, resolved.column, deps)
|
||||
}
|
||||
|
||||
@@ -180,6 +180,20 @@ type SplitWithStartupDeps = {
|
||||
startup?: SplitStartupPayload | null
|
||||
}
|
||||
|
||||
function resolveTerminalHomePathFromEnv(env: Record<string, string> | undefined): string | null {
|
||||
const home = env?.HOME?.trim()
|
||||
if (home) {
|
||||
return home
|
||||
}
|
||||
const userProfile = env?.USERPROFILE?.trim()
|
||||
if (userProfile) {
|
||||
return userProfile
|
||||
}
|
||||
const homeDrive = env?.HOMEDRIVE?.trim()
|
||||
const homePath = env?.HOMEPATH?.trim()
|
||||
return homeDrive && homePath ? `${homeDrive}${homePath}` : null
|
||||
}
|
||||
|
||||
/** Scopes `deps.startup` to a single call of `splitPane()`, clearing it in `finally` so later splits do not replay the payload. */
|
||||
export function splitPaneWithOneShotStartup<TPane>(
|
||||
deps: SplitWithStartupDeps,
|
||||
@@ -355,6 +369,7 @@ export function useTerminalPaneLifecycle({
|
||||
cwd ??
|
||||
''
|
||||
const startupCwd = cwd ?? worktreePath
|
||||
const terminalHomePath = resolveTerminalHomePathFromEnv(startup?.env)
|
||||
// Why: existence probes can cross SSH/runtime boundaries. This cache is
|
||||
// lifecycle-scoped, so external mutations and the initial 'active' runtime
|
||||
// fallback can temporarily leave stale entries.
|
||||
@@ -363,6 +378,7 @@ export function useTerminalPaneLifecycle({
|
||||
worktreeId,
|
||||
worktreePath,
|
||||
startupCwd,
|
||||
terminalHomePath,
|
||||
managerRef,
|
||||
linkProviderDisposablesRef,
|
||||
pathExistsCache,
|
||||
|
||||
@@ -62,6 +62,55 @@ describe('terminal path helpers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractTerminalFileLinks local path tokens', () => {
|
||||
it('detects tilde-prefixed POSIX paths', () => {
|
||||
const links = extractTerminalFileLinks('~/Documents/Path/file_name')
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0]).toMatchObject({
|
||||
pathText: '~/Documents/Path/file_name',
|
||||
displayText: '~/Documents/Path/file_name'
|
||||
})
|
||||
})
|
||||
|
||||
it('detects absolute paths with spaces before the filename', () => {
|
||||
const links = extractTerminalFileLinks('/Users/Path/FolderName with Space/content.js')
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0]).toMatchObject({
|
||||
pathText: '/Users/Path/FolderName with Space/content.js',
|
||||
displayText: '/Users/Path/FolderName with Space/content.js'
|
||||
})
|
||||
})
|
||||
|
||||
it('stops a spaced absolute path before trailing prose', () => {
|
||||
const links = extractTerminalFileLinks(
|
||||
'Open /Users/Path/FolderName with Space/content.js for details'
|
||||
)
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0]).toMatchObject({
|
||||
pathText: '/Users/Path/FolderName with Space/content.js',
|
||||
displayText: '/Users/Path/FolderName with Space/content.js'
|
||||
})
|
||||
})
|
||||
|
||||
it('detects an extensionless absolute path ending in a spaced segment', () => {
|
||||
const links = extractTerminalFileLinks('/Users/alice/My Folder')
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0]).toMatchObject({
|
||||
pathText: '/Users/alice/My Folder',
|
||||
displayText: '/Users/alice/My Folder'
|
||||
})
|
||||
})
|
||||
|
||||
it('detects an extensionless relative path ending in a spaced segment', () => {
|
||||
const links = extractTerminalFileLinks('./My Folder')
|
||||
expect(links).toHaveLength(1)
|
||||
expect(links[0]).toMatchObject({
|
||||
pathText: './My Folder',
|
||||
displayText: './My Folder'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('supports Windows cwd resolution for terminal file links', () => {
|
||||
expect(
|
||||
resolveTerminalFileLink(
|
||||
@@ -82,6 +131,67 @@ describe('terminal path helpers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves tilde-prefixed POSIX paths against the cwd user home', () => {
|
||||
expect(
|
||||
resolveTerminalFileLink(
|
||||
{
|
||||
pathText: '~/Documents/Path/file_name',
|
||||
line: null,
|
||||
column: null,
|
||||
startIndex: 0,
|
||||
endIndex: 26,
|
||||
displayText: '~/Documents/Path/file_name'
|
||||
},
|
||||
'/Users/alice/project'
|
||||
)
|
||||
).toEqual({
|
||||
absolutePath: '/Users/alice/Documents/Path/file_name',
|
||||
line: null,
|
||||
column: null
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves tilde-prefixed Windows paths against the cwd user home', () => {
|
||||
expect(
|
||||
resolveTerminalFileLink(
|
||||
{
|
||||
pathText: '~/Documents/Path/file_name',
|
||||
line: null,
|
||||
column: null,
|
||||
startIndex: 0,
|
||||
endIndex: 26,
|
||||
displayText: '~/Documents/Path/file_name'
|
||||
},
|
||||
'C:\\Users\\Alice\\project'
|
||||
)
|
||||
).toEqual({
|
||||
absolutePath: 'C:/Users/Alice/Documents/Path/file_name',
|
||||
line: null,
|
||||
column: null
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves tilde-prefixed paths against explicit terminal home when cwd is outside home', () => {
|
||||
expect(
|
||||
resolveTerminalFileLink(
|
||||
{
|
||||
pathText: '~/Documents/Path/file_name',
|
||||
line: null,
|
||||
column: null,
|
||||
startIndex: 0,
|
||||
endIndex: 26,
|
||||
displayText: '~/Documents/Path/file_name'
|
||||
},
|
||||
'/workspace/project',
|
||||
'/home/alice'
|
||||
)
|
||||
).toEqual({
|
||||
absolutePath: '/home/alice/Documents/Path/file_name',
|
||||
line: null,
|
||||
column: null
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves exact repo-relative OSC hyperlink text', () => {
|
||||
expect(resolveTerminalFileLinkText('docs/README.md', '/repo')).toEqual({
|
||||
absolutePath: '/repo/docs/README.md',
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
/* eslint-disable max-lines -- Why: terminal link parsing depends on ordered passes sharing range state. */
|
||||
import {
|
||||
joinAbsolutePath,
|
||||
normalizeAbsolutePath,
|
||||
resolveTildePath
|
||||
} from './terminal-path-normalization'
|
||||
|
||||
export type ParsedTerminalFileLink = {
|
||||
pathText: string
|
||||
line: number | null
|
||||
@@ -18,7 +25,23 @@ export type ResolvedTerminalFileLink = Pick<ParsedTerminalFileLink, 'line' | 'co
|
||||
|
||||
// Matches a path with at least one `/` separator, optionally followed by
|
||||
// `:line` and `:col` suffixes (e.g. `src/foo.ts:12:3`, `./bin`, `/abs/path`).
|
||||
const LOCAL_PATH_REGEX = /(?:\/|\.{1,2}\/|[A-Za-z0-9._-]+\/)[A-Za-z0-9._~\-/]*(?::\d+)?(?::\d+)?/g
|
||||
const LOCAL_PATH_REGEX =
|
||||
/(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])[A-Za-z0-9._~\-/%+@\\]*(?::\d+)?(?::\d+)?/g
|
||||
|
||||
// Matches separator paths whose file or folder names include spaces. This runs
|
||||
// before LOCAL_PATH_REGEX so `/Users/A/Foo Bar/file.ts` is claimed as one link
|
||||
// instead of split into `/Users/A/Foo` and `Bar/file.ts`.
|
||||
const SPACED_PATH_WITH_SEPARATOR_REGEX =
|
||||
/(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])(?=[^()[\]{}'",;<>|`\r\n]*\s+[^()[\]{}'",;<>|`\r\n]*[\\/])[^()[\]{}'",;<>|`\r\n]+(?::\d+)?(?::\d+)?/g
|
||||
const SPACED_PATH_WITH_EXTENSION_REGEX =
|
||||
/(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])[^()[\]{}'",;<>|`\r\n]*?\s+[^()[\]{}'",;<>|`\\/ \r\n]*\.[A-Za-z0-9_+-]+(?::\d+)?(?::\d+)?/g
|
||||
const LINE_ENDING_SPACED_PATH_REGEX =
|
||||
/(?:~[\\/]|[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/]|[A-Za-z0-9._-]+[\\/])(?=[^()[\]{}'",;<>|`\r\n]*\s+)[^()[\]{}'",;<>|`\r\n]*\S(?=\s*$)/g
|
||||
const SPACED_LOCAL_PATH_REGEXES = [
|
||||
SPACED_PATH_WITH_SEPARATOR_REGEX,
|
||||
SPACED_PATH_WITH_EXTENSION_REGEX,
|
||||
LINE_ENDING_SPACED_PATH_REGEX
|
||||
]
|
||||
|
||||
// Word separators used by the bare-filename pass. Mirrors the default set in
|
||||
// VSCode's `terminal.integrated.wordSeparators` with the exception that we
|
||||
@@ -79,97 +102,6 @@ function parsePathWithOptionalLineColumn(value: string): {
|
||||
return { pathText, line, column }
|
||||
}
|
||||
|
||||
type NormalizedAbsolutePath = {
|
||||
normalized: string
|
||||
comparisonKey: string
|
||||
rootKind: 'posix' | 'windows' | 'unc'
|
||||
}
|
||||
|
||||
function normalizeSegments(pathValue: string): string[] {
|
||||
const segments = pathValue.split(/[\\/]+/)
|
||||
const stack: string[] = []
|
||||
for (const segment of segments) {
|
||||
if (!segment || segment === '.') {
|
||||
continue
|
||||
}
|
||||
if (segment === '..') {
|
||||
if (stack.length > 0) {
|
||||
stack.pop()
|
||||
}
|
||||
continue
|
||||
}
|
||||
stack.push(segment)
|
||||
}
|
||||
|
||||
return stack
|
||||
}
|
||||
|
||||
function normalizeAbsolutePath(pathValue: string): NormalizedAbsolutePath | null {
|
||||
const windowsDriveMatch = /^([A-Za-z]):[\\/]*(.*)$/.exec(pathValue)
|
||||
if (windowsDriveMatch) {
|
||||
const driveLetter = windowsDriveMatch[1].toUpperCase()
|
||||
const suffix = normalizeSegments(windowsDriveMatch[2]).join('/')
|
||||
const normalized = suffix ? `${driveLetter}:/${suffix}` : `${driveLetter}:/`
|
||||
return {
|
||||
normalized,
|
||||
comparisonKey: normalized.toLowerCase(),
|
||||
rootKind: 'windows'
|
||||
}
|
||||
}
|
||||
|
||||
const uncMatch = /^\\\\([^\\/]+)[\\/]+([^\\/]+)(?:[\\/]*(.*))?$/.exec(pathValue)
|
||||
if (uncMatch) {
|
||||
const server = uncMatch[1]
|
||||
const share = uncMatch[2]
|
||||
const suffix = normalizeSegments(uncMatch[3] ?? '').join('/')
|
||||
const normalizedRoot = `//${server}/${share}`
|
||||
const normalized = suffix ? `${normalizedRoot}/${suffix}` : normalizedRoot
|
||||
return {
|
||||
normalized,
|
||||
comparisonKey: normalized.toLowerCase(),
|
||||
rootKind: 'unc'
|
||||
}
|
||||
}
|
||||
|
||||
if (pathValue.startsWith('/')) {
|
||||
const normalized = `/${normalizeSegments(pathValue).join('/')}`.replace(/\/+$/, '') || '/'
|
||||
return {
|
||||
normalized,
|
||||
comparisonKey: normalized,
|
||||
rootKind: 'posix'
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function joinAbsolutePath(basePath: string, relativePath: string): string | null {
|
||||
const normalizedBase = normalizeAbsolutePath(basePath)
|
||||
if (!normalizedBase) {
|
||||
return null
|
||||
}
|
||||
|
||||
return normalizeJoinedPath(normalizedBase, relativePath)
|
||||
}
|
||||
|
||||
function normalizeJoinedPath(basePath: NormalizedAbsolutePath, relativePath: string): string {
|
||||
const normalizedBaseSegments = normalizeSegments(basePath.normalized)
|
||||
const relativeSegments = normalizeSegments(relativePath)
|
||||
const joinedSegments = [...normalizedBaseSegments, ...relativeSegments]
|
||||
|
||||
if (basePath.rootKind === 'unc') {
|
||||
const [server, share, ...rest] = joinedSegments
|
||||
return rest.length > 0 ? `//${server}/${share}/${rest.join('/')}` : `//${server}/${share}`
|
||||
}
|
||||
|
||||
if (basePath.rootKind === 'windows') {
|
||||
const [drive, ...rest] = joinedSegments
|
||||
return rest.length > 0 ? `${drive}/${rest.join('/')}` : drive
|
||||
}
|
||||
|
||||
return `/${joinedSegments.join('/')}`.replace(/\/+$/, '') || '/'
|
||||
}
|
||||
|
||||
// Project files that look like filenames despite having no extension. The
|
||||
// word detector otherwise requires a `.` in the token to keep noise down —
|
||||
// without this list, `ls` output containing `Makefile` or `LICENSE` would
|
||||
@@ -235,6 +167,42 @@ function isInsideUriScheme(lineText: string, range: DetectedRange): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
function rangesOverlap(range: DetectedRange, claimedRanges: readonly [number, number][]): boolean {
|
||||
return claimedRanges.some(([start, end]) => range.startIndex < end && range.endIndex > start)
|
||||
}
|
||||
|
||||
function trimSpacedPathTrailingProse(range: DetectedRange): DetectedRange {
|
||||
const filenameBeforeProseMatch = /^(.+\.[A-Za-z0-9_+-]+(?::\d+)?(?::\d+)?)(?:\s+.+)$/.exec(
|
||||
range.text
|
||||
)
|
||||
if (!filenameBeforeProseMatch) {
|
||||
return range
|
||||
}
|
||||
|
||||
const text = filenameBeforeProseMatch[1]
|
||||
return {
|
||||
text,
|
||||
startIndex: range.startIndex,
|
||||
endIndex: range.startIndex + text.length
|
||||
}
|
||||
}
|
||||
|
||||
function buildLineEndingSpacedPathPrefixRanges(range: DetectedRange): DetectedRange[] {
|
||||
const ranges: DetectedRange[] = []
|
||||
for (const match of range.text.matchAll(/\s+/g)) {
|
||||
const endIndex = match.index ?? 0
|
||||
const text = range.text.slice(0, endIndex).trimEnd()
|
||||
if (text.includes(' ')) {
|
||||
ranges.push({
|
||||
text,
|
||||
startIndex: range.startIndex,
|
||||
endIndex: range.startIndex + text.length
|
||||
})
|
||||
}
|
||||
}
|
||||
return ranges.reverse()
|
||||
}
|
||||
|
||||
function toParsedLink(range: DetectedRange): ParsedTerminalFileLink | null {
|
||||
const parsed = parsePathWithOptionalLineColumn(range.text)
|
||||
if (!parsed) {
|
||||
@@ -250,16 +218,32 @@ function toParsedLink(range: DetectedRange): ParsedTerminalFileLink | null {
|
||||
}
|
||||
}
|
||||
|
||||
function sortLinksByPosition(links: ParsedTerminalFileLink[]): ParsedTerminalFileLink[] {
|
||||
return links.sort((a, b) => a.startIndex - b.startIndex || b.endIndex - a.endIndex)
|
||||
}
|
||||
|
||||
// Ported from VSCode's TerminalLocalLinkDetector. Extracts anything that
|
||||
// contains a path separator, optionally with a `:line:col` suffix — covers
|
||||
// `./src/foo.ts`, `/abs/bar`, `src/foo.ts:12:3`, etc.
|
||||
function detectLocalPathLinks(lineText: string): ParsedTerminalFileLink[] {
|
||||
function detectLocalPathLinks(
|
||||
lineText: string,
|
||||
includeLineEndingPrefixCandidates = false
|
||||
): ParsedTerminalFileLink[] {
|
||||
const links: ParsedTerminalFileLink[] = []
|
||||
const spacedLinks = detectSpacedLocalPathLinks(lineText, includeLineEndingPrefixCandidates)
|
||||
const spacedRanges = spacedLinks.map(({ startIndex, endIndex }): [number, number] => [
|
||||
startIndex,
|
||||
endIndex
|
||||
])
|
||||
links.push(...spacedLinks)
|
||||
for (const range of detectRanges(lineText, LOCAL_PATH_REGEX)) {
|
||||
if (rangesOverlap(range, spacedRanges)) {
|
||||
continue
|
||||
}
|
||||
if (isInsideUriScheme(lineText, range)) {
|
||||
continue
|
||||
}
|
||||
if (!range.text.includes('/')) {
|
||||
if (!/[\\/]/.test(range.text)) {
|
||||
continue
|
||||
}
|
||||
const link = toParsedLink(range)
|
||||
@@ -267,6 +251,34 @@ function detectLocalPathLinks(lineText: string): ParsedTerminalFileLink[] {
|
||||
links.push(link)
|
||||
}
|
||||
}
|
||||
return sortLinksByPosition(links)
|
||||
}
|
||||
|
||||
function detectSpacedLocalPathLinks(
|
||||
lineText: string,
|
||||
includeLineEndingPrefixCandidates = false
|
||||
): ParsedTerminalFileLink[] {
|
||||
const links: ParsedTerminalFileLink[] = []
|
||||
const claimedRanges: [number, number][] = []
|
||||
for (const regex of SPACED_LOCAL_PATH_REGEXES) {
|
||||
for (const range of detectRanges(lineText, regex)) {
|
||||
if (rangesOverlap(range, claimedRanges) || isInsideUriScheme(lineText, range)) {
|
||||
continue
|
||||
}
|
||||
const candidateRanges =
|
||||
includeLineEndingPrefixCandidates && regex === LINE_ENDING_SPACED_PATH_REGEX
|
||||
? [range, ...buildLineEndingSpacedPathPrefixRanges(range)]
|
||||
: [range]
|
||||
const candidateLinks = candidateRanges
|
||||
.map((candidateRange) => toParsedLink(trimSpacedPathTrailingProse(candidateRange)))
|
||||
.filter((link): link is ParsedTerminalFileLink => link !== null)
|
||||
const link = candidateLinks[0]
|
||||
if (link) {
|
||||
links.push(...candidateLinks)
|
||||
claimedRanges.push([link.startIndex, link.endIndex])
|
||||
}
|
||||
}
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
@@ -308,12 +320,24 @@ export function extractTerminalFileLinks(lineText: string): ParsedTerminalFileLi
|
||||
return [...pathLinks, ...wordLinks]
|
||||
}
|
||||
|
||||
export function extractTerminalFileLinkCandidates(lineText: string): ParsedTerminalFileLink[] {
|
||||
const pathLinks = detectLocalPathLinks(lineText, true)
|
||||
const claimed = pathLinks.map(({ startIndex, endIndex }): [number, number] => [
|
||||
startIndex,
|
||||
endIndex
|
||||
])
|
||||
const wordLinks = detectBareFilenameLinks(lineText, claimed)
|
||||
return [...pathLinks, ...wordLinks]
|
||||
}
|
||||
|
||||
export function resolveTerminalFileLink(
|
||||
parsed: ParsedTerminalFileLink,
|
||||
cwd: string
|
||||
cwd: string,
|
||||
homePath?: string | null
|
||||
): ResolvedTerminalFileLink | null {
|
||||
const absolutePath =
|
||||
normalizeAbsolutePath(parsed.pathText)?.normalized ?? joinAbsolutePath(cwd, parsed.pathText)
|
||||
const absolutePath = /^~[\\/]/.test(parsed.pathText)
|
||||
? resolveTildePath(parsed.pathText, cwd, homePath)
|
||||
: (normalizeAbsolutePath(parsed.pathText)?.normalized ?? joinAbsolutePath(cwd, parsed.pathText))
|
||||
if (!absolutePath) {
|
||||
return null
|
||||
}
|
||||
@@ -327,11 +351,12 @@ export function resolveTerminalFileLink(
|
||||
|
||||
export function resolveTerminalFileLinkText(
|
||||
linkText: string,
|
||||
cwd: string
|
||||
cwd: string,
|
||||
homePath?: string | null
|
||||
): ResolvedTerminalFileLink | null {
|
||||
const links = extractTerminalFileLinks(linkText)
|
||||
const exactLink = links.find((link) => link.startIndex === 0 && link.endIndex === linkText.length)
|
||||
return exactLink ? resolveTerminalFileLink(exactLink, cwd) : null
|
||||
return exactLink ? resolveTerminalFileLink(exactLink, cwd, homePath) : null
|
||||
}
|
||||
|
||||
export function isPathInsideWorktree(filePath: string, worktreePath: string): boolean {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
type NormalizedAbsolutePath = {
|
||||
normalized: string
|
||||
comparisonKey: string
|
||||
rootKind: 'posix' | 'windows' | 'unc'
|
||||
}
|
||||
|
||||
function normalizeSegments(pathValue: string): string[] {
|
||||
const segments = pathValue.split(/[\\/]+/)
|
||||
const stack: string[] = []
|
||||
for (const segment of segments) {
|
||||
if (!segment || segment === '.') {
|
||||
continue
|
||||
}
|
||||
if (segment === '..') {
|
||||
if (stack.length > 0) {
|
||||
stack.pop()
|
||||
}
|
||||
continue
|
||||
}
|
||||
stack.push(segment)
|
||||
}
|
||||
|
||||
return stack
|
||||
}
|
||||
|
||||
export function normalizeAbsolutePath(pathValue: string): NormalizedAbsolutePath | null {
|
||||
const windowsDriveMatch = /^([A-Za-z]):[\\/]*(.*)$/.exec(pathValue)
|
||||
if (windowsDriveMatch) {
|
||||
const driveLetter = windowsDriveMatch[1].toUpperCase()
|
||||
const suffix = normalizeSegments(windowsDriveMatch[2]).join('/')
|
||||
const normalized = suffix ? `${driveLetter}:/${suffix}` : `${driveLetter}:/`
|
||||
return {
|
||||
normalized,
|
||||
comparisonKey: normalized.toLowerCase(),
|
||||
rootKind: 'windows'
|
||||
}
|
||||
}
|
||||
|
||||
const uncMatch = /^\\\\([^\\/]+)[\\/]+([^\\/]+)(?:[\\/]*(.*))?$/.exec(pathValue)
|
||||
if (uncMatch) {
|
||||
const server = uncMatch[1]
|
||||
const share = uncMatch[2]
|
||||
const suffix = normalizeSegments(uncMatch[3] ?? '').join('/')
|
||||
const normalizedRoot = `//${server}/${share}`
|
||||
const normalized = suffix ? `${normalizedRoot}/${suffix}` : normalizedRoot
|
||||
return {
|
||||
normalized,
|
||||
comparisonKey: normalized.toLowerCase(),
|
||||
rootKind: 'unc'
|
||||
}
|
||||
}
|
||||
|
||||
if (pathValue.startsWith('/')) {
|
||||
const normalized = `/${normalizeSegments(pathValue).join('/')}`.replace(/\/+$/, '') || '/'
|
||||
return {
|
||||
normalized,
|
||||
comparisonKey: normalized,
|
||||
rootKind: 'posix'
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function inferHomePathFromCwd(cwd: string): string | null {
|
||||
const normalizedCwd = normalizeAbsolutePath(cwd)
|
||||
if (!normalizedCwd) {
|
||||
return null
|
||||
}
|
||||
|
||||
const segments = normalizeSegments(normalizedCwd.normalized)
|
||||
if (normalizedCwd.rootKind === 'windows') {
|
||||
const [drive, usersSegment, userSegment] = segments
|
||||
if (!drive || !usersSegment || !userSegment || usersSegment.toLowerCase() !== 'users') {
|
||||
return null
|
||||
}
|
||||
return `${drive}/${usersSegment}/${userSegment}`
|
||||
}
|
||||
|
||||
if (normalizedCwd.rootKind === 'posix') {
|
||||
const [rootParent, userSegment] = segments
|
||||
if ((rootParent === 'Users' || rootParent === 'home') && userSegment) {
|
||||
return `/${rootParent}/${userSegment}`
|
||||
}
|
||||
if (rootParent === 'root') {
|
||||
return '/root'
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function normalizeExplicitHomePath(homePath: string | null | undefined): string | null {
|
||||
const trimmedHomePath = homePath?.trim()
|
||||
if (!trimmedHomePath) {
|
||||
return null
|
||||
}
|
||||
|
||||
return normalizeAbsolutePath(trimmedHomePath)?.normalized ?? null
|
||||
}
|
||||
|
||||
export function resolveTildePath(
|
||||
pathValue: string,
|
||||
cwd: string,
|
||||
homePath?: string | null
|
||||
): string | null {
|
||||
if (!/^~[\\/]/.test(pathValue)) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Why: remote/devcontainer terminals can have cwd outside the user's home;
|
||||
// prefer the terminal's explicit home when the caller has it.
|
||||
const resolvedHomePath = normalizeExplicitHomePath(homePath) ?? inferHomePathFromCwd(cwd)
|
||||
if (!resolvedHomePath) {
|
||||
return null
|
||||
}
|
||||
|
||||
return joinAbsolutePath(resolvedHomePath, pathValue.slice(2))
|
||||
}
|
||||
|
||||
export function joinAbsolutePath(basePath: string, relativePath: string): string | null {
|
||||
const normalizedBase = normalizeAbsolutePath(basePath)
|
||||
if (!normalizedBase) {
|
||||
return null
|
||||
}
|
||||
|
||||
return normalizeJoinedPath(normalizedBase, relativePath)
|
||||
}
|
||||
|
||||
function normalizeJoinedPath(basePath: NormalizedAbsolutePath, relativePath: string): string {
|
||||
const normalizedBaseSegments = normalizeSegments(basePath.normalized)
|
||||
const relativeSegments = normalizeSegments(relativePath)
|
||||
const joinedSegments = [...normalizedBaseSegments, ...relativeSegments]
|
||||
|
||||
if (basePath.rootKind === 'unc') {
|
||||
const [server, share, ...rest] = joinedSegments
|
||||
return rest.length > 0 ? `//${server}/${share}/${rest.join('/')}` : `//${server}/${share}`
|
||||
}
|
||||
|
||||
if (basePath.rootKind === 'windows') {
|
||||
const [drive, ...rest] = joinedSegments
|
||||
return rest.length > 0 ? `${drive}/${rest.join('/')}` : drive
|
||||
}
|
||||
|
||||
return `/${joinedSegments.join('/')}`.replace(/\/+$/, '') || '/'
|
||||
}
|
||||
Reference in New Issue
Block a user