Skip to content

Commit

Permalink
Merge pull request #39 from guicassolato/save-env-in-memory
Browse files Browse the repository at this point in the history
cleanup temp files created in /tmp
  • Loading branch information
guicassolato committed Jan 9, 2023
2 parents e491d20 + 1b8c864 commit 592e721
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 25 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ This file is structured according to the [Keep a Changelog](http://keepachangelo

## [Unreleased]

### Changed

- Automaticaly cleanup temp files created in /tmp to carry out the envs across code blocks when running in separate shells in the background
- Setting `tothom.saveEnvToTmp` is now called `tothom.propagateEnv` and it's enabled by default

## [v0.5.1] - 2022-01-08

### Fixed
Expand Down
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,20 @@ New preview windows and preview windows not yet bound to a terminal will execute
![Run in background](./resources/run-in-background.gif)

Keep in mind that, with this option enabled, each execution of a code block will run in an independent shell (separate child process).
To set and re-use environment variable values across multiple code blocks, enable the `tothom.saveEnvToTmp` configuration option.
To set and re-use environment variable values across multiple code blocks, enable the `tothom.propagateEnv` configuration option.

This option is ignored if the preview is currently bound to a terminal (e.g. by using the 'Select terminal' command).
If needed, clear the current binding of a preview to a terminal after enabling this option by activating the preview window and executing the command <kbd>⇧ ⌘ P</kbd> _Tothom: Clear terminal selection_.

## Extension Settings

| Setting | Description | Options/Default |
|-----------------------------------|-----------------------------------------------------------------------------------------------------------------|-----------------------------------|
| `tothom.bracketedPasteMode` | Apply bracketed paste sequences on commands sent to terminal | `true` (default), `false` |
| `tothom.colorScheme` | Color scheme of the preview panel | `auto` (default), `light`, `dark` |
| `tothom.runInTerminalLabel` | Label of the _Run in terminal_ button | Default: `▶️` |
| `tothom.runInBackgroundByDefault` | Default to running code blocks in a separate child process in the background instead of the integrated terminal | `true`, `false` (default) |
| `tothom.saveEnvToTmp` | Save and restore environment variables to temporary files around each code block execution | `true`, `false` (default) |
| Setting | Description | Options/Default |
|-----------------------------------|------------------------------------------------------------------------------------------------------------------|-----------------------------------|
| `tothom.bracketedPasteMode` | Apply bracketed paste sequences on commands sent to terminal | `true` (default), `false` |
| `tothom.colorScheme` | Color scheme of the preview panel | `auto` (default), `light`, `dark` |
| `tothom.runInTerminalLabel` | Label of the _Run in terminal_ button | Default: `▶️` |
| `tothom.runInBackgroundByDefault` | Default to running code blocks in a separate child process in the background instead of the integrated terminal | `true`, `false` (default) |
| `tothom.propagateEnv` | Propagates environment variables across executions when running code blocks in separate shells in the background | `true` (default), `false` |

## Limitations

Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"order": 10
},
"tothom.runInBackgroundByDefault": {
"markdownDescription": "Default to running code blocks in a separate shell in the background instead of in an integrated terminal window. Outputs of the executions are appended to the preview window.\n\nThis setting is ignored if the preview is bound to a terminal (e.g. by using the 'Select terminal' command).\n\nTo be able to set and re-use environment variables across code blocks when this option is active, activate as well `#tothom.saveEnvToTmp#`.",
"markdownDescription": "Default to running code blocks in a separate shell in the background instead of in an integrated terminal window. Outputs of the executions are appended to the preview window.\n\nThis setting is ignored if the preview is bound to a terminal (e.g. by using the 'Select terminal' command).\n\nTo be able to set and re-use environment variables across code blocks when this option is active, activate as well `#tothom.propagateEnv#`.",
"type": "boolean",
"default": false,
"order": 40
Expand All @@ -72,10 +72,10 @@
"default": "▶️",
"order": 20
},
"tothom.saveEnvToTmp": {
"markdownDescription": "Save and restore environment variables to temporary files (`/tmp/tothom-*.env`) around each code block execution. Only applies when `#tothom.runInBackgroundByDefault#` is enabled.",
"tothom.propagateEnv": {
"markdownDescription": "Propagates environment variable values across code block executions.\n\nIt requires access to read/write temporary files in `/tmp`.\n\nOnly applies when `#tothom.runInBackgroundByDefault#` is enabled.",
"type": "boolean",
"default": false,
"default": true,
"order": 50
}
}
Expand Down
4 changes: 3 additions & 1 deletion samples/tothom.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ export TIME="$(date)"
echo "Time was: $TIME\nTime now is: $(date)"
```

> **Note:** `$TIME` above will be undefined when running the blocks in separate shells in the background and the `tothom.saveEnvToTmp` setting is disabled.
```sh
unset TIME
```

## Compatibility

Expand Down
2 changes: 1 addition & 1 deletion src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const tothomOptions = (): TothomOptions => {
runInTerminalLabel: config.get('runInTerminalLabel')
},
runInBackgroundByDefault: config.get('runInBackgroundByDefault'),
saveEnvToTmp: config.get('saveEnvToTmp')
propagateEnv: config.get('propagateEnv')
};
};

Expand Down
27 changes: 16 additions & 11 deletions src/tothom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,14 @@ export interface TothomOptions {
bracketedPasteMode?: boolean;
engineOptions?: EngineOptions;
runInBackgroundByDefault?: boolean;
saveEnvToTmp?: boolean;
propagateEnv?: boolean;
};

interface TothomPreview {
uri: vscode.Uri;
panel: vscode.WebviewPanel;
terminal?: vscode.Terminal;
env?: string;
}

export class Tothom {
Expand Down Expand Up @@ -247,7 +248,7 @@ export class Tothom {
let command = terminal.decodeTerminalCommand(encodedCommand);

if (preview.terminal === undefined && this.options?.runInBackgroundByDefault) {
return this.runInBackground(command, uri, codeId, preview.panel.webview);
return this.runInBackground(command, uri, codeId, preview);
}

const term = terminal.findTerminal(preview.terminal?.name) || terminal.findOrCreateTerminal(uri.toString());
Expand All @@ -261,9 +262,10 @@ export class Tothom {
term.show();
};

private runInBackground = (command: string, uri: vscode.Uri, codeId: string | null, webview: vscode.Webview) => {
private runInBackground = (command: string, uri: vscode.Uri, codeId: string | null, preview: TothomPreview) => {
const workspaceRoots: readonly vscode.WorkspaceFolder[] | undefined = vscode.workspace.workspaceFolders;
const workspaceRoot: string = (workspaceRoots?.length) ? workspaceRoots[0].uri.fsPath || '' : '';
const envFile = `/tmp/tothom-${createHash('sha256').update(uri.fsPath).digest('hex').slice(0, 7)}.env`;

const callback = (error: ExecException | null, stdout: string, stderr: string) => {
if (!codeId) {
Expand All @@ -275,24 +277,27 @@ export class Tothom {
return;
}

webview.postMessage({
preview.panel.webview.postMessage({
uri: uri.fsPath,
command: 'tothom.terminalOutput',
data: {
codeId: codeId,
text: stdout.length ? stdout : stderr
}
});

if (this.options?.propagateEnv) {
exec(`sed -E 's/^([^=]+)=(.*)$/export \\1="\\2"/g' ${envFile} && rm -rf ${envFile}`, { encoding: "utf8" }, (error: ExecException | null, stdout: string, stderr: string) => preview.env = stdout);
}
};

let commandWithEnv = command;
if (this.options?.saveEnvToTmp) {
const envFile = `/tmp/tothom-${createHash('sha256').update(uri.fsPath).digest('hex').slice(0, 7)}.env`;
commandWithEnv = `if [ -f ${envFile} ]; then
eval $(sed -E 's/^([^=]+)=(.*)$/export \\1="\\2"/g' ${envFile}) && rm -rf ${envFile}
fi
${command}
env > ${envFile}`;

if (this.options?.propagateEnv) {
if (preview.env?.length) {
commandWithEnv = `${preview.env}\n${commandWithEnv}`;
}
commandWithEnv += `\nenv > ${envFile}`;
}

exec(commandWithEnv, { encoding: "utf8", cwd: workspaceRoot }, callback);
Expand Down

0 comments on commit 592e721

Please sign in to comment.