Open History to see the last commit
1export interface WslDistro {
2 readonly name: string;
3 readonly isDefault: boolean;
4 readonly version: 1 | 2;
5}
6
7export interface WslConfig {
8 readonly distro: string | null;
9}
10
11// Literal space — \s would also match \n/\t/\r and corrupt UNC paths like \\wsl.localhost\<distro>\...
12// Trailing char must also be \w so hand-edited config like "Ubuntu " / "Ubuntu-" / "Ubuntu." rejects.
13export const DISTRO_NAME_PATTERN = /^\w(?:[\w \-.]*\w)?$/;
14
15export function parseWslDistroList(stdout: Buffer): readonly WslDistro[] {
16 const hasUtf16Bom = stdout.length >= 2 && stdout[0] === 0xff && stdout[1] === 0xfe;
17 const likelyUtf16Le =
18 hasUtf16Bom ||
19 Array.from(stdout.subarray(0, Math.min(stdout.length, 80))).filter(
20 (byte, index) => index % 2 === 1 && byte === 0,
21 ).length > 10;
22 let text = stdout.toString(likelyUtf16Le ? "utf16le" : "utf8");
23 if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
24
25 const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
26 const distros: WslDistro[] = [];
27 for (let i = 1; i < lines.length; i++) {
28 const line = lines[i]!;
29 const isDefault = line.startsWith("*");
30 const cleaned = isDefault ? line.slice(1).trim() : line.trim();
31 const fields = cleaned.split(/\s{2,}/);
32 if (fields.length < 3) continue;
33 const name = fields[0]!.trim();
34 const versionNum = parseInt(fields[2]!, 10);
35 if (!name || (versionNum !== 1 && versionNum !== 2)) continue;
36 distros.push({ name, isDefault, version: versionNum as 1 | 2 });
37 }
38 return distros;
39}
40
41export interface WslUncPath {
42 readonly distro: string;
43 readonly linuxPath: string;
44}
45
46// Recognizes \\wsl.localhost\<distro>\... and the legacy \\wsl$\<distro>\...
47// while preserving the distro identity. Dropping that identity is unsafe: the
48// same Linux path can exist in multiple distros, so callers must validate the
49// selected distro against the concrete backend they are targeting before
50// returning only the Linux path.
51export function parseWslUncPath(windowsPath: string): WslUncPath | null {
52 const match = /^\\\\(?:wsl\.localhost|wsl\$)\\([^\\]+)(?:\\(.*))?$/i.exec(windowsPath);
53 if (!match) return null;
54
55 const distro = match[1]!;
56 if (!DISTRO_NAME_PATTERN.test(distro)) return null;
57
58 const rest = match[2] ?? "";
59 return {
60 distro,
61 linuxPath: rest.length === 0 ? "/" : `/${rest.split("\\").filter(Boolean).join("/")}`,
62 };
63}
64
65export function isSameWslDistro(left: string, right: string): boolean {
66 return left.toLowerCase() === right.toLowerCase();
67}
68
69export function resolveWslHomeUncPath(
70 config: WslConfig,
71 distros: readonly WslDistro[],
72): string | null {
73 const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
74 return distroName ? `\\\\wsl.localhost\\${distroName}\\home` : null;
75}
76
77export function resolveWslPickFolderDefaultPath(
78 rawOptions: unknown,
79 config: WslConfig,
80 distros: readonly WslDistro[],
81 // Absolute Linux path of the user's home dir inside the chosen distro
82 // (e.g. "/home/josh"). When known, `~` and `~/...` expand against this so
83 // we don't open the picker at a non-existent `/home/<rest>`. When null we
84 // fall back to the `/home` parent — wrong directory but at least it exists.
85 userHome: string | null = null,
86): string | null {
87 const homePath = resolveWslHomeUncPath(config, distros);
88 if (typeof rawOptions !== "object" || rawOptions === null) {
89 return homePath;
90 }
91
92 const { initialPath } = rawOptions as { initialPath?: unknown };
93 if (typeof initialPath !== "string") {
94 return homePath;
95 }
96
97 const trimmedPath = initialPath.trim();
98 if (trimmedPath.length === 0) {
99 return homePath;
100 }
101 const distroName = config.distro ?? distros.find((distro) => distro.isDefault)?.name ?? null;
102 if (!distroName) {
103 return homePath;
104 }
105
106 if (trimmedPath.startsWith("\\\\")) {
107 const parsed = parseWslUncPath(trimmedPath);
108 // Never seed a picker for one distro with a path owned by another distro.
109 // That makes it far too easy to select a valid-looking path that is later
110 // interpreted by the wrong Linux backend. Non-WSL UNC paths also fall back
111 // to the target distro's home rather than becoming an accidental default.
112 return parsed && isSameWslDistro(parsed.distro, distroName) ? trimmedPath : homePath;
113 }
114
115 const toUncPath = (linuxPath: string) =>
116 `\\\\wsl.localhost\\${distroName}${linuxPath.replaceAll("/", "\\")}`;
117
118 const normalizedUserHome = userHome && userHome.startsWith("/") ? userHome : null;
119
120 if (trimmedPath === "~") {
121 return normalizedUserHome ? toUncPath(normalizedUserHome) : homePath;
122 }
123 if (trimmedPath.startsWith("~/")) {
124 const remainder = trimmedPath.slice(2);
125 if (normalizedUserHome) {
126 return toUncPath(`${normalizedUserHome}/${remainder}`);
127 }
128 return homePath ? `${homePath}\\${remainder.replaceAll("/", "\\")}` : null;
129 }
130 if (trimmedPath.startsWith("/")) {
131 return toUncPath(trimmedPath);
132 }
133
134 return homePath;
135}
136
137export function isValidDistroName(value: string): boolean {
138 return DISTRO_NAME_PATTERN.test(value);
139}