@microsoft/inshellisense 0.0.1-rc.4 → 0.0.1-rc.6

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 (43) hide show
  1. package/README.md +23 -7
  2. package/build/commands/complete.js +15 -0
  3. package/build/commands/root.js +20 -29
  4. package/build/commands/uninstall.js +1 -1
  5. package/build/index.js +5 -6
  6. package/build/isterm/commandManager.js +217 -0
  7. package/build/isterm/index.js +4 -0
  8. package/build/isterm/pty.js +248 -0
  9. package/build/runtime/generator.js +21 -10
  10. package/build/runtime/parser.js +2 -2
  11. package/build/runtime/runtime.js +37 -23
  12. package/build/runtime/suggestion.js +34 -14
  13. package/build/runtime/template.js +24 -18
  14. package/build/runtime/utils.js +42 -12
  15. package/build/ui/input.js +7 -53
  16. package/build/ui/suggestionManager.js +139 -0
  17. package/build/ui/ui-root.js +120 -64
  18. package/build/ui/ui-uninstall.js +1 -3
  19. package/build/ui/utils.js +41 -0
  20. package/build/utils/ansi.js +56 -0
  21. package/build/utils/config.js +68 -0
  22. package/build/utils/log.js +30 -0
  23. package/build/utils/shell.js +84 -1
  24. package/package.json +12 -5
  25. package/shell/bash-preexec.sh +380 -0
  26. package/shell/shellIntegration-env.zsh +9 -0
  27. package/shell/shellIntegration-login.zsh +4 -0
  28. package/shell/shellIntegration-profile.zsh +4 -0
  29. package/shell/shellIntegration-rc.zsh +52 -0
  30. package/shell/shellIntegration.bash +65 -0
  31. package/shell/shellIntegration.fish +14 -0
  32. package/shell/shellIntegration.ps1 +17 -0
  33. package/build/commands/bind.js +0 -12
  34. package/build/ui/suggestions.js +0 -84
  35. package/build/ui/ui-bind.js +0 -69
  36. package/build/ui/ui-init.js +0 -44
  37. package/build/utils/bindings.js +0 -236
  38. package/build/utils/cache.js +0 -21
  39. package/shell/key-bindings-powershell.ps1 +0 -27
  40. package/shell/key-bindings-pwsh.ps1 +0 -27
  41. package/shell/key-bindings.bash +0 -7
  42. package/shell/key-bindings.fish +0 -8
  43. package/shell/key-bindings.zsh +0 -10
@@ -0,0 +1,139 @@
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 { parseKeystroke } from "../utils/ansi.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
+ return;
33
+ }
34
+ if (commandText == this.#command) {
35
+ return;
36
+ }
37
+ this.#command = commandText;
38
+ const suggestionBlob = await getSuggestions(commandText, this.#term.cwd, this.#shell);
39
+ this.#suggestBlob = suggestionBlob;
40
+ }
41
+ _renderArgumentDescription(description, x) {
42
+ if (!description)
43
+ return "";
44
+ return renderBox([truncateText(description, descriptionWidth - borderWidth)], descriptionWidth, x);
45
+ }
46
+ _renderDescription(description, x) {
47
+ if (!description)
48
+ return "";
49
+ return renderBox(truncateMultilineText(description, descriptionWidth - borderWidth, descriptionHeight), descriptionWidth, x);
50
+ }
51
+ _descriptionRows(description) {
52
+ if (!description)
53
+ return 0;
54
+ return truncateMultilineText(description, descriptionWidth - borderWidth, descriptionHeight).length;
55
+ }
56
+ _renderSuggestions(suggestions, activeSuggestionIdx, x) {
57
+ return renderBox(suggestions.map((suggestion, idx) => {
58
+ const suggestionText = `${suggestion.icon} ${suggestion.name}`.padEnd(suggestionWidth - borderWidth, " ");
59
+ const truncatedSuggestion = truncateText(suggestionText, suggestionWidth - 2);
60
+ return idx == activeSuggestionIdx ? chalk.bgHex(activeSuggestionBackgroundColor)(truncatedSuggestion) : truncatedSuggestion;
61
+ }), suggestionWidth, x);
62
+ }
63
+ async render(remainingLines) {
64
+ await this._loadSuggestions();
65
+ if (!this.#suggestBlob)
66
+ return { data: "", rows: 0 };
67
+ const { suggestions, argumentDescription } = this.#suggestBlob;
68
+ const page = Math.min(Math.floor(this.#activeSuggestionIdx / maxSuggestions) + 1, Math.floor(suggestions.length / maxSuggestions) + 1);
69
+ const pagedSuggestions = suggestions.filter((_, idx) => idx < page * maxSuggestions && idx >= (page - 1) * maxSuggestions);
70
+ const activePagedSuggestionIndex = this.#activeSuggestionIdx % maxSuggestions;
71
+ const activeDescription = pagedSuggestions.at(activePagedSuggestionIndex)?.description || argumentDescription || "";
72
+ const wrappedPadding = this.#term.getCursorState().cursorX % this.#term.cols;
73
+ const maxPadding = activeDescription.length !== 0 ? this.#term.cols - suggestionWidth - descriptionWidth : this.#term.cols - suggestionWidth;
74
+ const swapDescription = wrappedPadding > maxPadding && activeDescription.length !== 0;
75
+ const swappedPadding = swapDescription ? Math.max(wrappedPadding - descriptionWidth, 0) : wrappedPadding;
76
+ const clampedLeftPadding = Math.min(Math.min(wrappedPadding, swappedPadding), maxPadding);
77
+ if (suggestions.length <= this.#activeSuggestionIdx) {
78
+ this.#activeSuggestionIdx = Math.max(suggestions.length - 1, 0);
79
+ }
80
+ if (pagedSuggestions.length == 0) {
81
+ if (argumentDescription != null) {
82
+ return {
83
+ data: ansi.cursorHide +
84
+ ansi.cursorUp(2) +
85
+ ansi.cursorForward(clampedLeftPadding) +
86
+ this._renderArgumentDescription(argumentDescription, clampedLeftPadding),
87
+ rows: 3,
88
+ };
89
+ }
90
+ return { data: "", rows: 0 };
91
+ }
92
+ const suggestionRowsUsed = pagedSuggestions.length + borderWidth;
93
+ let descriptionRowsUsed = this._descriptionRows(activeDescription) + borderWidth;
94
+ let rows = Math.max(descriptionRowsUsed, suggestionRowsUsed);
95
+ if (rows <= remainingLines) {
96
+ descriptionRowsUsed = suggestionRowsUsed;
97
+ rows = suggestionRowsUsed;
98
+ }
99
+ const descriptionUI = ansi.cursorUp(descriptionRowsUsed - 1) +
100
+ (swapDescription
101
+ ? this._renderDescription(activeDescription, clampedLeftPadding)
102
+ : this._renderDescription(activeDescription, clampedLeftPadding + suggestionWidth)) +
103
+ ansi.cursorDown(descriptionRowsUsed - 1);
104
+ const suggestionUI = ansi.cursorUp(suggestionRowsUsed - 1) +
105
+ (swapDescription
106
+ ? this._renderSuggestions(pagedSuggestions, activePagedSuggestionIndex, clampedLeftPadding + descriptionWidth)
107
+ : this._renderSuggestions(pagedSuggestions, activePagedSuggestionIndex, clampedLeftPadding)) +
108
+ ansi.cursorDown(suggestionRowsUsed - 1);
109
+ const ui = swapDescription ? descriptionUI + suggestionUI : suggestionUI + descriptionUI;
110
+ return {
111
+ data: ansi.cursorHide + ansi.cursorForward(clampedLeftPadding) + ui + ansi.cursorShow,
112
+ rows,
113
+ };
114
+ }
115
+ update(input) {
116
+ const keyStroke = parseKeystroke(input);
117
+ if (keyStroke == null)
118
+ return false;
119
+ if (keyStroke == "esc") {
120
+ this.#suggestBlob = undefined;
121
+ }
122
+ else if (keyStroke == "up") {
123
+ this.#activeSuggestionIdx = Math.max(0, this.#activeSuggestionIdx - 1);
124
+ }
125
+ else if (keyStroke == "down") {
126
+ this.#activeSuggestionIdx = Math.min(this.#activeSuggestionIdx + 1, (this.#suggestBlob?.suggestions.length ?? 1) - 1);
127
+ }
128
+ else if (keyStroke == "tab") {
129
+ const removals = "\u007F".repeat(this.#suggestBlob?.charactersToDrop ?? 0);
130
+ const suggestion = this.#suggestBlob?.suggestions.at(this.#activeSuggestionIdx);
131
+ const chars = suggestion?.insertValue ?? suggestion?.name + " ";
132
+ if (this.#suggestBlob == null || !chars.trim() || this.#suggestBlob?.suggestions.length == 0) {
133
+ return false;
134
+ }
135
+ this.#term.write(removals + chars);
136
+ }
137
+ return "handled";
138
+ }
139
+ }
@@ -1,71 +1,127 @@
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);
24
- }
25
- }, []);
26
- useInput((input, key) => {
27
- if (key.ctrl && input.toLowerCase() == "d") {
28
- uiResult = undefined;
29
- exit();
3
+ import ansi from "ansi-escapes";
4
+ import chalk from "chalk";
5
+ import { inputModifier } from "./input.js";
6
+ import log from "../utils/log.js";
7
+ import isterm from "../isterm/index.js";
8
+ import { eraseLinesBelow } from "../utils/ansi.js";
9
+ import { SuggestionManager, MAX_LINES } from "./suggestionManager.js";
10
+ export const renderConfirmation = (live) => {
11
+ const statusMessage = live ? chalk.green("live") : chalk.red("not found");
12
+ return `inshellisense session [${statusMessage}]\n`;
13
+ };
14
+ export const render = async (shell) => {
15
+ const term = await isterm.spawn({ shell, rows: process.stdout.rows, cols: process.stdout.columns });
16
+ const suggestionManager = new SuggestionManager(term, shell);
17
+ let hasActiveSuggestions = false;
18
+ let previousSuggestionsRows = 0;
19
+ process.stdin.setRawMode(true);
20
+ const writeOutput = (data) => {
21
+ log.debug({ msg: "writing data", data });
22
+ process.stdout.write(data);
23
+ };
24
+ writeOutput(ansi.clearTerminal);
25
+ term.onData((data) => {
26
+ if (hasActiveSuggestions) {
27
+ // Considers when data includes newlines which have shifted the cursor position downwards
28
+ const newlines = Math.max((data.match(/\r/g) || []).length, (data.match(/\n/g) || []).length);
29
+ const linesOfInterest = MAX_LINES + newlines;
30
+ if (term.getCursorState().remainingLines <= previousSuggestionsRows) {
31
+ // handles when suggestions get loaded before shell output so you need to always clear below output as a precaution
32
+ if (term.getCursorState().remainingLines != 0) {
33
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + eraseLinesBelow(linesOfInterest + 1) + ansi.cursorRestorePosition);
34
+ }
35
+ writeOutput(data +
36
+ ansi.cursorHide +
37
+ ansi.cursorSavePosition +
38
+ ansi.cursorPrevLine.repeat(linesOfInterest) +
39
+ term.getCells(linesOfInterest, "above") +
40
+ ansi.cursorRestorePosition +
41
+ ansi.cursorShow);
42
+ }
43
+ else {
44
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + eraseLinesBelow(linesOfInterest + 1) + ansi.cursorRestorePosition + ansi.cursorShow + data);
45
+ }
30
46
  }
31
- if (key.return) {
32
- setIsExiting(true);
47
+ else {
48
+ writeOutput(data);
33
49
  }
50
+ setImmediate(async () => {
51
+ const suggestion = await suggestionManager.render(term.getCursorState().remainingLines);
52
+ const commandState = term.getCommandState();
53
+ if (suggestion.data != "" && commandState.cursorTerminated && !commandState.hasOutput) {
54
+ if (hasActiveSuggestions) {
55
+ if (term.getCursorState().remainingLines < suggestion.rows) {
56
+ writeOutput(ansi.cursorHide +
57
+ ansi.cursorSavePosition +
58
+ ansi.cursorPrevLine.repeat(MAX_LINES) +
59
+ term.getCells(MAX_LINES, "above") +
60
+ ansi.cursorRestorePosition +
61
+ ansi.cursorSavePosition +
62
+ ansi.cursorUp() +
63
+ suggestion.data +
64
+ ansi.cursorRestorePosition +
65
+ ansi.cursorShow);
66
+ }
67
+ else {
68
+ const offset = MAX_LINES - suggestion.rows;
69
+ writeOutput(ansi.cursorHide +
70
+ ansi.cursorSavePosition +
71
+ eraseLinesBelow(MAX_LINES) +
72
+ (offset > 0 ? ansi.cursorUp(offset) : "") +
73
+ suggestion.data +
74
+ ansi.cursorRestorePosition +
75
+ ansi.cursorShow);
76
+ }
77
+ }
78
+ else {
79
+ if (term.getCursorState().remainingLines < suggestion.rows) {
80
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + ansi.cursorUp() + suggestion.data + ansi.cursorRestorePosition + ansi.cursorShow);
81
+ }
82
+ else {
83
+ writeOutput(ansi.cursorHide +
84
+ ansi.cursorSavePosition +
85
+ ansi.cursorNextLine.repeat(suggestion.rows) +
86
+ suggestion.data +
87
+ ansi.cursorRestorePosition +
88
+ ansi.cursorShow);
89
+ }
90
+ }
91
+ hasActiveSuggestions = true;
92
+ }
93
+ else {
94
+ if (hasActiveSuggestions) {
95
+ if (term.getCursorState().remainingLines <= previousSuggestionsRows) {
96
+ writeOutput(ansi.cursorHide +
97
+ ansi.cursorSavePosition +
98
+ ansi.cursorPrevLine.repeat(MAX_LINES) +
99
+ term.getCells(MAX_LINES, "above") +
100
+ ansi.cursorRestorePosition +
101
+ ansi.cursorShow);
102
+ }
103
+ else {
104
+ writeOutput(ansi.cursorHide + ansi.cursorSavePosition + eraseLinesBelow(MAX_LINES) + ansi.cursorRestorePosition + ansi.cursorShow);
105
+ }
106
+ }
107
+ hasActiveSuggestions = false;
108
+ }
109
+ previousSuggestionsRows = suggestion.rows;
110
+ });
34
111
  });
35
- useEffect(() => {
36
- if (isExiting) {
37
- uiResult = command;
38
- exit();
112
+ process.stdin.on("data", (d) => {
113
+ const suggestionResult = suggestionManager.update(d);
114
+ if (previousSuggestionsRows > 0 && suggestionResult == "handled") {
115
+ term.noop();
39
116
  }
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,
117
+ else if (suggestionResult != "fully-handled") {
118
+ term.write(inputModifier(d));
119
+ }
120
+ });
121
+ term.onExit(({ exitCode }) => {
122
+ process.exit(exitCode);
68
123
  });
69
- const lines = wrappedText.split("\n");
70
- return (lines.length - 1) * windowWidth + lines[lines.length - 1].length + Prompt.length;
71
- }
124
+ process.stdout.on("resize", () => {
125
+ term.resize(process.stdout.columns, process.stdout.rows);
126
+ });
127
+ };
@@ -1,10 +1,8 @@
1
1
  // Copyright (c) Microsoft Corporation.
2
2
  // Licensed under the MIT License.
3
3
  import chalk from "chalk";
4
- import { unbindAll, deleteConfigFolder } from "../utils/bindings.js";
4
+ import { deleteConfigFolder } from "../utils/config.js";
5
5
  export const render = async () => {
6
- await unbindAll();
7
- process.stdout.write(chalk.green("✓") + " successfully uninstalled all existing bindings \n");
8
6
  deleteConfigFolder();
9
7
  process.stdout.write(chalk.green("✓") + " successfully deleted the .inshellisense config folder \n");
10
8
  process.stdout.write(chalk.magenta("•") + " to complete the uninstall, run the the command: " + chalk.underline(chalk.cyan("npm uninstall -g @microsoft/inshellisense")) + "\n");
@@ -0,0 +1,41 @@
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
+ };
@@ -0,0 +1,56 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ const ESC = "\u001B";
4
+ const CSI = "\u001B[";
5
+ const OSC = "\u001B]";
6
+ const BEL = "\u0007";
7
+ const SS3 = "\u001BO";
8
+ export const IsTermOscPs = 6973;
9
+ const IS_OSC = OSC + IsTermOscPs + ";";
10
+ export var IstermOscPt;
11
+ (function (IstermOscPt) {
12
+ IstermOscPt["PromptStarted"] = "PS";
13
+ IstermOscPt["PromptEnded"] = "PE";
14
+ IstermOscPt["CurrentWorkingDirectory"] = "CWD";
15
+ })(IstermOscPt || (IstermOscPt = {}));
16
+ export const IstermPromptStart = IS_OSC + IstermOscPt.PromptStarted + BEL;
17
+ export const IstermPromptEnd = IS_OSC + IstermOscPt.PromptEnded + BEL;
18
+ export const cursorHide = CSI + "?25l";
19
+ export const cursorShow = CSI + "?25h";
20
+ export const cursorNextLine = CSI + "E";
21
+ export const eraseLine = CSI + "2K";
22
+ export const cursorBackward = (count = 1) => CSI + count + "D";
23
+ export const cursorTo = ({ x, y }) => {
24
+ return CSI + (y ?? "") + ";" + (x ?? "") + "H";
25
+ };
26
+ export const deleteLinesBelow = (count = 1) => {
27
+ return [...Array(count).keys()].map(() => CSI + "B" + CSI + "M").join("");
28
+ };
29
+ export const deleteLine = (count = 1) => CSI + count + "M";
30
+ export const scrollUp = (count = 1) => CSI + count + "S";
31
+ export const scrollDown = (count = 1) => CSI + count + "T";
32
+ export const eraseLinesBelow = (count = 1) => {
33
+ return [...Array(count).keys()].map(() => cursorNextLine + eraseLine).join("");
34
+ };
35
+ export const parseKeystroke = (b) => {
36
+ let s;
37
+ if (b[0] > 127 && b[1] === undefined) {
38
+ b[0] -= 128;
39
+ s = "\u001B" + String(b);
40
+ }
41
+ else {
42
+ s = String(b);
43
+ }
44
+ if (s == ESC) {
45
+ return "esc";
46
+ }
47
+ else if (s == CSI + "A" || s == SS3 + "A") {
48
+ return "up";
49
+ }
50
+ else if (s == CSI + "B" || s == SS3 + "B") {
51
+ return "down";
52
+ }
53
+ else if (s == "\t") {
54
+ return "tab";
55
+ }
56
+ };
@@ -0,0 +1,68 @@
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
+ };
@@ -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 };
@@ -2,9 +2,92 @@
2
2
  // Licensed under the MIT License.
3
3
  import process from "node:process";
4
4
  import find from "find-process";
5
- import { supportedShells } from "./bindings.js";
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
+ };
6
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
+ }
7
56
  const processResult = (await find("pid", process.ppid)).at(0);
8
57
  const name = processResult?.name;
9
58
  return name != null ? supportedShells.find((shell) => name.includes(shell)) : undefined;
10
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
+ };