Implementation of a persistent shell #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This turned out to be harder to do than I thought and the solution here feels a tad hacky, but overall not too bad.
Because we want to run the commands in a persistent shell, and shells are for humans to write prompts in, it's actually not super easy to know when the last executed command has finished. We create a shell process by spawing
shand then all the 'real' commands are done by writing to stdin and reading from stdout/stderr (just like if you're using a terminal to work with a shell). In a tty, you get a prompt printed when the last command has finished executing, but this doesn't happen when runningshnot in a tty (such as spawing a child process from node.js).To work around it, we create a unique id for each command, and then
echothat id to stdout after the main command. We can listen on stdout and receive the real command's output, and when we see that unique id (which should never accidentally appear in the real output), we know to stop reading and return everything else to the caller.In addition to this, we use
echo $?to retrieve the exit code of the main command. There's a bit of string manipulation to get all the relevant output back out of the stdout stream.