470 lines
16 KiB
TypeScript
470 lines
16 KiB
TypeScript
/// <reference types="node" />
|
|
import { execFile, execFileSync } from "node:child_process";
|
|
import { accessSync, constants, existsSync } from "node:fs";
|
|
import { access, mkdir, readdir, stat } from "node:fs/promises";
|
|
import { homedir } from "node:os";
|
|
import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
import { promisify } from "node:util";
|
|
import type { PickerSettings } from "../shared/settings";
|
|
import { PORTAL_PICK_SCRIPT } from "./portal-script";
|
|
|
|
const exec = promisify(execFile);
|
|
|
|
// Five minutes is enough for a person to browse to a folder. The picker is
|
|
// a window on the host, so nothing shorter is safe.
|
|
const PICK_TIMEOUT_MS = 5 * 60 * 1000;
|
|
|
|
export type PickResult =
|
|
| { status: "picked"; path: string; picker: string }
|
|
| { status: "cancelled"; picker: string }
|
|
| { status: "error"; message: string };
|
|
|
|
export interface PickerInfo {
|
|
id: string;
|
|
label: string;
|
|
available: boolean;
|
|
detail: string;
|
|
}
|
|
|
|
export interface DetectResult {
|
|
platform: string;
|
|
desktop: string | null;
|
|
pickers: PickerInfo[];
|
|
recommended: string | null;
|
|
}
|
|
|
|
function onPath(command: string): string | null {
|
|
if (command.includes("/")) {
|
|
try {
|
|
accessSync(command, constants.X_OK);
|
|
return command;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
|
|
if (!dir) continue;
|
|
const candidate = join(dir, command);
|
|
try {
|
|
accessSync(candidate, constants.X_OK);
|
|
return candidate;
|
|
} catch {
|
|
// Keep searching the PATH.
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// The plugin process inherits the daemon's environment, which normally
|
|
// carries the desktop session. When the session bus address is missing,
|
|
// fall back to the standard runtime socket so portal and KDE dialogs
|
|
// still reach the running desktop.
|
|
function buildEnv(): NodeJS.ProcessEnv {
|
|
const env: NodeJS.ProcessEnv = { ...process.env };
|
|
if (!env.DBUS_SESSION_BUS_ADDRESS) {
|
|
const runtimeDir = env.XDG_RUNTIME_DIR ?? `/run/user/${process.getuid?.() ?? ""}`;
|
|
const bus = join(runtimeDir, "bus");
|
|
if (existsSync(bus)) env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${bus}`;
|
|
}
|
|
return env;
|
|
}
|
|
|
|
export function detectPickers(): DetectResult {
|
|
const env = buildEnv();
|
|
const platform = process.platform;
|
|
const desktop = env.XDG_CURRENT_DESKTOP ?? null;
|
|
const pickers: PickerInfo[] = [];
|
|
|
|
if (platform === "linux" || platform === "freebsd") {
|
|
const hasDisplay = Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
|
|
for (const [id, label] of [
|
|
["kdialog", "KDE file dialog (kdialog)"],
|
|
["zenity", "GTK file dialog (zenity)"],
|
|
["yad", "GTK file dialog (yad)"],
|
|
] as const) {
|
|
const found = onPath(id);
|
|
const available = found !== null && hasDisplay;
|
|
pickers.push({
|
|
id,
|
|
label,
|
|
available,
|
|
detail: !found
|
|
? `Install ${id} on the host to use it.`
|
|
: !hasDisplay
|
|
? `${found} is installed, but no desktop display session is active.`
|
|
: found,
|
|
});
|
|
}
|
|
const python = onPath("python3");
|
|
const portalReady =
|
|
python !== null && Boolean(env.DBUS_SESSION_BUS_ADDRESS) && hasPortalSession(python, env);
|
|
pickers.push({
|
|
id: "portal",
|
|
label: "Desktop portal file browser",
|
|
available: portalReady,
|
|
detail: portalReady
|
|
? "Uses the XDG portal through python3 and PyGObject."
|
|
: "Needs python3 with PyGObject and an active XDG desktop portal session.",
|
|
});
|
|
} else if (platform === "darwin") {
|
|
pickers.push({
|
|
id: "osascript",
|
|
label: "macOS Finder folder dialog",
|
|
available: onPath("osascript") !== null,
|
|
detail: "Built into macOS.",
|
|
});
|
|
} else if (platform === "win32") {
|
|
pickers.push({
|
|
id: "powershell",
|
|
label: "Windows folder dialog",
|
|
available: onPath("powershell.exe") !== null || onPath("powershell") !== null,
|
|
detail: "Uses Windows PowerShell and FolderBrowserDialog.",
|
|
});
|
|
}
|
|
pickers.push({
|
|
id: "custom",
|
|
label: "Custom command",
|
|
available: true,
|
|
detail: "Any command that prints the chosen folder to stdout.",
|
|
});
|
|
|
|
const recommended = pickers.find((picker) => picker.available && picker.id !== "custom");
|
|
return { platform, desktop, pickers, recommended: recommended?.id ?? null };
|
|
}
|
|
|
|
export function resolvePicker(settings: PickerSettings, detected: DetectResult): string | { error: string } {
|
|
if (settings.picker === "custom") {
|
|
if (!settings.customCommand.trim()) {
|
|
return { error: "The picker is set to a custom command, but no command is saved in settings." };
|
|
}
|
|
return "custom";
|
|
}
|
|
if (settings.picker !== "auto") {
|
|
const info = detected.pickers.find((picker) => picker.id === settings.picker);
|
|
if (!info?.available) {
|
|
return {
|
|
error: `The ${settings.picker} picker is not available on this host. ${info?.detail ?? ""}`.trim(),
|
|
};
|
|
}
|
|
return settings.picker;
|
|
}
|
|
if (!detected.recommended) {
|
|
return {
|
|
error:
|
|
"No file browser picker was found on this host. Install kdialog (KDE) or zenity (GNOME), or python3 with PyGObject for the desktop portal, then try again.",
|
|
};
|
|
}
|
|
return detected.recommended;
|
|
}
|
|
|
|
let cachedPortalSession: boolean | null = null;
|
|
|
|
function hasPortalSession(pythonPath: string, env: NodeJS.ProcessEnv): boolean {
|
|
if (cachedPortalSession !== null) return cachedPortalSession;
|
|
try {
|
|
execFileSync(
|
|
pythonPath,
|
|
[
|
|
"-c",
|
|
"from gi.repository import Gio, GLib; bus = Gio.bus_get_sync(Gio.BusType.SESSION, None); res = bus.call_sync('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'NameHasOwner', GLib.Variant('(s)', ('org.freedesktop.portal.Desktop',)), GLib.VariantType('(b)'), Gio.DBusCallFlags.NONE, 1000, None); exit(0 if res.unpack()[0] else 1)",
|
|
],
|
|
{
|
|
env,
|
|
timeout: 2000,
|
|
stdio: "ignore",
|
|
},
|
|
);
|
|
cachedPortalSession = true;
|
|
} catch {
|
|
cachedPortalSession = false;
|
|
}
|
|
return cachedPortalSession;
|
|
}
|
|
|
|
interface RunResult {
|
|
stdout: string;
|
|
stderr: string;
|
|
code: number | null;
|
|
}
|
|
|
|
async function run(command: string, args: string[], shell = false): Promise<RunResult> {
|
|
try {
|
|
const { stdout, stderr } = await exec(command, args, {
|
|
env: buildEnv(),
|
|
timeout: PICK_TIMEOUT_MS,
|
|
maxBuffer: 1024 * 1024,
|
|
shell,
|
|
});
|
|
return { stdout, stderr, code: 0 };
|
|
} catch (error) {
|
|
const failure = error as { code?: number | string; stdout?: string; stderr?: string; message?: string; killed?: boolean };
|
|
if (failure.killed) {
|
|
throw new Error("The file browser was open for five minutes without a selection and was closed.");
|
|
}
|
|
if (failure.code === "ENOENT") {
|
|
throw new Error(`Could not run ${command} on this host.`);
|
|
}
|
|
return {
|
|
stdout: failure.stdout ?? "",
|
|
stderr: failure.stderr ?? "",
|
|
code: typeof failure.code === "number" ? failure.code : null,
|
|
};
|
|
}
|
|
}
|
|
|
|
function firstLine(stdout: string): string {
|
|
return stdout.split("\n").map((line) => line.trim()).find((line) => line.length > 0) ?? "";
|
|
}
|
|
|
|
export function resolveStartDir(raw?: string): string {
|
|
const home = homedir();
|
|
const trimmed = raw?.trim();
|
|
if (!trimmed) return home;
|
|
const expanded = trimmed === "~" ? home : trimmed.startsWith("~/") ? join(home, trimmed.slice(2)) : trimmed;
|
|
return existsSync(expanded) ? resolve(expanded) : home;
|
|
}
|
|
|
|
export type CreateFolderResult =
|
|
| { status: "ok"; path: string; name: string }
|
|
| { status: "error"; message: string };
|
|
|
|
/**
|
|
* Create one folder named `name` inside `parentPath` (defaults to the home
|
|
* folder on the host). Reuses the same path-resolution and `~` expansion as
|
|
* {@link listDirectory} so the two stay consistent about which directories
|
|
* are reachable on the host.
|
|
*/
|
|
export async function createFolder(
|
|
parentPath: string | undefined,
|
|
rawName: string,
|
|
): Promise<CreateFolderResult> {
|
|
const name = rawName.trim();
|
|
if (!name) {
|
|
return { status: "error", message: "Enter a name for the new folder." };
|
|
}
|
|
// A single path segment only. Separators, "." and ".." would let a name
|
|
// escape the current folder or overwrite a folder it does not name.
|
|
if (name === "." || name === ".." || name.includes("/") || name.includes("\\") || name.includes("\0")) {
|
|
return { status: "error", message: `Invalid folder name: ${name}` };
|
|
}
|
|
|
|
const home = homedir();
|
|
const parent = parentPath?.trim()
|
|
? parentPath.trim() === "~"
|
|
? home
|
|
: parentPath.trim().startsWith("~/")
|
|
? join(home, parentPath.trim().slice(2))
|
|
: resolve(parentPath.trim())
|
|
: home;
|
|
|
|
if (!isAbsolute(parent)) {
|
|
return { status: "error", message: `Not a folder on this host: ${parent}` };
|
|
}
|
|
|
|
try {
|
|
const info = await stat(parent);
|
|
if (!info.isDirectory()) {
|
|
return { status: "error", message: `Not a folder on this host: ${parent}` };
|
|
}
|
|
} catch (error) {
|
|
return {
|
|
status: "error",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
};
|
|
}
|
|
|
|
const fullPath = join(parent, name);
|
|
try {
|
|
// Not recursive: mkdir fails with EEXIST when a file or folder already
|
|
// has that name, which is exactly the collision we want to report.
|
|
await mkdir(fullPath);
|
|
} catch (error) {
|
|
const code = (error as { code?: string }).code;
|
|
if (code === "EEXIST") {
|
|
return {
|
|
status: "error",
|
|
message: `A file or folder named "${name}" already exists in ${parent}.`,
|
|
};
|
|
}
|
|
return {
|
|
status: "error",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
};
|
|
}
|
|
|
|
return { status: "ok", path: fullPath, name };
|
|
}
|
|
|
|
export type ListDirResult =
|
|
| {
|
|
status: "ok";
|
|
path: string;
|
|
parent: string | null;
|
|
home: string;
|
|
entries: Array<{ name: string; path: string; isGitRepo: boolean }>;
|
|
}
|
|
| { status: "error"; message: string };
|
|
|
|
export async function listDirectory(rawPath?: string, showHidden = false): Promise<ListDirResult> {
|
|
const home = homedir();
|
|
const target = rawPath?.trim()
|
|
? rawPath.trim() === "~"
|
|
? home
|
|
: rawPath.trim().startsWith("~/")
|
|
? join(home, rawPath.trim().slice(2))
|
|
: resolve(rawPath.trim())
|
|
: home;
|
|
|
|
try {
|
|
const info = await stat(target);
|
|
if (!info.isDirectory()) {
|
|
return { status: "error", message: `Not a folder on this host: ${target}` };
|
|
}
|
|
|
|
const dirents = await readdir(target, { withFileTypes: true });
|
|
const dirCandidates: Array<{ name: string; fullPath: string }> = [];
|
|
|
|
for (const dirent of dirents) {
|
|
if (!showHidden && dirent.name.startsWith(".")) continue;
|
|
const fullPath = join(target, dirent.name);
|
|
if (dirent.isDirectory()) {
|
|
dirCandidates.push({ name: dirent.name, fullPath });
|
|
} else if (dirent.isSymbolicLink()) {
|
|
const linked = await stat(fullPath).catch(() => null);
|
|
if (linked?.isDirectory()) {
|
|
dirCandidates.push({ name: dirent.name, fullPath });
|
|
}
|
|
}
|
|
}
|
|
|
|
dirCandidates.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" }));
|
|
|
|
const entries = await Promise.all(
|
|
dirCandidates.map(async ({ name, fullPath }) => {
|
|
const isGitRepo = await access(join(fullPath, ".git"))
|
|
.then(() => true)
|
|
.catch(() => false);
|
|
return { name, path: fullPath, isGitRepo };
|
|
}),
|
|
);
|
|
|
|
const parentDir = dirname(target);
|
|
return {
|
|
status: "ok",
|
|
path: target,
|
|
parent: parentDir === target ? null : parentDir,
|
|
home,
|
|
entries,
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
status: "error",
|
|
message: error instanceof Error ? error.message : String(error),
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function pickFolder(
|
|
settings: PickerSettings,
|
|
initialDir?: string,
|
|
): Promise<PickResult> {
|
|
const detected = detectPickers();
|
|
const picker = resolvePicker(settings, detected);
|
|
if (typeof picker !== "string") return { status: "error", message: picker.error };
|
|
|
|
const prompt = settings.prompt.trim() || "Select project folder";
|
|
const startDir = resolveStartDir(initialDir?.trim() || settings.startDir);
|
|
|
|
try {
|
|
switch (picker) {
|
|
case "kdialog": {
|
|
const result = await run("kdialog", ["--title", prompt, "--getexistingdirectory", startDir]);
|
|
const path = firstLine(result.stdout);
|
|
if (path) return { status: "picked", path, picker };
|
|
return result.code === 1
|
|
? { status: "cancelled", picker }
|
|
: { status: "error", message: "kdialog closed without returning a folder." };
|
|
}
|
|
case "zenity": {
|
|
const result = await run("zenity", [
|
|
"--file-selection",
|
|
"--directory",
|
|
"--title",
|
|
prompt,
|
|
"--filename",
|
|
`${startDir}/`,
|
|
]);
|
|
const path = firstLine(result.stdout);
|
|
if (path) return { status: "picked", path, picker };
|
|
return result.code === 1
|
|
? { status: "cancelled", picker }
|
|
: { status: "error", message: "zenity closed without returning a folder." };
|
|
}
|
|
case "yad": {
|
|
const result = await run("yad", [
|
|
"--file",
|
|
"--directory",
|
|
"--title",
|
|
prompt,
|
|
"--filename",
|
|
`${startDir}/`,
|
|
]);
|
|
const path = firstLine(result.stdout).replace(/\|$/, "");
|
|
if (path) return { status: "picked", path, picker };
|
|
return result.code === 1 || result.code === 252
|
|
? { status: "cancelled", picker }
|
|
: { status: "error", message: "yad closed without returning a folder." };
|
|
}
|
|
case "portal": {
|
|
const result = await run("python3", ["-c", PORTAL_PICK_SCRIPT, prompt, startDir]);
|
|
const path = firstLine(result.stdout);
|
|
if (path) return { status: "picked", path, picker };
|
|
if (result.code === 3) return { status: "cancelled", picker };
|
|
const detail = result.stderr.trim();
|
|
return {
|
|
status: "error",
|
|
message:
|
|
detail ||
|
|
"The desktop portal file browser failed. It needs python3 with PyGObject and a running xdg-desktop-portal on the host. Install kdialog or zenity as an alternative.",
|
|
};
|
|
}
|
|
case "osascript": {
|
|
const escapedPrompt = prompt.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
const escapedDir = startDir.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
const script = `POSIX path of (choose folder with prompt "${escapedPrompt}" default location POSIX file "${escapedDir}")`;
|
|
const result = await run("osascript", ["-e", script]);
|
|
const path = firstLine(result.stdout);
|
|
if (path) return { status: "picked", path: path.replace(/\/$/, "") || "/", picker };
|
|
return { status: "cancelled", picker };
|
|
}
|
|
case "powershell": {
|
|
const escapedDir = startDir.replace(/'/g, "''");
|
|
const script = [
|
|
"Add-Type -AssemblyName System.Windows.Forms;",
|
|
"$dialog = New-Object System.Windows.Forms.FolderBrowserDialog;",
|
|
`$dialog.Description = '${prompt.replace(/'/g, "''")}';`,
|
|
`$dialog.SelectedPath = '${escapedDir}';`,
|
|
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($dialog.SelectedPath) }",
|
|
].join(" ");
|
|
const result = await run("powershell.exe", ["-NoProfile", "-STA", "-Command", script]);
|
|
const path = firstLine(result.stdout);
|
|
if (path) return { status: "picked", path, picker };
|
|
return { status: "cancelled", picker };
|
|
}
|
|
case "custom": {
|
|
const command = settings.customCommand.replaceAll("{dir}", startDir);
|
|
const result = await run(command, [], true);
|
|
const path = firstLine(result.stdout);
|
|
if (path) return { status: "picked", path, picker };
|
|
return result.code === 1
|
|
? { status: "cancelled", picker }
|
|
: { status: "error", message: "The custom picker command printed no folder." };
|
|
}
|
|
default:
|
|
return { status: "error", message: `Unknown picker: ${picker}` };
|
|
}
|
|
} catch (error) {
|
|
return { status: "error", message: error instanceof Error ? error.message : String(error) };
|
|
}
|
|
}
|