@microsoft/inshellisense 0.0.1-rc.1 → 0.0.1-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CODE_OF_CONDUCT.md +9 -9
  2. package/LICENSE +21 -21
  3. package/README.md +114 -55
  4. package/SECURITY.md +41 -41
  5. package/SUPPORT.md +13 -13
  6. package/build/commands/complete.js +16 -0
  7. package/build/commands/root.js +23 -31
  8. package/build/commands/uninstall.js +11 -0
  9. package/build/index.js +16 -7
  10. package/build/isterm/commandManager.js +262 -0
  11. package/build/isterm/index.js +4 -0
  12. package/build/isterm/pty.js +270 -0
  13. package/build/runtime/generator.js +23 -10
  14. package/build/runtime/parser.js +2 -2
  15. package/build/runtime/runtime.js +44 -27
  16. package/build/runtime/suggestion.js +47 -21
  17. package/build/runtime/template.js +24 -18
  18. package/build/runtime/utils.js +42 -12
  19. package/build/ui/suggestionManager.js +153 -0
  20. package/build/ui/ui-root.js +132 -63
  21. package/build/ui/ui-uninstall.js +9 -0
  22. package/build/ui/utils.js +56 -0
  23. package/build/utils/ansi.js +33 -0
  24. package/build/utils/config.js +107 -0
  25. package/build/utils/log.js +30 -0
  26. package/build/utils/shell.js +98 -0
  27. package/package.json +86 -59
  28. package/shell/bash-preexec.sh +380 -0
  29. package/shell/shellIntegration-env.zsh +9 -0
  30. package/shell/shellIntegration-login.zsh +4 -0
  31. package/shell/shellIntegration-profile.zsh +4 -0
  32. package/shell/shellIntegration-rc.zsh +58 -0
  33. package/shell/shellIntegration.bash +104 -0
  34. package/shell/shellIntegration.fish +19 -0
  35. package/shell/shellIntegration.ps1 +24 -0
  36. package/shell/shellIntegration.xsh +29 -0
  37. package/build/commands/bind.js +0 -12
  38. package/build/ui/input.js +0 -55
  39. package/build/ui/suggestions.js +0 -84
  40. package/build/ui/ui-bind.js +0 -64
  41. package/build/utils/bindings.js +0 -144
  42. package/build/utils/cache.js +0 -21
  43. package/shell/key-bindings-powershell.ps1 +0 -27
  44. package/shell/key-bindings-pwsh.ps1 +0 -27
  45. package/shell/key-bindings.bash +0 -7
  46. package/shell/key-bindings.fish +0 -8
  47. package/shell/key-bindings.zsh +0 -10
@@ -1,71 +1,140 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
- import React, { useCallback, useEffect, useState } from "react";
4
- import { Text, Box, render as inkRender, measureElement, useInput, useApp } from "ink";
5
- import wrapAnsi from "wrap-ansi";
6
- import { getSuggestions } from "../runtime/runtime.js";
7
- import Suggestions from "./suggestions.js";
8
- import Input from "./input.js";
9
- const Prompt = "> ";
10
- let uiResult = undefined;
11
- function UI({ startingCommand }) {
12
- const { exit } = useApp();
13
- const [isExiting, setIsExiting] = useState(false);
14
- const [command, setCommand] = useState(startingCommand);
15
- const [activeSuggestion, setActiveSuggestion] = useState();
16
- const [tabCompletionDropSize, setTabCompletionDropSize] = useState(0);
17
- const [suggestions, setSuggestions] = useState([]);
18
- const [windowWidth, setWindowWidth] = useState(500);
19
- const leftPadding = getLeftPadding(windowWidth, command);
20
- const measureRef = useCallback((node) => {
21
- if (node !== null) {
22
- const { width } = measureElement(node);
23
- setWindowWidth(width);
3
+ import readline from "node:readline";
4
+ import ansi from "ansi-escapes";
5
+ import chalk from "chalk";
6
+ import log from "../utils/log.js";
7
+ import { Shell } from "../utils/shell.js";
8
+ import isterm from "../isterm/index.js";
9
+ import { eraseLinesBelow } from "../utils/ansi.js";
10
+ import { SuggestionManager, MAX_LINES } from "./suggestionManager.js";
11
+ export const renderConfirmation = (live) => {
12
+ const statusMessage = live ? chalk.green("live") : chalk.red("not found");
13
+ return `inshellisense session [${statusMessage}]\n`;
14
+ };
15
+ export const render = async (shell, underTest, parentTermExit) => {
16
+ const term = await isterm.spawn({ shell, rows: process.stdout.rows, cols: process.stdout.columns, underTest });
17
+ const suggestionManager = new SuggestionManager(term, shell);
18
+ let hasActiveSuggestions = false;
19
+ let previousSuggestionsRows = 0;
20
+ if (process.stdin.isTTY)
21
+ process.stdin.setRawMode(true);
22
+ readline.emitKeypressEvents(process.stdin);
23
+ const writeOutput = (data) => {
24
+ log.debug({ msg: "writing data", data });
25
+ process.stdout.write(data);
26
+ };
27
+ writeOutput(ansi.clearTerminal);
28
+ term.onData((data) => {
29
+ if (hasActiveSuggestions) {
30
+ // Considers when data includes newlines which have shifted the cursor position downwards
31
+ const newlines = Math.max((data.match(/\r/g) || []).length, (data.match(/\n/g) || []).length);
32
+ const linesOfInterest = MAX_LINES + newlines;
33
+ if (term.getCursorState().remainingLines <= MAX_LINES) {
34
+ // handles when suggestions get loaded before shell output so you need to always clear below output as a precaution
35
+ if (term.getCursorState().remainingLines != 0) {
36
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + eraseLinesBelow(linesOfInterest + 1) + ansi.cursorRestorePosition);
37
+ }
38
+ writeOutput(data +
39
+ ansi.cursorHide +
40
+ ansi.cursorSavePosition +
41
+ ansi.cursorPrevLine.repeat(linesOfInterest) +
42
+ term.getCells(linesOfInterest, "above") +
43
+ ansi.cursorRestorePosition +
44
+ ansi.cursorShow);
45
+ }
46
+ else {
47
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + eraseLinesBelow(linesOfInterest + 1) + ansi.cursorRestorePosition + ansi.cursorShow + data);
48
+ }
49
+ }
50
+ else {
51
+ writeOutput(data);
24
52
  }
25
- }, []);
26
- useInput((input, key) => {
27
- if (key.ctrl && input.toLowerCase() == "d") {
28
- uiResult = undefined;
29
- exit();
53
+ process.nextTick(async () => {
54
+ // validate result to prevent stale suggestion being provided
55
+ const suggestion = suggestionManager.validate(await suggestionManager.render(term.getCursorState().remainingLines));
56
+ const commandState = term.getCommandState();
57
+ if (suggestion.data != "" && commandState.cursorTerminated && !commandState.hasOutput) {
58
+ if (hasActiveSuggestions) {
59
+ if (term.getCursorState().remainingLines < MAX_LINES) {
60
+ writeOutput(ansi.cursorHide +
61
+ ansi.cursorSavePosition +
62
+ ansi.cursorPrevLine.repeat(MAX_LINES) +
63
+ term.getCells(MAX_LINES, "above") +
64
+ ansi.cursorRestorePosition +
65
+ ansi.cursorSavePosition +
66
+ ansi.cursorUp() +
67
+ suggestion.data +
68
+ ansi.cursorRestorePosition +
69
+ ansi.cursorShow);
70
+ }
71
+ else {
72
+ const offset = MAX_LINES - suggestion.rows;
73
+ writeOutput(ansi.cursorHide +
74
+ ansi.cursorSavePosition +
75
+ eraseLinesBelow(MAX_LINES) +
76
+ (offset > 0 ? ansi.cursorUp(offset) : "") +
77
+ suggestion.data +
78
+ ansi.cursorRestorePosition +
79
+ ansi.cursorShow);
80
+ }
81
+ }
82
+ else {
83
+ if (term.getCursorState().remainingLines < MAX_LINES) {
84
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + ansi.cursorUp() + suggestion.data + ansi.cursorRestorePosition + ansi.cursorShow);
85
+ }
86
+ else {
87
+ writeOutput(ansi.cursorHide +
88
+ ansi.cursorSavePosition +
89
+ ansi.cursorNextLine.repeat(suggestion.rows) +
90
+ suggestion.data +
91
+ ansi.cursorRestorePosition +
92
+ ansi.cursorShow);
93
+ }
94
+ }
95
+ hasActiveSuggestions = true;
96
+ }
97
+ else {
98
+ if (hasActiveSuggestions) {
99
+ if (term.getCursorState().remainingLines <= MAX_LINES) {
100
+ writeOutput(ansi.cursorHide +
101
+ ansi.cursorSavePosition +
102
+ ansi.cursorPrevLine.repeat(MAX_LINES) +
103
+ term.getCells(MAX_LINES, "above") +
104
+ ansi.cursorRestorePosition +
105
+ ansi.cursorShow);
106
+ }
107
+ else {
108
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + eraseLinesBelow(MAX_LINES) + ansi.cursorRestorePosition + ansi.cursorShow);
109
+ }
110
+ }
111
+ hasActiveSuggestions = false;
112
+ }
113
+ previousSuggestionsRows = suggestion.rows;
114
+ });
115
+ });
116
+ process.stdin.on("keypress", (...keyPress) => {
117
+ const press = keyPress[1];
118
+ const inputHandled = suggestionManager.update(press);
119
+ if (previousSuggestionsRows > 0 && inputHandled) {
120
+ term.noop();
30
121
  }
31
- if (key.return) {
32
- setIsExiting(true);
122
+ else if (!inputHandled) {
123
+ if (press.name == "backspace" && (shell === Shell.Pwsh || shell === Shell.Powershell || shell === Shell.Cmd)) {
124
+ term.write("\u007F");
125
+ }
126
+ else {
127
+ term.write(press.sequence);
128
+ }
33
129
  }
34
130
  });
35
- useEffect(() => {
36
- if (isExiting) {
37
- uiResult = command;
38
- exit();
131
+ term.onExit(({ exitCode }) => {
132
+ if (parentTermExit && process.ppid) {
133
+ process.kill(process.ppid);
39
134
  }
40
- }, [isExiting]);
41
- useEffect(() => {
42
- getSuggestions(command).then((suggestions) => {
43
- setSuggestions(suggestions?.suggestions ?? []);
44
- setTabCompletionDropSize(suggestions?.charactersToDrop ?? 0);
45
- });
46
- }, [command]);
47
- if (isExiting) {
48
- return (React.createElement(Text, null,
49
- Prompt,
50
- command));
51
- }
52
- return (React.createElement(Box, { flexDirection: "column", ref: measureRef },
53
- React.createElement(Box, null,
54
- React.createElement(Text, null,
55
- React.createElement(Input, { value: command, setValue: setCommand, prompt: Prompt, activeSuggestion: activeSuggestion, tabCompletionDropSize: tabCompletionDropSize }))),
56
- React.createElement(Suggestions, { leftPadding: leftPadding, setActiveSuggestion: setActiveSuggestion, suggestions: suggestions })));
57
- }
58
- export const render = async (command) => {
59
- uiResult = undefined;
60
- const { waitUntilExit } = inkRender(React.createElement(UI, { startingCommand: command ?? "" }));
61
- await waitUntilExit();
62
- return uiResult;
63
- };
64
- function getLeftPadding(windowWidth, command) {
65
- const wrappedText = wrapAnsi(command + "", windowWidth, {
66
- trim: false,
67
- hard: true,
135
+ process.exit(exitCode);
68
136
  });
69
- const lines = wrappedText.split("\n");
70
- return (lines.length - 1) * windowWidth + lines[lines.length - 1].length + Prompt.length;
71
- }
137
+ process.stdout.on("resize", () => {
138
+ term.resize(process.stdout.columns, process.stdout.rows);
139
+ });
140
+ };
@@ -0,0 +1,9 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import chalk from "chalk";
4
+ import { deleteCacheFolder } from "../utils/config.js";
5
+ export const render = async () => {
6
+ deleteCacheFolder();
7
+ process.stdout.write(chalk.green("✓") + " successfully deleted the .inshellisense cache folder \n");
8
+ process.stdout.write(chalk.magenta("•") + " to complete the uninstall, run the the command: " + chalk.underline(chalk.cyan("npm uninstall -g @microsoft/inshellisense")) + "\n");
9
+ };
@@ -0,0 +1,56 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import ansi from "ansi-escapes";
4
+ import wrapAnsi from "wrap-ansi";
5
+ import chalk from "chalk";
6
+ import wcwidth from "wcwidth";
7
+ /**
8
+ * Renders a box around the given rows
9
+ * @param rows the text content to be included in the box, must be <= width - 2
10
+ * @param width the max width of a row
11
+ * @param x the column to start the box at
12
+ */
13
+ export const renderBox = (rows, width, x, borderColor) => {
14
+ const result = [];
15
+ const setColor = (text) => (borderColor ? chalk.hex(borderColor).apply(text) : text);
16
+ result.push(ansi.cursorTo(x) + setColor("┌" + "─".repeat(width - 2) + "┐") + ansi.cursorTo(x));
17
+ rows.forEach((row) => {
18
+ result.push(ansi.cursorDown() + setColor("│") + row + setColor("│") + ansi.cursorTo(x));
19
+ });
20
+ result.push(ansi.cursorDown() + setColor("└" + "─".repeat(width - 2) + "┘") + ansi.cursorTo(x));
21
+ return result.join("") + ansi.cursorUp(rows.length + 1);
22
+ };
23
+ export const truncateMultilineText = (description, width, maxHeight) => {
24
+ const wrappedText = wrapAnsi(description, width, {
25
+ trim: false,
26
+ hard: true,
27
+ });
28
+ const lines = wrappedText.split("\n");
29
+ const truncatedLines = lines.slice(0, maxHeight);
30
+ if (lines.length > maxHeight) {
31
+ truncatedLines[maxHeight - 1] = [...truncatedLines[maxHeight - 1]].slice(0, -1).join("") + "…";
32
+ }
33
+ return truncatedLines.map((line) => line.padEnd(width));
34
+ };
35
+ const wcPadEnd = (text, width, char = " ") => text + char.repeat(Math.max(width - wcwidth(text), 0));
36
+ const wcPoints = (text, length) => {
37
+ const points = [...text];
38
+ const accPoints = [];
39
+ let accWidth = 0;
40
+ for (const point of points) {
41
+ const width = wcwidth(point);
42
+ if (width + accWidth > length) {
43
+ return wcwidth(accPoints.join("")) < length ? [accPoints.join(""), true] : [accPoints.slice(0, -1).join(""), true];
44
+ }
45
+ accPoints.push(point);
46
+ accWidth += width;
47
+ }
48
+ return [accPoints.join(""), false];
49
+ };
50
+ /**
51
+ * Truncates the text to the given width
52
+ */
53
+ export const truncateText = (text, width) => {
54
+ const [points, truncated] = wcPoints(text, width);
55
+ return !truncated ? wcPadEnd(text, width) : wcPadEnd(points + "…", width);
56
+ };
@@ -0,0 +1,33 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ const ESC = "\u001B";
4
+ const CSI = ESC + "[";
5
+ const OSC = "\u001B]";
6
+ const BEL = "\u0007";
7
+ export const IsTermOscPs = 6973;
8
+ const IS_OSC = OSC + IsTermOscPs + ";";
9
+ export var IstermOscPt;
10
+ (function (IstermOscPt) {
11
+ IstermOscPt["PromptStarted"] = "PS";
12
+ IstermOscPt["PromptEnded"] = "PE";
13
+ IstermOscPt["CurrentWorkingDirectory"] = "CWD";
14
+ })(IstermOscPt || (IstermOscPt = {}));
15
+ export const IstermPromptStart = IS_OSC + IstermOscPt.PromptStarted + BEL;
16
+ export const IstermPromptEnd = IS_OSC + IstermOscPt.PromptEnded + BEL;
17
+ export const cursorHide = CSI + "?25l";
18
+ export const cursorShow = CSI + "?25h";
19
+ export const cursorNextLine = CSI + "E";
20
+ export const eraseLine = CSI + "2K";
21
+ export const cursorBackward = (count = 1) => CSI + count + "D";
22
+ export const cursorTo = ({ x, y }) => {
23
+ return CSI + (y ?? "") + ";" + (x ?? "") + "H";
24
+ };
25
+ export const deleteLinesBelow = (count = 1) => {
26
+ return [...Array(count).keys()].map(() => CSI + "B" + CSI + "M").join("");
27
+ };
28
+ export const deleteLine = (count = 1) => CSI + count + "M";
29
+ export const scrollUp = (count = 1) => CSI + count + "S";
30
+ export const scrollDown = (count = 1) => CSI + count + "T";
31
+ export const eraseLinesBelow = (count = 1) => {
32
+ return [...Array(count).keys()].map(() => cursorNextLine + eraseLine).join("");
33
+ };
@@ -0,0 +1,107 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import fs from "node:fs";
6
+ import fsAsync from "node:fs/promises";
7
+ import toml from "toml";
8
+ import _Ajv from "ajv";
9
+ const Ajv = _Ajv;
10
+ const ajv = new Ajv();
11
+ const bindingSchema = {
12
+ type: "object",
13
+ nullable: true,
14
+ properties: {
15
+ shift: { type: "boolean", nullable: true },
16
+ control: { type: "boolean", nullable: true },
17
+ key: { type: "string" },
18
+ },
19
+ required: ["key"],
20
+ };
21
+ const promptPatternsSchema = {
22
+ type: "array",
23
+ nullable: true,
24
+ items: {
25
+ type: "object",
26
+ properties: {
27
+ regex: { type: "string" },
28
+ postfix: { type: "string" },
29
+ },
30
+ required: ["regex", "postfix"],
31
+ },
32
+ };
33
+ const configSchema = {
34
+ type: "object",
35
+ nullable: true,
36
+ properties: {
37
+ bindings: {
38
+ type: "object",
39
+ nullable: true,
40
+ properties: {
41
+ nextSuggestion: bindingSchema,
42
+ previousSuggestion: bindingSchema,
43
+ dismissSuggestions: bindingSchema,
44
+ acceptSuggestion: bindingSchema,
45
+ },
46
+ },
47
+ prompt: {
48
+ type: "object",
49
+ nullable: true,
50
+ properties: {
51
+ bash: promptPatternsSchema,
52
+ pwsh: promptPatternsSchema,
53
+ powershell: promptPatternsSchema,
54
+ xonsh: promptPatternsSchema,
55
+ },
56
+ },
57
+ },
58
+ additionalProperties: false,
59
+ };
60
+ const configFile = ".inshellisenserc";
61
+ const cachePath = path.join(os.homedir(), ".inshellisense");
62
+ const configPath = path.join(os.homedir(), configFile);
63
+ let globalConfig = {
64
+ bindings: {
65
+ nextSuggestion: { key: "down" },
66
+ previousSuggestion: { key: "up" },
67
+ acceptSuggestion: { key: "tab" },
68
+ dismissSuggestions: { key: "escape" },
69
+ },
70
+ };
71
+ export const getConfig = () => globalConfig;
72
+ export const loadConfig = async (program) => {
73
+ if (fs.existsSync(configPath)) {
74
+ let config;
75
+ try {
76
+ config = toml.parse((await fsAsync.readFile(configPath)).toString());
77
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
+ }
79
+ catch (e) {
80
+ program.error(`${configFile} is invalid toml. Parsing error on line ${e.line}, column ${e.column}: ${e.message}`);
81
+ }
82
+ const isValid = ajv.validate(configSchema, config);
83
+ if (!isValid) {
84
+ program.error(`${configFile} is invalid: ${ajv.errorsText()}`);
85
+ }
86
+ globalConfig = {
87
+ bindings: {
88
+ nextSuggestion: config?.bindings?.nextSuggestion ?? globalConfig.bindings.nextSuggestion,
89
+ previousSuggestion: config?.bindings?.previousSuggestion ?? globalConfig.bindings.previousSuggestion,
90
+ acceptSuggestion: config?.bindings?.acceptSuggestion ?? globalConfig.bindings.acceptSuggestion,
91
+ dismissSuggestions: config?.bindings?.dismissSuggestions ?? globalConfig.bindings.dismissSuggestions,
92
+ },
93
+ prompt: {
94
+ bash: config.prompt?.bash,
95
+ powershell: config.prompt?.powershell,
96
+ xonsh: config.prompt?.xonsh,
97
+ pwsh: config.prompt?.pwsh,
98
+ },
99
+ };
100
+ }
101
+ };
102
+ export const deleteCacheFolder = async () => {
103
+ const cliConfigPath = path.join(os.homedir(), cachePath);
104
+ if (fs.existsSync(cliConfigPath)) {
105
+ fs.rmSync(cliConfigPath, { recursive: true });
106
+ }
107
+ };
@@ -0,0 +1,30 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import fs from "node:fs";
6
+ import fsAsync from "node:fs/promises";
7
+ const logFolder = path.join(os.homedir(), ".inshellisense");
8
+ const logTarget = path.join(logFolder, "inshellisense.log");
9
+ let logEnabled = false;
10
+ const reset = async () => {
11
+ if (!fs.existsSync(logTarget)) {
12
+ await fsAsync.mkdir(logFolder, { recursive: true });
13
+ }
14
+ await fsAsync.writeFile(logTarget, "");
15
+ };
16
+ const debug = (content) => {
17
+ if (!logEnabled) {
18
+ return;
19
+ }
20
+ fs.appendFile(logTarget, JSON.stringify(content) + "\n", (err) => {
21
+ if (err != null) {
22
+ throw err;
23
+ }
24
+ });
25
+ };
26
+ export const enable = async () => {
27
+ await reset();
28
+ logEnabled = true;
29
+ };
30
+ export default { reset, debug, enable };
@@ -0,0 +1,98 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ import process from "node:process";
4
+ import find from "find-process";
5
+ import path from "node:path";
6
+ import which from "which";
7
+ import fs from "node:fs";
8
+ import url from "node:url";
9
+ import os from "node:os";
10
+ import fsAsync from "node:fs/promises";
11
+ export var Shell;
12
+ (function (Shell) {
13
+ Shell["Bash"] = "bash";
14
+ Shell["Powershell"] = "powershell";
15
+ Shell["Pwsh"] = "pwsh";
16
+ Shell["Zsh"] = "zsh";
17
+ Shell["Fish"] = "fish";
18
+ Shell["Cmd"] = "cmd";
19
+ Shell["Xonsh"] = "xonsh";
20
+ })(Shell || (Shell = {}));
21
+ export const supportedShells = [
22
+ Shell.Bash,
23
+ process.platform == "win32" ? Shell.Powershell : null,
24
+ Shell.Pwsh,
25
+ Shell.Zsh,
26
+ Shell.Fish,
27
+ process.platform == "win32" ? Shell.Cmd : null,
28
+ Shell.Xonsh,
29
+ ].filter((shell) => shell != null);
30
+ export const userZdotdir = process.env?.ZDOTDIR ?? os.homedir() ?? `~`;
31
+ export const zdotdir = path.join(os.tmpdir(), `is-zsh`);
32
+ const configFolder = ".inshellisense";
33
+ export const setupBashPreExec = async () => {
34
+ const shellFolderPath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), "..", "..", "shell");
35
+ const globalConfigPath = path.join(os.homedir(), configFolder);
36
+ if (!fs.existsSync(globalConfigPath)) {
37
+ await fsAsync.mkdir(globalConfigPath, { recursive: true });
38
+ }
39
+ await fsAsync.cp(path.join(shellFolderPath, "bash-preexec.sh"), path.join(globalConfigPath, "bash-preexec.sh"));
40
+ };
41
+ export const setupZshDotfiles = async () => {
42
+ const shellFolderPath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), "..", "..", "shell");
43
+ await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-rc.zsh"), path.join(zdotdir, ".zshrc"));
44
+ await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-profile.zsh"), path.join(zdotdir, ".zprofile"));
45
+ await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-env.zsh"), path.join(zdotdir, ".zshenv"));
46
+ await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-login.zsh"), path.join(zdotdir, ".zlogin"));
47
+ };
48
+ export const inferShell = async () => {
49
+ try {
50
+ const name = path.parse(process.env.SHELL ?? "").name;
51
+ const shellName = supportedShells.find((shell) => name.includes(shell));
52
+ if (shellName)
53
+ return shellName;
54
+ }
55
+ catch {
56
+ /* empty */
57
+ }
58
+ const processResult = (await find("pid", process.ppid)).at(0);
59
+ const name = processResult?.name;
60
+ return name != null ? supportedShells.find((shell) => name.includes(shell)) : undefined;
61
+ };
62
+ export const gitBashPath = async () => {
63
+ const gitBashPaths = await getGitBashPaths();
64
+ for (const gitBashPath of gitBashPaths) {
65
+ if (fs.existsSync(gitBashPath)) {
66
+ return gitBashPath;
67
+ }
68
+ }
69
+ throw new Error("unable to find a git bash executable installed");
70
+ };
71
+ export const getPythonPath = async () => {
72
+ return await which("python", { nothrow: true });
73
+ };
74
+ const getGitBashPaths = async () => {
75
+ const gitDirs = new Set();
76
+ const gitExePath = await which("git.exe", { nothrow: true });
77
+ if (gitExePath) {
78
+ const gitExeDir = path.dirname(gitExePath);
79
+ gitDirs.add(path.resolve(gitExeDir, "../.."));
80
+ }
81
+ const addValid = (set, value) => {
82
+ if (value)
83
+ set.add(value);
84
+ };
85
+ // Add common git install locations
86
+ addValid(gitDirs, process.env["ProgramW6432"]);
87
+ addValid(gitDirs, process.env["ProgramFiles"]);
88
+ addValid(gitDirs, process.env["ProgramFiles(X86)"]);
89
+ addValid(gitDirs, `${process.env["LocalAppData"]}\\Program`);
90
+ const gitBashPaths = [];
91
+ for (const gitDir of gitDirs) {
92
+ gitBashPaths.push(`${gitDir}\\Git\\bin\\bash.exe`, `${gitDir}\\Git\\usr\\bin\\bash.exe`, `${gitDir}\\usr\\bin\\bash.exe`);
93
+ }
94
+ // Add special installs that don't follow the standard directory structure
95
+ gitBashPaths.push(`${process.env["UserProfile"]}\\scoop\\apps\\git\\current\\bin\\bash.exe`);
96
+ gitBashPaths.push(`${process.env["UserProfile"]}\\scoop\\apps\\git-with-openssh\\current\\bin\\bash.exe`);
97
+ return gitBashPaths;
98
+ };