Open History to see the last commit
1export function isWindowsDrivePath(value: string): boolean {
2 return /^[a-zA-Z]:([/\\]|$)/.test(value);
3}
4
5export function isUncPath(value: string): boolean {
6 return value.startsWith("\\\\");
7}
8
9/**
10 * Windows treats `/` and `\` alike, so any two leading separators name a UNC
11 * or device path. Touching one makes Windows sign in to that host with the
12 * user's NTLM credentials, so agent-authored paths must not reach one.
13 */
14export function isNetworkPath(value: string): boolean {
15 return /^[\\/]{2}/.test(value);
16}
17
18/** A `\\wsl.localhost\<distro>` or `\\wsl$\<distro>` share: a WSL distro's files seen from Windows over 9P. */
19export function isWslSharePath(value: string): boolean {
20 return /^[\\/]{2}(?:[?.][\\/]UNC[\\/])?wsl(?:\.localhost|\$)[\\/]/i.test(value.trim());
21}
22
23export function isWindowsAbsolutePath(value: string): boolean {
24 return isUncPath(value) || isWindowsDrivePath(value);
25}
26
27export function isExplicitRelativePath(value: string): boolean {
28 return (
29 value === "." ||
30 value === ".." ||
31 value.startsWith("./") ||
32 value.startsWith("../") ||
33 value.startsWith(".\\") ||
34 value.startsWith("..\\")
35 );
36}
37
38function isRootPath(value: string): boolean {
39 // Bare C: means the current directory on C, not its root; require the drive separator.
40 return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]$/.test(value);
41}
42
43function trimTrailingPathSeparators(value: string): string {
44 if (value.length === 0 || isRootPath(value)) {
45 return value;
46 }
47 const trimmed = value.startsWith("/")
48 ? value.replace(/\/+$/g, "")
49 : value.replace(/[\\/]+$/g, "");
50 if (trimmed.length === 0) {
51 return value;
52 }
53 return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
54}
55
56export function normalizeProjectPathForDispatch(value: string): string {
57 return trimTrailingPathSeparators(value.trim());
58}
59
60export function normalizeProjectPathForComparison(value: string): string {
61 const normalized = normalizeProjectPathForDispatch(value);
62 if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {
63 return normalized.replaceAll("/", "\\").toLowerCase();
64 }
65 return normalized;
66}
67
68// Windows refuses these as file names, with or without an extension.
69const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
70
71// Latin letters NFKD leaves whole (ł, ø, ß) or splits with a spacing mark (Ŀ, ʼn).
72const LATIN_FOLDS: Record<string, string> = {
73 Ŀ: "L",
74 ŀ: "l",
75 ʼn: "n",
76 Đ: "D",
77 đ: "d",
78 Ð: "D",
79 ð: "d",
80 ß: "ss",
81 ẞ: "SS",
82 Ł: "L",
83 ł: "l",
84 Ø: "O",
85 ø: "o",
86 Æ: "AE",
87 æ: "ae",
88 Œ: "OE",
89 œ: "oe",
90 Þ: "TH",
91 þ: "th",
92 Ħ: "H",
93 ħ: "h",
94 ı: "i",
95 ĸ: "q",
96 Ŋ: "N",
97 ŋ: "n",
98 Ŧ: "T",
99 ŧ: "t",
100};
101const LATIN_FOLD_PATTERN = new RegExp(`[${Object.keys(LATIN_FOLDS).join("")}]`, "g");
102
103/** Folds accented Latin letters to ASCII ("tìm" -> "tim"); other scripts pass through. */
104export function foldLatinDiacritics(text: string): string {
105 return text
106 .replace(LATIN_FOLD_PATTERN, (letter) => LATIN_FOLDS[letter] ?? letter)
107 .normalize("NFKD")
108 .replace(/[\u0300-\u036f]/g, "");
109}
110
111export function newProjectFolderName(name: string): string {
112 const slug = foldLatinDiacritics(name)
113 .toLowerCase()
114 .replace(/[^a-z0-9]+/g, "-")
115 .replace(/^-+/, "")
116 .slice(0, 64)
117 .replace(/-+$/, "");
118 if (slug.length === 0) return "project";
119 return WINDOWS_RESERVED_NAME.test(slug) ? `${slug}-project` : slug;
120}
121
122const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
123
124/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
125export function stripSlashPrefixedWindowsDrive(path: string): string {
126 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
127}
128
129export function fileBasename(path: string): string {
130 const trimmed = path.replace(/[/\\]+$/, "");
131 if (trimmed.length === 0) return path;
132 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
133 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
134}
135
136/** A path's last segment composed to NFC for display: macOS stores many names in NFD. */
137export function fileDisplayName(path: string): string {
138 return fileBasename(path).normalize("NFC");
139}
140
141export function workspaceRelativeFilePath(
142 path: string,
143 workspaceRoot: string | null | undefined,
144): string | null {
145 if (!workspaceRoot) return null;
146 const caseInsensitive =
147 isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) ||
148 (isNetworkPath(workspaceRoot) && isUncPath(path));
149 const normalizedPath = caseInsensitive
150 ? stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"))
151 : path;
152 const normalizedRoot = (
153 caseInsensitive
154 ? stripSlashPrefixedWindowsDrive(workspaceRoot.replaceAll("\\", "/"))
155 : workspaceRoot
156 ).replace(/\/+$/, "");
157 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
158 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
159 if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";
160 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
161 const relativePath = normalizedPath.slice(normalizedRoot.length + 1);
162 // `/repo/../x` starts with the root but escapes it; the server rejects that as a workspace path.
163 let depth = 0;
164 for (const segment of relativePath.split("/")) {
165 if (segment === "..") depth -= 1;
166 else if (segment.length > 0 && segment !== ".") depth += 1;
167 if (depth < 0) return null;
168 }
169 return relativePath;
170}
171
172export function isAbsolutePath(value: string): boolean {
173 return value.startsWith("/") || isWindowsAbsolutePath(value);
174}
175
176/** Both ~/ and ~\ home prefixes are expanded by the destination server. */
177export function isHostPath(value: string): boolean {
178 return isAbsolutePath(value) || value.startsWith("~/") || value.startsWith("~\\");
179}
180
181// Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`.
182const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/;
183const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g;
184
185// Folder browsers only navigate `~/` home paths, so a pasted `~\` path is not a replacement.
186function isPastedFolderPath(value: string): boolean {
187 return isAbsolutePath(value) || value.startsWith("~/");
188}
189
190/**
191 * What a folder box holds after a change. A full path pasted into it replaces the box, even after
192 * the text already there, because `~/'/a b'` would create that nested folder.
193 */
194export function resolvePastedPath(previous: string, next: string): string {
195 const isTyping = next.startsWith(previous)
196 ? next.length === previous.length + 1
197 : previous.startsWith(next);
198 if (isTyping) return next;
199
200 const match = QUOTED_PATH_AT_END.exec(next);
201 // Text before the quote that wasn't in the box is a search, not a folder to paste after.
202 if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) {
203 const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? "";
204 if (isPastedFolderPath(quoted)) return quoted;
205 }
206
207 // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder.
208 const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous);
209 const path = afterFolder ? next.slice(previous.length) : next;
210 if (!isPastedFolderPath(path)) return next;
211 // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths.
212 return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1");
213}
214
215export function resolveWorkspaceFilePath(path: string, workspaceRoot: string): string {
216 if (isAbsolutePath(path) || path.startsWith("~/") || path.startsWith("~\\")) return path;
217 const base = workspaceRoot.replace(/[/\\]+$/, "");
218 return isWindowsAbsolutePath(workspaceRoot)
219 ? `${base}\\${path.replaceAll("/", "\\")}`
220 : `${base}/${path}`;
221}