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
18export function isWindowsAbsolutePath(value: string): boolean {
19 return isUncPath(value) || isWindowsDrivePath(value);
20}
21
22export function isExplicitRelativePath(value: string): boolean {
23 return (
24 value === "." ||
25 value === ".." ||
26 value.startsWith("./") ||
27 value.startsWith("../") ||
28 value.startsWith(".\\") ||
29 value.startsWith("..\\")
30 );
31}
32
33function isRootPath(value: string): boolean {
34 // Bare C: means the current directory on C, not its root; require the drive separator.
35 return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]$/.test(value);
36}
37
38function trimTrailingPathSeparators(value: string): string {
39 if (value.length === 0 || isRootPath(value)) {
40 return value;
41 }
42 const trimmed = value.startsWith("/")
43 ? value.replace(/\/+$/g, "")
44 : value.replace(/[\\/]+$/g, "");
45 if (trimmed.length === 0) {
46 return value;
47 }
48 return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
49}
50
51export function normalizeProjectPathForDispatch(value: string): string {
52 return trimTrailingPathSeparators(value.trim());
53}
54
55export function normalizeProjectPathForComparison(value: string): string {
56 const normalized = normalizeProjectPathForDispatch(value);
57 if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {
58 return normalized.replaceAll("/", "\\").toLowerCase();
59 }
60 return normalized;
61}
62
63// Windows refuses these as file names, with or without an extension.
64const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
65
66/** Folds accented Latin letters to ASCII ("tìm" -> "tim"); other scripts pass through. */
67export function foldLatinDiacritics(text: string): string {
68 return text
69 .normalize("NFKD")
70 .replace(/[\u0300-\u036f]/g, "")
71 .replace(/đ/g, "d") // d-with-stroke and sharp s have no Unicode decomposition
72 .replace(/Đ/g, "D")
73 .replace(/ß/g, "ss")
74 .replace(/ẞ/g, "SS");
75}
76
77export function newProjectFolderName(name: string): string {
78 const slug = foldLatinDiacritics(name)
79 .toLowerCase()
80 .replace(/[^a-z0-9]+/g, "-")
81 .replace(/^-+/, "")
82 .slice(0, 64)
83 .replace(/-+$/, "");
84 if (slug.length === 0) return "project";
85 return WINDOWS_RESERVED_NAME.test(slug) ? `${slug}-project` : slug;
86}
87
88const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
89
90/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
91export function stripSlashPrefixedWindowsDrive(path: string): string {
92 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
93}
94
95export function fileBasename(path: string): string {
96 const trimmed = path.replace(/[/\\]+$/, "");
97 if (trimmed.length === 0) return path;
98 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
99 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
100}
101
102export function workspaceRelativeFilePath(
103 path: string,
104 workspaceRoot: string | null | undefined,
105): string | null {
106 if (!workspaceRoot) return null;
107 const caseInsensitive =
108 isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) ||
109 (isNetworkPath(workspaceRoot) && isUncPath(path));
110 const normalizedPath = caseInsensitive
111 ? stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"))
112 : path;
113 const normalizedRoot = (
114 caseInsensitive
115 ? stripSlashPrefixedWindowsDrive(workspaceRoot.replaceAll("\\", "/"))
116 : workspaceRoot
117 ).replace(/\/+$/, "");
118 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
119 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
120 if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";
121 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
122 const relativePath = normalizedPath.slice(normalizedRoot.length + 1);
123 // `/repo/../x` starts with the root but escapes it; the server rejects that as a workspace path.
124 let depth = 0;
125 for (const segment of relativePath.split("/")) {
126 if (segment === "..") depth -= 1;
127 else if (segment.length > 0 && segment !== ".") depth += 1;
128 if (depth < 0) return null;
129 }
130 return relativePath;
131}
132
133export function isAbsolutePath(value: string): boolean {
134 return value.startsWith("/") || isWindowsAbsolutePath(value);
135}
136
137/** Home-relative host paths are expanded by the destination server. */
138export function isHostPath(value: string): boolean {
139 return isAbsolutePath(value) || value.startsWith("~/");
140}
141
142// Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`.
143const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/;
144const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g;
145
146/**
147 * What a folder box holds after a change. A full path pasted into it replaces the box, even after
148 * the text already there, because `~/'/a b'` would create that nested folder.
149 */
150export function resolvePastedPath(previous: string, next: string): string {
151 const isTyping = next.startsWith(previous)
152 ? next.length === previous.length + 1
153 : previous.startsWith(next);
154 if (isTyping) return next;
155
156 const match = QUOTED_PATH_AT_END.exec(next);
157 // Text before the quote that wasn't in the box is a search, not a folder to paste after.
158 if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) {
159 const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? "";
160 if (isHostPath(quoted)) return quoted;
161 }
162
163 // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder.
164 const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous);
165 const path = afterFolder ? next.slice(previous.length) : next;
166 if (!isHostPath(path)) return next;
167 // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths.
168 return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1");
169}
170
171export function resolveWorkspaceFilePath(path: string, workspaceRoot: string): string {
172 if (isAbsolutePath(path) || path.startsWith("~/") || path.startsWith("~\\")) return path;
173 const base = workspaceRoot.replace(/[/\\]+$/, "");
174 return isWindowsAbsolutePath(workspaceRoot)
175 ? `${base}\\${path.replaceAll("/", "\\")}`
176 : `${base}/${path}`;
177}