Support Windows
Build a windows-x64 binary and add install.ps1. The editor, browser links, paths, clipboard images and t3tui upgrade all learn Windows' way of doing things; t3tui tmux says it needs WSL.
This commit is contained in:
1 parent
2845b6fe2b
commit
df2c8e0907
23 files changed
+355
-72
No files matched your search
+3
-1
@@ -3,7 +3,7 @@ import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts"
|
||||
|
||||
import { migrateConfigDir } from "./client/auth.ts";
|
||||
import { T3Session } from "./client/session.ts";
|
||||
import { isCompiled, upgrade, VERSION } from "./upgrade.ts";
|
||||
import { isCompiled, removeOldBinaries, upgrade, VERSION } from "./upgrade.ts";
|
||||
import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts";
|
||||
|
||||
const USAGE = `t3tui: a terminal client for T3 Code
|
||||
@@ -24,6 +24,7 @@ env:
|
||||
|
||||
async function main(argv: string[]) {
|
||||
migrateConfigDir();
|
||||
if (process.platform === "win32" && isCompiled()) removeOldBinaries();
|
||||
const [command, ...rest] = argv;
|
||||
switch (command) {
|
||||
case undefined:
|
||||
@@ -89,6 +90,7 @@ async function list(json: boolean) {
|
||||
}
|
||||
|
||||
async function tmuxCommand(args: string[]) {
|
||||
if (process.platform === "win32") return fail("t3tui tmux needs tmux, which doesn't run on Windows. Run it inside WSL instead.");
|
||||
const { syncTmux } = await import("./mux/tmux.ts");
|
||||
const sessionFlag = args.indexOf("--session");
|
||||
const name = sessionFlag >= 0 ? args[sessionFlag + 1] : "t3tui";
|
||||
|
||||
@@ -11,6 +11,8 @@ import { clampFileAttachmentUploadBytes, fileAttachmentTooLargeMessage } from "@
|
||||
import { homedir } from "node:os";
|
||||
import { basename, isAbsolute, resolve } from "node:path";
|
||||
|
||||
import { isWindowsAbsolute } from "./paths.ts";
|
||||
|
||||
const IMAGE_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
|
||||
gif: "image/gif",
|
||||
jpeg: "image/jpeg",
|
||||
@@ -28,7 +30,7 @@ export function imageMimeTypeForName(name: string): string | null {
|
||||
/** Expands `~` and resolves a relative path against `cwd`, as the attach prompt promises. */
|
||||
export function expandAttachmentPath(input: string, cwd: string | null): string {
|
||||
const path = input.trim();
|
||||
const expanded = path === "~" ? homedir() : path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : path;
|
||||
const expanded = path === "~" ? homedir() : path.startsWith("~/") || path.startsWith("~\\") ? resolve(homedir(), path.slice(2)) : path;
|
||||
return isAbsolute(expanded) ? expanded : resolve(cwd ?? process.cwd(), expanded);
|
||||
}
|
||||
|
||||
@@ -46,8 +48,13 @@ export interface ClipboardImageTool {
|
||||
readonly decode?: (stdout: Uint8Array) => Uint8Array | null;
|
||||
}
|
||||
|
||||
/** Prints the clipboard's image as base64 PNG, and nothing when it holds none. Reading the clipboard needs -STA. */
|
||||
const WINDOWS_CLIPBOARD_IMAGE =
|
||||
"Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $image = [Windows.Forms.Clipboard]::GetImage(); if ($image) { $stream = New-Object IO.MemoryStream; $image.Save($stream, [Drawing.Imaging.ImageFormat]::Png); [Convert]::ToBase64String($stream.ToArray()) }";
|
||||
|
||||
/** The clipboard readers, in order: the platform's usual image grabber first. */
|
||||
export function clipboardImageCommands(platform: string): readonly ClipboardImageTool[] {
|
||||
if (platform === "win32") return [{ read: () => ["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-Command", WINDOWS_CLIPBOARD_IMAGE], mimeType: "image/png", decode: (stdout) => Buffer.from(new TextDecoder().decode(stdout).trim(), "base64") }];
|
||||
return platform === "darwin"
|
||||
? [
|
||||
{ read: () => ["pngpaste", "-"], mimeType: "image/png" },
|
||||
@@ -90,13 +97,16 @@ export function pastedImagePath(text: string, cwd: string | null): string | null
|
||||
try {
|
||||
const url = new URL(raw);
|
||||
if (url.hostname && url.hostname !== "localhost") return null;
|
||||
path = decodeURIComponent(url.pathname);
|
||||
// `file:///C:/a.png` is a Windows path, whole, after its first slash.
|
||||
path = decodeURIComponent(url.pathname).replace(/^\/(?=[A-Za-z]:\/)/, "");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
path = raw.replace(/\\(.)/g, "$1");
|
||||
// A Windows path's backslashes are its folders, not escapes.
|
||||
path = isWindowsAbsolute(raw) ? raw : raw.replace(/\\(.)/g, "$1");
|
||||
}
|
||||
if (isWindowsAbsolute(path)) return imageMimeTypeForName(path) ? path : null;
|
||||
if (!path.startsWith("/") && !path.startsWith("~") && !path.startsWith(".")) return null;
|
||||
return imageMimeTypeForName(path) ? expandAttachmentPath(path, cwd) : null;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import type {
|
||||
VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { formatWorkingDurationLabel, type ThreadStructureTurnItem } from "@t3tools/client-runtime/state/models";
|
||||
import { homedir } from "node:os";
|
||||
import { tildify } from "./paths.ts";
|
||||
|
||||
import type { VcsState } from "../client/session.ts";
|
||||
import { formatClock, type T3tuiConfig } from "../config.ts";
|
||||
@@ -379,10 +379,6 @@ function prState(state: string, draft: boolean): { state: string; tone: StatusTo
|
||||
return { state, tone: "muted" };
|
||||
}
|
||||
|
||||
function tildify(path: string): string {
|
||||
const home = homedir();
|
||||
return path === home || path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
|
||||
}
|
||||
|
||||
const LIVE_SUBAGENT: ReadonlySet<string> = new Set(["pending", "running", "waiting"]);
|
||||
type SubagentStatus = "running" | "failed" | "done";
|
||||
|
||||
+4
-5
@@ -1,5 +1,5 @@
|
||||
import type { ProjectEntry } from "@t3tools/contracts";
|
||||
import { homedir } from "node:os";
|
||||
import { tildify } from "./paths.ts";
|
||||
|
||||
import type { ChangedFile } from "./details.ts";
|
||||
|
||||
@@ -72,11 +72,10 @@ const IMAGE_EXTENSIONS: ReadonlySet<string> = new Set(["png", "jpg", "jpeg", "gi
|
||||
|
||||
/** `~/…/project`: the root with the home folder shortened, cut from the middle to `width`. */
|
||||
export function rootLabel(root: string, width: number): string {
|
||||
const home = homedir();
|
||||
const path = root === home || root.startsWith(`${home}/`) ? `~${root.slice(home.length)}` : root;
|
||||
const path = tildify(root);
|
||||
if (path.length <= width) return path;
|
||||
const name = nameOf(path);
|
||||
const head = path.startsWith("~/") ? "~/…/" : "…/";
|
||||
const head = path.startsWith("~/") || path.startsWith("~\\") ? "~/…/" : "…/";
|
||||
return head.length + name.length <= width ? `${head}${name}` : `…${name.slice(Math.max(0, name.length - width + 1))}`;
|
||||
}
|
||||
|
||||
@@ -85,4 +84,4 @@ export function sizeLabel(bytes: number): string {
|
||||
return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
const nameOf = (path: string) => path.slice(path.lastIndexOf("/") + 1);
|
||||
const nameOf = (path: string) => path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
|
||||
+21
-8
@@ -1,22 +1,35 @@
|
||||
/** Characters a file path on screen is made of, with an optional `:line` or `:line:col` after it. */
|
||||
const PATH_CHARS = /[\w.~/@+-]/;
|
||||
|
||||
/** On Windows, backslashes too. */
|
||||
const WINDOWS_PATH_CHARS = /[\w.~/\\@+-]/;
|
||||
|
||||
/**
|
||||
* The file path the text has at `index`, as an agent writes them: `src/ui/App.tsx`,
|
||||
* `./bin.ts:12`, `~/notes.md`. Null for words, URLs and anything else without a folder
|
||||
* or an extension.
|
||||
* `./bin.ts:12`, `~/notes.md`, and on Windows `src\ui\App.tsx` and `C:\notes.md`. Null for
|
||||
* words, URLs and anything else without a folder or an extension.
|
||||
*/
|
||||
export function pathAt(text: string, index: number): string | null {
|
||||
if (!PATH_CHARS.test(text[index] ?? "")) return null;
|
||||
export function pathAt(text: string, index: number, platform: string = process.platform): string | null {
|
||||
const windows = platform === "win32";
|
||||
const chars = windows ? WINDOWS_PATH_CHARS : PATH_CHARS;
|
||||
if (!chars.test(text[index] ?? "")) return null;
|
||||
let start = index;
|
||||
let end = index + 1;
|
||||
while (start > 0 && PATH_CHARS.test(text[start - 1]!)) start--;
|
||||
while (end < text.length && (PATH_CHARS.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++;
|
||||
while (start > 0 && chars.test(text[start - 1]!)) start--;
|
||||
while (end < text.length && (chars.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++;
|
||||
// The drive's colon, which is no line number: `C:\notes.md`.
|
||||
if (windows && text[start - 1] === ":" && /(?:^|[^\w])[A-Za-z]$/.test(text.slice(Math.max(0, start - 3), start - 1)) && /[\\/]/.test(text[start] ?? "")) start -= 2;
|
||||
if (text[start - 1] === ":" || text.slice(end, end + 3) === "://") return null;
|
||||
const token = text.slice(start, end).replace(/[.,]+$/, "");
|
||||
const path = token.replace(/(:\d+){1,2}$/, "");
|
||||
if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/")) return null;
|
||||
return path.includes("/") || /\.[A-Za-z]\w*$/.test(path) ? path : null;
|
||||
if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/") && !(windows && /^\.{0,2}\\/.test(path))) return null;
|
||||
return path.includes("/") || (windows && path.includes("\\")) || /\.[A-Za-z]\w*$/.test(path) ? path : null;
|
||||
}
|
||||
|
||||
/** The command that opens a web link in the desktop's browser. Windows' goes round cmd, which would split a URL at its `&`. */
|
||||
export function browserCommand(url: string, platform: string = process.platform): string[] {
|
||||
if (platform === "win32") return ["rundll32.exe", "url.dll,FileProtocolHandler", url];
|
||||
return [platform === "darwin" ? "open" : "xdg-open", url];
|
||||
}
|
||||
|
||||
/** A link's target is a web page unless it is a bare path. */
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { homedir } from "node:os";
|
||||
|
||||
/** A path with the home folder as `~`, whichever way the path's slashes lean. */
|
||||
export function tildify(path: string, home: string = homedir()): string {
|
||||
return path === home || path.startsWith(`${home}/`) || path.startsWith(`${home}\\`) ? `~${path.slice(home.length)}` : path;
|
||||
}
|
||||
|
||||
/** Whether this is a Windows path no folder can be relative to: `C:\x`, `C:/x` or `\\server\x`. */
|
||||
export const isWindowsAbsolute = (path: string) => /^(?:[A-Za-z]:[\\/]|\\\\)/.test(path);
|
||||
+2
-2
@@ -4,7 +4,6 @@ import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/compo
|
||||
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
|
||||
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
|
||||
import { existsSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { isAbsolute, join, relative } from "node:path";
|
||||
import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -73,6 +72,7 @@ import { useThreadLibrary } from "./useThreadLibrary.ts";
|
||||
import { usePaletteSearch } from "./usePaletteSearch.ts";
|
||||
import { useThreadFind } from "./useThreadFind.ts";
|
||||
import { ThreadFindBar } from "./ThreadFindBar.tsx";
|
||||
import { tildify } from "../model/paths.ts";
|
||||
import { mergeThreadShells, messageMatchGroups } from "../model/search.ts";
|
||||
import { useAttachments } from "./useAttachments.ts";
|
||||
import { useAutomations } from "./useAutomations.ts";
|
||||
@@ -1397,7 +1397,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
|
||||
serverStatus={serverConfig?.status ?? "loading"}
|
||||
usage={[...usageInfo.lines, ...usageSummaryLines(usage.summary), ...(usage.failed && !usage.summary ? [{ label: "Last 30 days", value: "could not read usage" }] : [])]}
|
||||
selected={settingsIndex}
|
||||
path={configPath().replace(homedir(), "~")}
|
||||
path={tildify(configPath())}
|
||||
onCycle={(index) => {
|
||||
setMode("settings");
|
||||
cycleSetting(index);
|
||||
|
||||
+14
-4
@@ -165,10 +165,20 @@ function attachServer(session: T3Session, target: TerminalTarget, term: Embedded
|
||||
/** A program run here on its own pty, answering its terminal queries through the emulator. */
|
||||
function spawnLocal(program: Extract<PaneProgram, { kind: "local" }>, term: EmbeddedTerminalRenderable, cols: number, rows: number, close: (message?: string) => void): Link {
|
||||
let stopped = false;
|
||||
const child = Bun.spawn([...program.command], {
|
||||
...(program.cwd ? { cwd: program.cwd } : {}),
|
||||
terminal: { cols, rows, data: (_pty, data) => term.write(data) },
|
||||
});
|
||||
let child: ReturnType<typeof Bun.spawn>;
|
||||
try {
|
||||
child = Bun.spawn([...program.command], {
|
||||
...(program.cwd ? { cwd: program.cwd } : {}),
|
||||
terminal: { cols, rows, data: (_pty, data) => term.write(data) },
|
||||
});
|
||||
} catch (error) {
|
||||
// A missing program throws here, inside a resize; let the pane say so rather than the render loop.
|
||||
queueMicrotask(() => {
|
||||
program.onExit(127);
|
||||
close(`Couldn't start ${program.command[0]}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
});
|
||||
return { send: () => {}, resize: () => {}, stop: () => {} };
|
||||
}
|
||||
void child.exited.then((code) => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
|
||||
+27
-8
@@ -2,27 +2,45 @@ import type { CliRenderer } from "@opentui/core";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, join } from "node:path";
|
||||
import { join } from "node:path";
|
||||
|
||||
const editorSetting = () => process.env.VISUAL || process.env.EDITOR || "vi";
|
||||
const WINDOWS = process.platform === "win32";
|
||||
const editorSetting = () => process.env.VISUAL || process.env.EDITOR || (WINDOWS ? "notepad" : "vi");
|
||||
const shell = () => process.env.SHELL || "sh";
|
||||
/** The editor's program, without its arguments. */
|
||||
const editorProgram = () => editorSetting().trim().split(/\s+/)[0] ?? "vi";
|
||||
const editorProgram = () => (WINDOWS ? windowsWords(editorSetting())[0] : editorSetting().trim().split(/\s+/)[0]) ?? "vi";
|
||||
|
||||
/**
|
||||
* $VISUAL or $EDITOR (falling back to vi) on `file`, through the shell so EDITOR="code --wait" works.
|
||||
* $VISUAL or $EDITOR (falling back to vi, or notepad on Windows) on `file`, through the shell so EDITOR="code --wait" works.
|
||||
* With `listen`, Neovim serves that socket, so more files can go to it (see nvimRemote).
|
||||
*/
|
||||
export function editorCommand(file: string, listen?: string): string[] {
|
||||
const editor = editorSetting();
|
||||
if (WINDOWS) return [...windowsCommand(editor), ...(listen ? ["--listen", listen] : []), file];
|
||||
return listen ? [shell(), "-c", `${editor} --listen "$2" "$1"`, "sh", file, listen] : [shell(), "-c", `${editor} "$1"`, "sh", file];
|
||||
}
|
||||
|
||||
/** Whether the editor is Neovim, which can take more files and be asked to quit through a socket. */
|
||||
export const editorIsNvim = () => basename(editorProgram()) === "nvim";
|
||||
/** Splits a command line on spaces outside double quotes: `"C:\Program Files\Neovim\bin\nvim.exe" -p`. */
|
||||
export function windowsWords(command: string): string[] {
|
||||
return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2]!);
|
||||
}
|
||||
|
||||
/** A socket for a Neovim started here, in a temp folder of its own (`remove` cleans up). Kept short: sockets have a length limit. */
|
||||
/** A command to run with no shell. Windows has no sh, and a .cmd like VS Code's `code` only runs through cmd. */
|
||||
export function windowsCommand(command: string, which: (program: string) => string | null = Bun.which): string[] {
|
||||
const [program = "", ...args] = windowsWords(command);
|
||||
const found = which(program) ?? program;
|
||||
return [...(/\.(?:cmd|bat)$/i.test(found) ? ["cmd.exe", "/c"] : []), found, ...args];
|
||||
}
|
||||
|
||||
/** Whether this program, by name or path, is Neovim. */
|
||||
export const isNvim = (program: string) => /^nvim(?:\.exe)?$/i.test(program.split(/[\\/]/).pop() ?? "");
|
||||
|
||||
/** Whether the editor is Neovim, which can take more files and be asked to quit through a socket. */
|
||||
export const editorIsNvim = () => isNvim(editorProgram());
|
||||
|
||||
/** A socket for a Neovim started here, in a temp folder of its own (`remove` cleans up); on Windows, a named pipe. Kept short: sockets have a length limit. */
|
||||
export function nvimSocket(): { readonly path: string; readonly remove: () => void } {
|
||||
if (WINDOWS) return { path: `\\\\.\\pipe\\t3tui-nvim-${crypto.randomUUID()}`, remove: () => {} };
|
||||
const dir = mkdtempSync(join(tmpdir(), "t3tui-nvim-"));
|
||||
return { path: join(dir, "nvim.sock"), remove: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
@@ -33,7 +51,8 @@ export function nvimSocket(): { readonly path: string; readonly remove: () => vo
|
||||
* never fall back to editing in a Neovim of their own.
|
||||
*/
|
||||
export async function nvimRemote(socket: string, args: readonly string[]): Promise<string | null> {
|
||||
const child = Bun.spawn([shell(), "-c", `${editorProgram()} --server "$@"`, "sh", socket, ...args], { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
||||
const command = WINDOWS ? [...windowsCommand(`"${editorProgram()}"`), "--server", socket, ...args] : [shell(), "-c", `${editorProgram()} --server "$@"`, "sh", socket, ...args];
|
||||
const child = Bun.spawn(command, { stdin: "ignore", stdout: "pipe", stderr: "ignore" });
|
||||
const [code, output] = await Promise.all([child.exited, new Response(child.stdout).text()]);
|
||||
return code === 0 ? output : null;
|
||||
}
|
||||
|
||||
+5
-3
@@ -1,13 +1,15 @@
|
||||
import type { CliRenderer } from "@opentui/core";
|
||||
|
||||
import { browserCommand } from "../model/links.ts";
|
||||
|
||||
/** Opens a web link in the desktop's browser; `fail` hears why it couldn't, as over SSH. */
|
||||
export function openInBrowser(url: string, fail: (reason: string) => void): void {
|
||||
try {
|
||||
const opener = process.platform === "darwin" ? "open" : "xdg-open";
|
||||
const command = browserCommand(url);
|
||||
// The environment as it is now: Bun otherwise looks the opener up on the PATH it started with.
|
||||
const child = Bun.spawn([opener, url], { env: process.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
||||
const child = Bun.spawn(command, { env: process.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
|
||||
void child.exited.then((code) => {
|
||||
if (code !== 0) fail(`${opener} exited with ${code}`);
|
||||
if (code !== 0) fail(`${command[0]} exited with ${code}`);
|
||||
});
|
||||
} catch (error) {
|
||||
fail(error instanceof Error ? error.message : String(error));
|
||||
|
||||
+2
-2
@@ -1,6 +1,5 @@
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
import type { ChatAttachment, ModelSelection, OrchestrationMessageContext, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
|
||||
import { homedir } from "node:os";
|
||||
import { useState } from "react";
|
||||
|
||||
import type { T3Session } from "../client/session.ts";
|
||||
@@ -8,6 +7,7 @@ import { RUNTIME_MODE_LABELS } from "../model/details.ts";
|
||||
import type { Binding } from "../model/keymap.ts";
|
||||
import { draftDefaults, modelSummary, type DraftThread } from "../model/models.ts";
|
||||
import type { Picker } from "../model/palette.ts";
|
||||
import { tildify } from "../model/paths.ts";
|
||||
import type { DraftLine } from "./DraftView.tsx";
|
||||
|
||||
type WorkspaceStrategy = { type: "root" } | { type: "existing_worktree"; worktreePath: string } | { type: "worktree"; baseRef: string; startFromOrigin?: boolean };
|
||||
@@ -64,7 +64,7 @@ export function useDraft(deps: {
|
||||
items: projects.map((candidate) => ({
|
||||
id: `project:${candidate.id}`,
|
||||
title: candidate.title,
|
||||
hint: candidate.id === draft.projectId ? "current" : candidate.workspaceRoot.replace(homedir(), "~"),
|
||||
hint: candidate.id === draft.projectId ? "current" : tildify(candidate.workspaceRoot),
|
||||
run: () => setDraft(draftDefaults({ config, project: candidate, currentModel: draft.modelSelection, projectHasThreads: hasThreads(candidate.id) })),
|
||||
})),
|
||||
},
|
||||
|
||||
+46
-13
@@ -1,20 +1,26 @@
|
||||
// `t3tui upgrade`: replaces a released binary with the latest release's.
|
||||
import { chmod, rename, rm } from "node:fs/promises";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { readdirSync, realpathSync, rmSync } from "node:fs";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
export const VERSION = version;
|
||||
const REPO = "callumalpass/t3tui";
|
||||
const LATEST_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
|
||||
const DOWNLOAD_URL = `https://github.com/${REPO}/releases/download`;
|
||||
|
||||
/** Bun's embedded filesystem: `/$bunfs/…`, or `B:\~BUN\…` on Windows. */
|
||||
export const isEmbeddedPath = (path: string) => path.startsWith("/$bunfs/") || /^[A-Za-z]:[\\/]~BUN[\\/]/.test(path);
|
||||
|
||||
/** A compiled binary runs its code from Bun's embedded filesystem. */
|
||||
export function isCompiled(): boolean {
|
||||
return import.meta.path.startsWith("/$bunfs/");
|
||||
return isEmbeddedPath(import.meta.path);
|
||||
}
|
||||
|
||||
/** The release asset for this machine, e.g. t3tui-linux-x64. */
|
||||
/** The release asset for this machine, e.g. t3tui-linux-x64 or t3tui-windows-x64.exe. */
|
||||
export function assetName(platform: string = process.platform, arch: string = process.arch): string {
|
||||
return `t3tui-${platform}-${arch}`;
|
||||
return platform === "win32" ? `t3tui-windows-${arch}.exe` : `t3tui-${platform}-${arch}`;
|
||||
}
|
||||
|
||||
/** Finds an asset's hash in a sha256sum listing. */
|
||||
@@ -31,7 +37,7 @@ export async function upgrade(): Promise<void> {
|
||||
console.log("t3tui is running from source. Update it with: git pull --recurse-submodules && bun install");
|
||||
return;
|
||||
}
|
||||
const latest = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: { accept: "application/vnd.github+json" } });
|
||||
const latest = await fetch(LATEST_URL, { headers: { accept: "application/vnd.github+json" } });
|
||||
if (latest.status === 404) throw new Error("No t3tui release has been published yet.");
|
||||
if (!latest.ok) throw new Error(`Couldn't check for a new release (GitHub answered ${latest.status}).`);
|
||||
const tag = ((await latest.json()) as { tag_name: string }).tag_name;
|
||||
@@ -40,27 +46,54 @@ export async function upgrade(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
const file = `${assetName()}.gz`;
|
||||
const base = `https://github.com/${REPO}/releases/download/${tag}`;
|
||||
const base = `${DOWNLOAD_URL}/${tag}`;
|
||||
const [archive, sums] = await Promise.all([download(`${base}/${file}`), download(`${base}/SHA256SUMS`)]);
|
||||
const expected = checksumFor(new TextDecoder().decode(sums), file);
|
||||
if (!expected) throw new Error(`Release ${tag} has no ${file}.`);
|
||||
const actual = new Bun.CryptoHasher("sha256").update(archive).digest("hex");
|
||||
if (actual !== expected) throw new Error(`The downloaded ${file} doesn't match its checksum; nothing was changed.`);
|
||||
|
||||
// Renaming over the running binary is safe: the running process keeps the old file open.
|
||||
const target = realpathSync(process.execPath);
|
||||
await replaceBinary(realpathSync(process.execPath), Bun.gunzipSync(archive));
|
||||
console.log(`t3tui ${VERSION} → ${tag.replace(/^v/, "")}`);
|
||||
}
|
||||
|
||||
/** Puts `binary` where `target` is, which may be the running program. */
|
||||
export async function replaceBinary(target: string, binary: Uint8Array, platform: string = process.platform): Promise<void> {
|
||||
const temporary = `${target}.upgrade-${process.pid}`;
|
||||
try {
|
||||
await Bun.write(temporary, Bun.gunzipSync(archive));
|
||||
await chmod(temporary, 0o755);
|
||||
await rename(temporary, target);
|
||||
await Bun.write(temporary, binary);
|
||||
if (platform === "win32") {
|
||||
// Windows won't let a running .exe be replaced, or deleted, but it can be moved aside.
|
||||
const aside = `${target}${OLD_SUFFIX}${process.pid}`;
|
||||
await rename(target, aside);
|
||||
await rename(temporary, target).catch(async (error) => {
|
||||
await rename(aside, target);
|
||||
throw error;
|
||||
});
|
||||
} else {
|
||||
// Renaming over the running binary is safe: the running process keeps the old file open.
|
||||
await chmod(temporary, 0o755);
|
||||
await rename(temporary, target);
|
||||
}
|
||||
} catch (error) {
|
||||
await rm(temporary, { force: true });
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "EACCES" || code === "EPERM") throw new Error(`Can't write ${target}. Rerun with permission to replace it (e.g. sudo t3tui upgrade).`);
|
||||
if (code === "EACCES" || code === "EPERM") throw new Error(`Can't write ${target}. ${platform === "win32" ? "Rerun from an administrator terminal." : "Rerun with permission to replace it (e.g. sudo t3tui upgrade)."}`);
|
||||
throw error;
|
||||
}
|
||||
console.log(`t3tui ${VERSION} → ${tag.replace(/^v/, "")}`);
|
||||
}
|
||||
|
||||
const OLD_SUFFIX = ".old-";
|
||||
|
||||
/** Deletes what an upgrade moved aside on Windows; one another t3tui still runs stays for next time. */
|
||||
export function removeOldBinaries(target: string = process.execPath): void {
|
||||
const folder = dirname(target);
|
||||
for (const name of readdirSync(folder)) {
|
||||
if (!name.startsWith(`${basename(target)}${OLD_SUFFIX}`)) continue;
|
||||
try {
|
||||
rmSync(join(folder, name));
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
async function download(url: string): Promise<Uint8Array<ArrayBuffer>> {
|
||||
|
||||
Reference in new issue
Block a user