Skip to content

Commit f38869e

Browse files
committed
Implement helper function for path escaping in mentions
- Added `escapePath` function to encapsulate multi-level escaping for backslashes and spaces in file paths. - Updated `convertToMentionPath` to utilize the new helper function, improving code clarity and consistency in path handling. - Ensured robust handling of paths with escaped characters across different scenarios.
1 parent bab59a1 commit f38869e

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

webview-ui/src/utils/path-mentions.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,16 @@
22
* Utilities for handling path-related operations in mentions
33
*/
44

5+
/**
6+
* Helper function to escape backslashes and spaces in a path.
7+
* This encapsulates the multi-level escaping strategy for file paths.
8+
* @param inputPath The path to escape
9+
* @returns The escaped path
10+
*/
11+
function escapePath(inputPath: string): string {
12+
return inputPath.replace(/\\/g, '\\\\').replace(/ /g, '\\ ');
13+
}
14+
515
/**
616
* Converts an absolute path to a mention-friendly path
717
* If the provided path starts with the current working directory,
@@ -13,12 +23,12 @@
1323
*/
1424
export function convertToMentionPath(path: string, cwd?: string): string {
1525
// First, handle Windows path separators and convert to forward slashes
16-
let processedPath = path.replace(/\\\\/g, "//").replace(/\\/g, "/");
17-
let normalizedCwd = cwd ? cwd.replace(/\\\\/g, "//").replace(/\\/g, "/") : "";
26+
let processedPath = path.replace(/\\\\\\/g, "//").replace(/\\/g, "/");
27+
let normalizedCwd = cwd ? cwd.replace(/\\\\\\/g, "//").replace(/\\/g, "/") : "";
1828

1929
if (!normalizedCwd) {
2030
// If no CWD, just escape spaces in the original path
21-
return processedPath.replace(/\\/g, '\\\\').replace(/ /g, '\\ ');
31+
return escapePath(processedPath);
2232
}
2333

2434
// Remove trailing slash from cwd if it exists
@@ -53,11 +63,11 @@ export function convertToMentionPath(path: string, cwd?: string): string {
5363
* will undergo a second round of escaping, resulting in double backslashes.
5464
* This is necessary to preserve the escapes through the entire text processing pipeline.
5565
*/
56-
// Escape backslashes first, then spaces (single backslash for space)
57-
return mentionPath.replace(/\\/g, '\\\\').replace(/ /g, '\\ ');
66+
// Use the helper function to escape the path
67+
return escapePath(mentionPath);
5868
}
5969

6070
// If path doesn't start with CWD, escape spaces in the processed path
61-
// Escape backslashes first, then spaces (single backslash for space)
62-
return processedPath.replace(/\\/g, '\\\\').replace(/ /g, '\\ ');
71+
// Use the helper function to escape the path
72+
return escapePath(processedPath);
6373
}

0 commit comments

Comments
 (0)