@microsoft/inshellisense 0.0.1-rc.8 → 0.0.1

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.
@@ -1,151 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import { getSuggestions } from "../runtime/runtime.js";
4
- import { renderBox, truncateText, truncateMultilineText } from "./utils.js";
5
- import ansi from "ansi-escapes";
6
- import chalk from "chalk";
7
- import log from "../utils/log.js";
8
- const maxSuggestions = 5;
9
- const suggestionWidth = 40;
10
- const descriptionWidth = 30;
11
- const descriptionHeight = 5;
12
- const borderWidth = 2;
13
- const activeSuggestionBackgroundColor = "#7D56F4";
14
- export const MAX_LINES = borderWidth + Math.max(maxSuggestions, descriptionHeight);
15
- export class SuggestionManager {
16
- #term;
17
- #command;
18
- #activeSuggestionIdx;
19
- #suggestBlob;
20
- #shell;
21
- constructor(terminal, shell) {
22
- this.#term = terminal;
23
- this.#suggestBlob = { suggestions: [] };
24
- this.#command = "";
25
- this.#activeSuggestionIdx = 0;
26
- this.#shell = shell;
27
- }
28
- async _loadSuggestions() {
29
- const commandText = this.#term.getCommandState().commandText;
30
- if (!commandText) {
31
- this.#suggestBlob = undefined;
32
- this.#activeSuggestionIdx = 0;
33
- return;
34
- }
35
- if (commandText == this.#command) {
36
- return;
37
- }
38
- this.#command = commandText;
39
- const suggestionBlob = await getSuggestions(commandText, this.#term.cwd, this.#shell);
40
- this.#suggestBlob = suggestionBlob;
41
- this.#activeSuggestionIdx = 0;
42
- }
43
- _renderArgumentDescription(description, x) {
44
- if (!description)
45
- return "";
46
- return renderBox([truncateText(description, descriptionWidth - borderWidth)], descriptionWidth, x);
47
- }
48
- _renderDescription(description, x) {
49
- if (!description)
50
- return "";
51
- return renderBox(truncateMultilineText(description, descriptionWidth - borderWidth, descriptionHeight), descriptionWidth, x);
52
- }
53
- _descriptionRows(description) {
54
- if (!description)
55
- return 0;
56
- return truncateMultilineText(description, descriptionWidth - borderWidth, descriptionHeight).length;
57
- }
58
- _renderSuggestions(suggestions, activeSuggestionIdx, x) {
59
- return renderBox(suggestions.map((suggestion, idx) => {
60
- const suggestionText = `${suggestion.icon} ${suggestion.name}`.padEnd(suggestionWidth - borderWidth, " ");
61
- const truncatedSuggestion = truncateText(suggestionText, suggestionWidth - 2);
62
- return idx == activeSuggestionIdx ? chalk.bgHex(activeSuggestionBackgroundColor)(truncatedSuggestion) : truncatedSuggestion;
63
- }), suggestionWidth, x);
64
- }
65
- validate(suggestion) {
66
- const commandText = this.#term.getCommandState().commandText;
67
- return !commandText ? { data: "", rows: 0 } : suggestion;
68
- }
69
- async render(remainingLines) {
70
- await this._loadSuggestions();
71
- if (!this.#suggestBlob) {
72
- return { data: "", rows: 0 };
73
- }
74
- const { suggestions, argumentDescription } = this.#suggestBlob;
75
- const page = Math.min(Math.floor(this.#activeSuggestionIdx / maxSuggestions) + 1, Math.floor(suggestions.length / maxSuggestions) + 1);
76
- const pagedSuggestions = suggestions.filter((_, idx) => idx < page * maxSuggestions && idx >= (page - 1) * maxSuggestions);
77
- const activePagedSuggestionIndex = this.#activeSuggestionIdx % maxSuggestions;
78
- const activeDescription = pagedSuggestions.at(activePagedSuggestionIndex)?.description || argumentDescription || "";
79
- const wrappedPadding = this.#term.getCursorState().cursorX % this.#term.cols;
80
- const maxPadding = activeDescription.length !== 0 ? this.#term.cols - suggestionWidth - descriptionWidth : this.#term.cols - suggestionWidth;
81
- const swapDescription = wrappedPadding > maxPadding && activeDescription.length !== 0;
82
- const swappedPadding = swapDescription ? Math.max(wrappedPadding - descriptionWidth, 0) : wrappedPadding;
83
- const clampedLeftPadding = Math.min(Math.min(wrappedPadding, swappedPadding), maxPadding);
84
- if (suggestions.length <= this.#activeSuggestionIdx) {
85
- this.#activeSuggestionIdx = Math.max(suggestions.length - 1, 0);
86
- }
87
- if (pagedSuggestions.length == 0) {
88
- if (argumentDescription != null) {
89
- return {
90
- data: ansi.cursorHide +
91
- ansi.cursorUp(2) +
92
- ansi.cursorForward(clampedLeftPadding) +
93
- this._renderArgumentDescription(argumentDescription, clampedLeftPadding),
94
- rows: 3,
95
- };
96
- }
97
- return { data: "", rows: 0 };
98
- }
99
- const suggestionRowsUsed = pagedSuggestions.length + borderWidth;
100
- let descriptionRowsUsed = this._descriptionRows(activeDescription) + borderWidth;
101
- let rows = Math.max(descriptionRowsUsed, suggestionRowsUsed);
102
- if (rows <= remainingLines) {
103
- descriptionRowsUsed = suggestionRowsUsed;
104
- rows = suggestionRowsUsed;
105
- }
106
- const descriptionUI = ansi.cursorUp(descriptionRowsUsed - 1) +
107
- (swapDescription
108
- ? this._renderDescription(activeDescription, clampedLeftPadding)
109
- : this._renderDescription(activeDescription, clampedLeftPadding + suggestionWidth)) +
110
- ansi.cursorDown(descriptionRowsUsed - 1);
111
- const suggestionUI = ansi.cursorUp(suggestionRowsUsed - 1) +
112
- (swapDescription
113
- ? this._renderSuggestions(pagedSuggestions, activePagedSuggestionIndex, clampedLeftPadding + descriptionWidth)
114
- : this._renderSuggestions(pagedSuggestions, activePagedSuggestionIndex, clampedLeftPadding)) +
115
- ansi.cursorDown(suggestionRowsUsed - 1);
116
- const ui = swapDescription ? descriptionUI + suggestionUI : suggestionUI + descriptionUI;
117
- return {
118
- data: ansi.cursorHide + ansi.cursorForward(clampedLeftPadding) + ui + ansi.cursorShow,
119
- rows,
120
- };
121
- }
122
- update(keyPress) {
123
- const { name } = keyPress;
124
- if (!this.#suggestBlob) {
125
- return false;
126
- }
127
- if (name == "escape") {
128
- this.#suggestBlob = undefined;
129
- }
130
- else if (name == "up") {
131
- this.#activeSuggestionIdx = Math.max(0, this.#activeSuggestionIdx - 1);
132
- }
133
- else if (name == "down") {
134
- this.#activeSuggestionIdx = Math.min(this.#activeSuggestionIdx + 1, (this.#suggestBlob?.suggestions.length ?? 1) - 1);
135
- }
136
- else if (name == "tab") {
137
- const removals = "\u007F".repeat(this.#suggestBlob?.charactersToDrop ?? 0);
138
- const suggestion = this.#suggestBlob?.suggestions.at(this.#activeSuggestionIdx);
139
- const chars = suggestion?.insertValue ?? suggestion?.name + " ";
140
- if (this.#suggestBlob == null || !chars.trim() || this.#suggestBlob?.suggestions.length == 0) {
141
- return false;
142
- }
143
- this.#term.write(removals + chars);
144
- }
145
- else {
146
- return false;
147
- }
148
- log.debug({ msg: "handled keypress", ...keyPress });
149
- return true;
150
- }
151
- }
@@ -1,137 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
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) => {
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);
52
- }
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();
121
- }
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
- }
129
- }
130
- });
131
- term.onExit(({ exitCode }) => {
132
- process.exit(exitCode);
133
- });
134
- process.stdout.on("resize", () => {
135
- term.resize(process.stdout.columns, process.stdout.rows);
136
- });
137
- };
@@ -1,9 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import chalk from "chalk";
4
- import { deleteConfigFolder } from "../utils/config.js";
5
- export const render = async () => {
6
- deleteConfigFolder();
7
- process.stdout.write(chalk.green("✓") + " successfully deleted the .inshellisense config 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
- };
package/build/ui/utils.js DELETED
@@ -1,41 +0,0 @@
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
- /**
7
- * Renders a box around the given rows
8
- * @param rows the text content to be included in the box, must be <= width - 2
9
- * @param width the max width of a row
10
- * @param x the column to start the box at
11
- */
12
- export const renderBox = (rows, width, x, borderColor) => {
13
- const result = [];
14
- const setColor = (text) => (borderColor ? chalk.hex(borderColor).apply(text) : text);
15
- result.push(ansi.cursorTo(x) + setColor("┌" + "─".repeat(width - 2) + "┐") + ansi.cursorTo(x));
16
- rows.forEach((row) => {
17
- result.push(ansi.cursorDown() + setColor("│") + row + setColor("│") + ansi.cursorTo(x));
18
- });
19
- result.push(ansi.cursorDown() + setColor("└" + "─".repeat(width - 2) + "┘") + ansi.cursorTo(x));
20
- return result.join("") + ansi.cursorUp(rows.length + 1);
21
- };
22
- export const truncateMultilineText = (description, width, maxHeight) => {
23
- const wrappedText = wrapAnsi(description, width, {
24
- trim: false,
25
- hard: true,
26
- });
27
- const lines = wrappedText.split("\n");
28
- const truncatedLines = lines.slice(0, maxHeight);
29
- if (lines.length > maxHeight) {
30
- truncatedLines[maxHeight - 1] = [...truncatedLines[maxHeight - 1]].slice(0, -1).join("") + "…";
31
- }
32
- return truncatedLines.map((line) => line.padEnd(width));
33
- };
34
- /**
35
- * Truncates the text to the given width
36
- */
37
- export const truncateText = (text, width) => {
38
- const textPoints = [...text];
39
- const slicedText = textPoints.slice(0, width - 1);
40
- return slicedText.length == textPoints.length ? text.padEnd(width) : (slicedText.join("") + "…").padEnd(width);
41
- };
@@ -1,33 +0,0 @@
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
- };
@@ -1,68 +0,0 @@
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 _Ajv from "ajv";
8
- const Ajv = _Ajv;
9
- const ajv = new Ajv();
10
- const configSchema = {
11
- type: "object",
12
- properties: {
13
- promptRegex: {
14
- type: "object",
15
- properties: {
16
- bash: {
17
- type: "object",
18
- nullable: true,
19
- properties: {
20
- regex: { type: "string" },
21
- postfix: { type: "string" },
22
- },
23
- required: ["regex", "postfix"],
24
- },
25
- pwsh: {
26
- type: "object",
27
- nullable: true,
28
- properties: {
29
- regex: { type: "string" },
30
- postfix: { type: "string" },
31
- },
32
- required: ["regex", "postfix"],
33
- },
34
- powershell: {
35
- type: "object",
36
- nullable: true,
37
- properties: {
38
- regex: { type: "string" },
39
- postfix: { type: "string" },
40
- },
41
- required: ["regex", "postfix"],
42
- },
43
- },
44
- nullable: true,
45
- },
46
- },
47
- additionalProperties: false,
48
- };
49
- const configFolder = ".inshellisense";
50
- const cachePath = path.join(os.homedir(), configFolder, "config.json");
51
- let globalConfig = {};
52
- export const getConfig = () => globalConfig;
53
- export const loadConfig = async (program) => {
54
- if (fs.existsSync(cachePath)) {
55
- const config = JSON.parse((await fsAsync.readFile(cachePath)).toString());
56
- const isValid = ajv.validate(configSchema, config);
57
- if (!isValid) {
58
- program.error("inshellisense config is invalid: " + ajv.errorsText());
59
- }
60
- globalConfig = config;
61
- }
62
- };
63
- export const deleteConfigFolder = async () => {
64
- const cliConfigPath = path.join(os.homedir(), configFolder);
65
- if (fs.existsSync(cliConfigPath)) {
66
- fs.rmSync(cliConfigPath, { recursive: true });
67
- }
68
- };
@@ -1,30 +0,0 @@
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 };
@@ -1,93 +0,0 @@
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 || (Shell = {}));
20
- export const supportedShells = [
21
- Shell.Bash,
22
- process.platform == "win32" ? Shell.Powershell : null,
23
- Shell.Pwsh,
24
- Shell.Zsh,
25
- Shell.Fish,
26
- process.platform == "win32" ? Shell.Cmd : null,
27
- ].filter((shell) => shell != null);
28
- export const userZdotdir = process.env?.ZDOTDIR ?? os.homedir() ?? `~`;
29
- export const zdotdir = path.join(os.tmpdir(), `is-zsh`);
30
- const configFolder = ".inshellisense";
31
- export const setupBashPreExec = async () => {
32
- const shellFolderPath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), "..", "..", "shell");
33
- const globalConfigPath = path.join(os.homedir(), configFolder);
34
- if (!fs.existsSync(globalConfigPath)) {
35
- await fsAsync.mkdir(globalConfigPath, { recursive: true });
36
- }
37
- await fsAsync.cp(path.join(shellFolderPath, "bash-preexec.sh"), path.join(globalConfigPath, "bash-preexec.sh"));
38
- };
39
- export const setupZshDotfiles = async () => {
40
- const shellFolderPath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), "..", "..", "shell");
41
- await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-rc.zsh"), path.join(zdotdir, ".zshrc"));
42
- await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-profile.zsh"), path.join(zdotdir, ".zprofile"));
43
- await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-env.zsh"), path.join(zdotdir, ".zshenv"));
44
- await fsAsync.cp(path.join(shellFolderPath, "shellIntegration-login.zsh"), path.join(zdotdir, ".zlogin"));
45
- };
46
- export const inferShell = async () => {
47
- try {
48
- const name = path.parse(process.env.SHELL ?? "").name;
49
- const shellName = supportedShells.find((shell) => name.includes(shell));
50
- if (shellName)
51
- return shellName;
52
- }
53
- catch {
54
- /* empty */
55
- }
56
- const processResult = (await find("pid", process.ppid)).at(0);
57
- const name = processResult?.name;
58
- return name != null ? supportedShells.find((shell) => name.includes(shell)) : undefined;
59
- };
60
- export const gitBashPath = async () => {
61
- const gitBashPaths = await getGitBashPaths();
62
- for (const gitBashPath of gitBashPaths) {
63
- if (fs.existsSync(gitBashPath)) {
64
- return gitBashPath;
65
- }
66
- }
67
- throw new Error("unable to find a git bash executable installed");
68
- };
69
- const getGitBashPaths = async () => {
70
- const gitDirs = new Set();
71
- const gitExePath = await which("git.exe", { nothrow: true });
72
- if (gitExePath) {
73
- const gitExeDir = path.dirname(gitExePath);
74
- gitDirs.add(path.resolve(gitExeDir, "../.."));
75
- }
76
- const addValid = (set, value) => {
77
- if (value)
78
- set.add(value);
79
- };
80
- // Add common git install locations
81
- addValid(gitDirs, process.env["ProgramW6432"]);
82
- addValid(gitDirs, process.env["ProgramFiles"]);
83
- addValid(gitDirs, process.env["ProgramFiles(X86)"]);
84
- addValid(gitDirs, `${process.env["LocalAppData"]}\\Program`);
85
- const gitBashPaths = [];
86
- for (const gitDir of gitDirs) {
87
- gitBashPaths.push(`${gitDir}\\Git\\bin\\bash.exe`, `${gitDir}\\Git\\usr\\bin\\bash.exe`, `${gitDir}\\usr\\bin\\bash.exe`);
88
- }
89
- // Add special installs that don't follow the standard directory structure
90
- gitBashPaths.push(`${process.env["UserProfile"]}\\scoop\\apps\\git\\current\\bin\\bash.exe`);
91
- gitBashPaths.push(`${process.env["UserProfile"]}\\scoop\\apps\\git-with-openssh\\current\\bin\\bash.exe`);
92
- return gitBashPaths;
93
- };
@@ -1,13 +0,0 @@
1
- // Copyright (c) Microsoft Corporation.
2
- // Licensed under the MIT License.
3
- import url from "node:url";
4
- import path from "node:path";
5
- import fsAsync from "node:fs/promises";
6
- const __filename = url.fileURLToPath(import.meta.url);
7
- const __dirname = path.dirname(__filename);
8
- export const getVersion = async () => {
9
- const packageJsonPath = path.join(__dirname, "..", "..", "package.json");
10
- const packageJson = await fsAsync.readFile(packageJsonPath, { encoding: "utf-8" });
11
- const packageJsonParsed = JSON.parse(packageJson);
12
- return packageJsonParsed.version;
13
- };