Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ is init

```shell
npm install -g @microsoft/inshellisense # OR brew upgrade inshellisense
is reinit
```

inshellisense refreshes its generated resources automatically the first time a new version starts. If it ever fails to start, the shell plugin falls back to your plain shell and prints the error; run `is reinit` to fully regenerate the resources.

### Quickstart

After completing the installation, run `is doctor` to verify your installation was successful. You can run `is` to start the autocomplete session for your desired shell. Additionally, inshellisense is also aliased under `inshellisense` after installation.
Expand Down
101 changes: 82 additions & 19 deletions src/commands/root.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { Shell, supportedShells as shells } from "../utils/shell.js";
import { spawnSync } from "node:child_process";
import { Shell, supportedShells as shells, getShellExecutable, getShellLoginArgs } from "../utils/shell.js";
import { inferShell } from "../utils/shell.js";
import { loadConfig } from "../utils/config.js";
import { Command } from "commander";
import { Command, CommanderError } from "commander";
import log from "../utils/log.js";
import { checkUnpackedVersion } from "../utils/node.js";
import { checkUnpackedVersion, refreshResources } from "../utils/node.js";
import { endTiming, startTiming } from "../utils/performance.js";
import { resetToInitialState } from "../utils/ansi.js";

export const supportedShells = shells.join(", ");

Expand All @@ -19,6 +21,65 @@ type RootCommandOptions = {
login: boolean | undefined;
};

const ensureResources = async () => {
if (await checkUnpackedVersion()) return;
const refreshTiming = startTiming();
log.debug({ msg: "unpacked resources are out of date, refreshing" });
await refreshResources();
endTiming("startup.refreshResources", refreshTiming);
};

// The shell plugins exit the parent shell once `is` returns, so failing to start would immediately close the terminal.
// Instead, report the failure and hand the terminal over to the plain shell. ISTERM is set to a non-empty value other
// than "1" so the shell plugin doesn't start inshellisense again, while a manual `is` can still retry.
const runFallbackShell = async (shell: Shell, login: boolean, error: unknown): Promise<never> => {
const { renderStartupFailure } = await import("../ui/ui-status.js");
const message = error instanceof CommanderError ? undefined : error instanceof Error ? error.message : String(error);
process.stderr.write(renderStartupFailure(message));

try {
const result = spawnSync(await getShellExecutable(shell), getShellLoginArgs(shell, login), {
stdio: "inherit",
env: { ...process.env, ISTERM: "0" },
});
if (result.error != null) throw result.error;
process.exit(result.status ?? 1);
} catch (e) {
process.stderr.write(`unable to start ${shell}: ${e instanceof Error ? e.message : String(e)}\n`);
process.exit(1);
}
};

// Stops a session whose UI failed to set up and gives the terminal back in its original state for the fallback shell.
const abandonSession = (term: { kill: () => void }) => {
try {
term.kill();
} catch {
/* the shell may have already exited */
}
process.stdin.removeAllListeners("data");
process.stdin.pause();
if (process.stdin.isTTY) process.stdin.setRawMode(false);
process.stdout.write(resetToInitialState);
};

const startSession = async (program: Command, shell: Shell, underTest: boolean, login: boolean) => {
// settle both before failing so a resource refresh is never left half-written behind the fallback shell
const results = await Promise.allSettled([ensureResources(), loadConfig(program)]);
const failure = results.find((result) => result.status === "rejected");
if (failure != null) throw failure.reason;
log.overrideConsole();

const [{ initializeRuntime }, { render }, isterm] = await Promise.all([
import("../runtime/initialize.js"),
import("../ui/ui-root.js"),
import("../isterm/index.js"),
]);
await initializeRuntime(shell);
const term = await isterm.default.spawn(program, { shell, rows: process.stdout.rows, cols: process.stdout.columns, underTest, login });
return { term, render };
};

export const action = (program: Command) => async (options: RootCommandOptions) => {
const startupTiming = startTiming();
const inISTerm = process.env.ISTERM === "1";
Expand All @@ -29,30 +90,32 @@ export const action = (program: Command) => async (options: RootCommandOptions)
process.exit(0);
}

const isVersionUpToDate = await checkUnpackedVersion();
if (!isVersionUpToDate) {
const { renderMissingResources } = await import("../ui/ui-status.js");
process.stdout.write(renderMissingResources());
endTiming("startup.missingResources", startupTiming);
process.exit(1);
}

if (options.verbose) await log.enable();

const [, inferredShell] = await Promise.all([loadConfig(program), options.shell ? Promise.resolve(options.shell) : inferShell()]);

log.overrideConsole();

const shell = (options.shell ?? inferredShell) as Shell | undefined;
const shell = (options.shell ?? (await inferShell())) as Shell | undefined;
if (shell == null) {
program.error(`Unable to identify shell, use the -s/--shell option to provide your shell`, { exitCode: 1 });
}
if (!shells.map((s) => s.valueOf()).includes(shell)) {
program.error(`Unsupported shell: '${shell}', supported shells: ${supportedShells}`, { exitCode: 1 });
}
const login = options.login ?? false;

const [{ initializeRuntime }, { render }] = await Promise.all([import("../runtime/initialize.js"), import("../ui/ui-root.js")]);
await initializeRuntime(shell);
// from here on, errors (including commander's program.error, e.g. for an invalid config) fall back to the plain shell
program.exitOverride();
let session: Awaited<ReturnType<typeof startSession>>;
try {
session = await startSession(program, shell, options.test ?? false, login);
} catch (error) {
log.debug({ msg: "inshellisense failed to start", error: error instanceof Error ? error.message : error });
return runFallbackShell(shell, login, error);
}
endTiming("startup.beforeRender", startupTiming);
await render(program, shell, options.test ?? false, options.login ?? false);
try {
await session.render(session.term, shell);
} catch (error) {
log.debug({ msg: "inshellisense failed to render", error: error instanceof Error ? error.message : error });
abandonSession(session.term);
return runFallbackShell(shell, login, error);
}
};
20 changes: 4 additions & 16 deletions src/isterm/pty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ interface ICellData extends IBufferCell {
}
import { CommandManager, CommandState } from "./commandManager.js";
import log from "../utils/log.js";
import { gitBashPath } from "../utils/shell.js";
import { getShellExecutable, getShellLoginArgs } from "../utils/shell.js";
import styles from "ansi-styles";
import * as ansi from "../utils/ansi.js";
import { Command } from "commander";
Expand Down Expand Up @@ -431,7 +431,7 @@ const shellExists = async (shellTarget: string): Promise<boolean> => {

const convertToPtyTarget = async (shell: Shell, underTest: boolean, login: boolean) => {
const platform = os.platform();
const shellTarget = shell == Shell.Bash && platform == "win32" ? await gitBashPath() : platform == "win32" ? `${shell}.exe` : shell;
const shellTarget = await getShellExecutable(shell);
let shellArgs: string[] = [];

switch (shell) {
Expand Down Expand Up @@ -465,20 +465,8 @@ const convertToPtyTarget = async (shell: Shell, underTest: boolean, login: boole
break;
}

if (login) {
switch (shell) {
case Shell.Powershell:
case Shell.Pwsh:
shellArgs.unshift("-login");
break;
case Shell.Zsh:
case Shell.Fish:
case Shell.Xonsh:
case Shell.Nushell:
shellArgs.unshift("--login");
break;
}
}
// bash login behavior is emulated by shellIntegration.bash (ISTERM_LOGIN) since --login can't be combined with --init-file
if (shell != Shell.Bash) shellArgs.unshift(...getShellLoginArgs(shell, login));

return { shellTarget, shellArgs };
};
Expand Down
62 changes: 62 additions & 0 deletions src/tests/utils/file.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { writeFileAtomic } from "../../utils/file.js";

let directory: string;

beforeEach(() => {
directory = fs.mkdtempSync(path.join(os.tmpdir(), "is-file-test-"));
});

afterEach(() => {
fs.rmSync(directory, { recursive: true, force: true });
});

const listTempFiles = () => fs.readdirSync(directory, { recursive: true }).filter((file) => String(file).endsWith(".tmp"));

describe("writeFileAtomic", () => {
test("creates missing parent directories", async () => {
const filePath = path.join(directory, "nested", "file.txt");
await writeFileAtomic(filePath, "content");
expect(fs.readFileSync(filePath, "utf-8")).toBe("content");
expect(listTempFiles()).toEqual([]);
});

test("replaces an outdated file", async () => {
const filePath = path.join(directory, "file.txt");
fs.writeFileSync(filePath, "old");
await writeFileAtomic(filePath, new Uint8Array(Buffer.from("new")));
expect(fs.readFileSync(filePath, "utf-8")).toBe("new");
expect(listTempFiles()).toEqual([]);
});

test("leaves an up to date file untouched", async () => {
const filePath = path.join(directory, "file.txt");
fs.writeFileSync(filePath, "same");
const inode = fs.statSync(filePath).ino;
await writeFileAtomic(filePath, "same");
expect(fs.statSync(filePath).ino).toBe(inode);
});

if (process.platform !== "win32") {
test("keeps the permissions of the replaced file", async () => {
const filePath = path.join(directory, "helper");
fs.writeFileSync(filePath, "old");
fs.chmodSync(filePath, 0o755);
await writeFileAtomic(filePath, "new");
expect(fs.statSync(filePath).mode & 0o777).toBe(0o755);
});
}

test("supports concurrent writers", async () => {
const filePath = path.join(directory, "file.txt");
fs.writeFileSync(filePath, "old");
await Promise.all(Array.from({ length: 10 }, () => writeFileAtomic(filePath, "new")));
expect(fs.readFileSync(filePath, "utf-8")).toBe("new");
expect(listTempFiles()).toEqual([]);
});
});
55 changes: 55 additions & 0 deletions src/tests/utils/node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { checkUnpackedVersion, refreshResources } from "../../utils/node.js";
import { getShellConfig, Shell } from "../../utils/shell.js";
import { getVersion } from "../../utils/version.js";

let directory: string;
let sourceRoot: string;
let resourcesPath: string;

const write = (filePath: string, content: string) => {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content);
};

beforeEach(() => {
directory = fs.mkdtempSync(path.join(os.tmpdir(), "is-node-test-"));
sourceRoot = path.join(directory, "source");
resourcesPath = path.join(directory, "resources");
write(path.join(sourceRoot, "shell", "shellIntegration-rc.zsh"), "new shell integration");
write(path.join(sourceRoot, "node_modules", "@withfig", "autocomplete", "build", "git.js"), "new spec");
});

afterEach(() => {
fs.rmSync(directory, { recursive: true, force: true });
});

describe("refreshResources", () => {
test("replaces resources unpacked by a previous version", async () => {
write(path.join(resourcesPath, "version.txt"), "0.0.1");
write(path.join(resourcesPath, "shell", "shellIntegration-rc.zsh"), "old shell integration");
write(path.join(resourcesPath, "spec", "git.js"), "old spec");
write(path.join(resourcesPath, "init", "zsh", "init.zsh"), "old init");
expect(await checkUnpackedVersion(resourcesPath)).toBe(false);

await refreshResources(resourcesPath, sourceRoot);

expect(fs.readFileSync(path.join(resourcesPath, "shell", "shellIntegration-rc.zsh"), "utf-8")).toBe("new shell integration");
expect(fs.readFileSync(path.join(resourcesPath, "spec", "git.js"), "utf-8")).toBe("new spec");
expect(fs.readFileSync(path.join(resourcesPath, "init", "zsh", "init.zsh"), "utf-8")).toBe(getShellConfig(Shell.Zsh));
expect(fs.readFileSync(path.join(resourcesPath, "version.txt"), "utf-8")).toBe(getVersion());
expect(await checkUnpackedVersion(resourcesPath)).toBe(true);
});

test("can run concurrently", async () => {
await Promise.all(Array.from({ length: 3 }, () => refreshResources(resourcesPath, sourceRoot)));

expect(await checkUnpackedVersion(resourcesPath)).toBe(true);
expect(fs.readdirSync(resourcesPath, { recursive: true }).filter((file) => String(file).endsWith(".tmp"))).toEqual([]);
});
});
29 changes: 28 additions & 1 deletion src/tests/utils/shell.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,15 @@
import os from "node:os";
import path from "node:path";
import process from "node:process";
import { getShellSourceCommand, hasLegacyShellConfig, normalizeBackspace, Shell, shouldFlagLegacyResourcePlugin, zdotdir } from "../../utils/shell.js";
import {
getShellLoginArgs,
getShellSourceCommand,
hasLegacyShellConfig,
normalizeBackspace,
Shell,
shouldFlagLegacyResourcePlugin,
zdotdir,
} from "../../utils/shell.js";

test("uses a process-specific ZDOTDIR", () => {
expect(zdotdir).toBe(path.join(os.tmpdir(), `is-zsh-${process.pid}`));
Expand Down Expand Up @@ -107,3 +115,22 @@ describe("shouldFlagLegacyResourcePlugin", () => {
expect(shouldFlagLegacyResourcePlugin(usesLegacyResources, hasXdgConfig)).toBe(expected);
});
});

describe("getShellLoginArgs", () => {
test.each([
[Shell.Bash, ["--login"]],
[Shell.Zsh, ["--login"]],
[Shell.Fish, ["--login"]],
[Shell.Xonsh, ["--login"]],
[Shell.Nushell, ["--login"]],
[Shell.Pwsh, ["-login"]],
[Shell.Powershell, ["-login"]],
[Shell.Cmd, []],
])("returns the login arguments for %s", (shell, expected) => {
expect(getShellLoginArgs(shell, true)).toEqual(expected);
});

test.each(Object.values(Shell))("returns no arguments for a non-login %s shell", (shell) => {
expect(getShellLoginArgs(shell, false)).toEqual([]);
});
});
7 changes: 3 additions & 4 deletions src/ui/ui-root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
// Licensed under the MIT License.

import ansi from "ansi-escapes";
import { Command } from "commander";

import log from "../utils/log.js";
import { normalizeBackspace, Shell } from "../utils/shell.js";
import { resetToInitialState } from "../utils/ansi.js";
import { endTiming, incrementMetric, startTiming } from "../utils/performance.js";
import type { KeyPressEvent } from "./suggestionManager.js";
import type { ISTerm } from "../isterm/pty.js";
import { BatchScheduler } from "./batchScheduler.js";
import { SuggestionRenderer } from "./suggestionRenderer.js";
import { StdioProxy } from "./stdioProxy.js";
Expand All @@ -20,9 +20,8 @@ const writeOutput = (data: string) => {
process.stdout.write(data);
};

export const render = async (program: Command, shell: Shell, underTest: boolean, login: boolean) => {
const [isterm, { SuggestionManager }] = await Promise.all([import("../isterm/index.js"), import("./suggestionManager.js")]);
const term = await isterm.default.spawn(program, { shell, rows: process.stdout.rows, cols: process.stdout.columns, underTest, login });
export const render = async (term: ISTerm, shell: Shell) => {
const { SuggestionManager } = await import("./suggestionManager.js");
const suggestions = new SuggestionManager(term, shell);
const renderer = new SuggestionRenderer(term, suggestions, writeOutput);
let commandStateVersion = term.getCommandStateVersion();
Expand Down
8 changes: 6 additions & 2 deletions src/ui/ui-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export const renderConfirmation = (live: boolean): string => {
return `inshellisense session [${statusMessage}]\n`;
};

export const renderMissingResources = (): string => {
return chalk.red(`inshellisense resources out of date, run "is reinit" to refresh\n`);
export const renderStartupFailure = (message: string | undefined): string => {
const reason = message != null && message.length > 0 ? `: ${message}` : "";
return (
chalk.red(`inshellisense failed to start${reason}\n`) +
chalk.dim(`starting your shell without inshellisense, run "is doctor" or "is reinit" to fix the installation\n`)
);
};
Loading