Introduction
In this blog post, we’ll explore how to create a TerminalWrapper class in a Visual Studio Code (VSCode) extension. The TerminalWrapper facilitates executing system commands within the integrated terminal, making it useful for various extension scenarios.
The TerminalWrapper
Class
Properties
executeResultFileName
:- A string containing the name of the log file where command execution results will be recorded.
executeLogFileName
:- A string containing the name of the log file where detailed information about command execution will be stored.
setEncodingUtf8
:- A PowerShell command that sets the output encoding to UTF-8.
Constructor
The TerminalWrapper
class is initialized with two parameters:
outputPathLog
:- A string representing the output path for log files.
terminalName
:- A string specifying the name of the terminal.
Methods
executeCommandWithoutLog
:- This method executes a command in the specified terminal without logging the details.
- It first checks if a terminal with the given name exists. If not, it creates a new one.
- The method shows the terminal and sends the provided
command
to it. - After executing the command, it sends an exit command (
; exit
) to close the terminal. - The method returns a promise that resolves with the terminal’s exit status or rejects with an error message if the status is undefined.
executeCommand
:- This method executes a command in the specified terminal.
- If the terminal with the given name does not exist, it creates a new one.
- The command is executed with the following steps:
$share = ${this.setEncodingUtf8} ${command} | Tee-Object -file ${this.executeLogFilePath};
: The command is executed, and its output is logged to theexecuteLogFilePath
.if($?){'1' > ${this.executeResultFilePath}}else{'0' > ${this.executeResultFilePath}};
: The result of the command execution (1 for success, 0 for failure) is recorded in theexecuteResultFilePath
.exit
: The terminal is closed.- Handling Terminal Closure:
- When the terminal is closed, the
onDidCloseTerminal
event is triggered. - The method reads the content of the
executeResultFilePath
. - If the terminal exit status is defined, it resolves the promise with
true
orfalse
based on the read status. - If the terminal exit status is undefined, it rejects the promise with the message «Terminal exited with undefined status.»
Usage and Purpose
The TerminalWrapper class encapsulates terminal-related functionality, allowing VSCode extensions to execute commands seamlessly. It handles terminal creation, command execution, and exit status retrieval.