-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatPathUtils.ts
More file actions
55 lines (50 loc) · 2.02 KB
/
Copy pathchatPathUtils.ts
File metadata and controls
55 lines (50 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import type { ProjectLocation } from "@/shared/contracts";
/** Normalize model / markdown paths to a project-relative POSIX path for the file editor. */
export function normalizeChatRelativePath(raw: string): string {
return normalizeChatPath(raw, { preserveAbsolute: false });
}
function normalizeChatPath(raw: string, options: { preserveAbsolute: boolean }): string {
let s = raw.trim();
if (!s) return s;
if (s.startsWith("file://")) {
try {
const u = new URL(s);
s = u.pathname;
if (s.startsWith("/") && /^\/[A-Za-z]:/.test(s)) s = s.slice(1);
else if (!options.preserveAbsolute) s = s.replace(/^\//, "");
} catch {
/* keep */
}
}
s = s.replace(/^\.\//, "").replace(/\\/g, "/");
const collapsed = s.replace(/\/+/g, "/");
return options.preserveAbsolute ? collapsed : collapsed.replace(/^\/+/, "");
}
export function normalizeChatProjectPath(raw: string, projectLocation: ProjectLocation): string {
const normalized = normalizeChatPath(raw, { preserveAbsolute: true });
const projectRoots = getProjectRoots(projectLocation).map((root) =>
normalizeChatPath(root, { preserveAbsolute: true }),
);
const root = projectRoots.find((candidate) => pathStartsWithRoot(normalized, candidate));
if (!root) return normalized;
return normalized.slice(root.length).replace(/^\/+/, "");
}
function getProjectRoots(projectLocation: ProjectLocation): string[] {
switch (projectLocation.kind) {
case "windows":
return [projectLocation.path];
case "wsl":
return [projectLocation.linuxPath, projectLocation.uncPath];
case "ssh":
case "posix":
return [projectLocation.path];
}
}
function pathStartsWithRoot(path: string, root: string): boolean {
const normalizedRoot = root.replace(/\/+$/, "");
if (!normalizedRoot) return false;
const lcPath = path.toLowerCase();
const lcRoot = normalizedRoot.toLowerCase();
if (path.length === normalizedRoot.length) return lcPath === lcRoot;
return lcPath.startsWith(`${lcRoot}/`) || path.startsWith(`${normalizedRoot}/`);
}