Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for loading / saving .env #40

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/hooks/useShell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ export function useShell(): ShellInstance {
await shell.spawn('mv', ['.jshrc', '/home/.jshrc']);
shell.mount(startFiles);

// Get .env from localStorage
const configRaw = localStorage.getItem('vslite_config');
const config = configRaw ? JSON.parse(configRaw) : {};
if (config?.env) {
await shell.fs.writeFile('.env', config.env);
}

// Setup terminal
const terminal = new Terminal({convertEol: true, theme});
const addon = new FitAddon();
Expand All @@ -62,7 +69,10 @@ export function useShell(): ShellInstance {
const watch = await shell.spawn('npx', ['-y', 'chokidar-cli', '.', '-i', '"(**/(node_modules|.git|_tmp_)**)"']);
watch.output.pipeTo(new WritableStream({
async write(data) {
const type: string = data.split(':').at(0) || ''
// Check if it is .env and read it into local storage
if (data.match(/\.env/))
await loadEnv(shell, data);
const type: string = data.split(':').at(0) || '';
if (watchReady) {
debug('Change detected: ', data);
} else if (data.includes('Watching "."')) {
Expand Down Expand Up @@ -122,3 +132,23 @@ export function useShell(): ShellInstance {

return { terminal, container, process, start };
}

async function loadEnv(shell: WebContainer, data: string) {
const configRaw = globalThis.localStorage?.vslite_config;
let config = configRaw ? JSON.parse(configRaw) : {};
debug('.env changed', data);
try {
const bContents = await shell.fs.readFile('.env');
const sContents = new TextDecoder().decode(bContents);
debug('contents', sContents);
if(!config) config = {};
config.env = sContents;
localStorage.setItem('vslite_config', JSON.stringify(config));
} catch(e) {
if (config?.env) {
delete config.env;
localStorage.setItem('vslite_config', JSON.stringify(config));
}
debug('.env file deleted', e);
}
}