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

feat: add uv to PATH when creating terminal #19

Merged
merged 8 commits into from
Dec 22, 2024
Merged
Show file tree
Hide file tree
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
29 changes: 14 additions & 15 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,12 @@ jobs:

- name: Download uv
run: |
mkdir bin
mkdir temp
mkdir -p ./assets/bin
curl -L https://github.com/astral-sh/uv/releases/download/${{ env.UV_VERSION }}/uv-x86_64-unknown-linux-gnu.tar.gz -o uv.tar.gz
tar -xzf uv.tar.gz -C ./bin
mv ./bin/uv-x86_64-unknown-linux-gnu/uv ./assets/uv
rm -rf ./bin/uv-x86_64-unknown-linux-gnu
ls -alF ./bin
ls -alF ./assets
tar -xzf uv.tar.gz -C ./temp
mv ./temp/uv-x86_64-unknown-linux-gnu/uv ./assets/bin/uv
rm -rf ./temp/uv-x86_64-unknown-linux-gnu

- name: setup nodejs
uses: actions/setup-node@v4
Expand All @@ -55,13 +54,12 @@ jobs:

- name: Download uv
run: |
mkdir bin
mkdir temp
mkdir -p ./assets/bin
curl -L https://github.com/astral-sh/uv/releases/download/${{ env.UV_VERSION }}/uv-aarch64-apple-darwin.tar.gz -o uv.tar.gz
tar -xzf uv.tar.gz -C ./bin
mv ./bin/uv-aarch64-apple-darwin/uv ./assets/uv
rm -rf ./bin/uv-aarch64-apple-darwin
ls -alF ./bin
ls -alF ./assets
tar -xzf uv.tar.gz -C ./temp
mv ./temp/uv-aarch64-apple-darwin/uv ./assets/bin/uv
rm -rf ./temp/uv-aarch64-apple-darwin

- name: setup nodejs
uses: actions/setup-node@v4
Expand All @@ -87,10 +85,11 @@ jobs:

- name: Download uv
run: |
mkdir bin
mkdir temp
mkdir -p ./assets/bin
curl -L https://github.com/astral-sh/uv/releases/download/${{ env.UV_VERSION }}/uv-x86_64-pc-windows-msvc.zip -o uv.zip
unzip uv.zip -d bin/
mv bin/uv.exe assets/uv.exe
unzip uv.zip -d temp/
mv temp/uv.exe assets/bin/uv.exe

- name: setup nodejs
uses: actions/setup-node@v4
Expand Down
7 changes: 2 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,8 @@
],
"extraResources": [
{
"from": "assets/",
"to": ".",
"filter": [
"uv*"
]
"from": "assets/bin",
"to": "./bin"
}
],
"linux": {
Expand Down
44 changes: 25 additions & 19 deletions src/lib/pty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import * as pty from 'node-pty';
import { assert } from 'tsafe';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { PtyManager } from '@/lib/pty';
Expand All @@ -15,6 +14,7 @@ describe('PtyManager', () => {
let mockPtyProcess: any;

beforeEach(() => {
(process as any).resourcesPath = '/mock/path';
ptyManager = new PtyManager();
mockPtyProcess = {
onData: vi.fn(),
Expand All @@ -30,55 +30,61 @@ describe('PtyManager', () => {
vi.clearAllMocks();
});

it('should create a new pty process', () => {
it('should create a new pty entry', () => {
const onData = vi.fn();
const onExit = vi.fn();
const id = ptyManager.create({ onData, onExit });
const entry = ptyManager.create({ onData, onExit });

expect(id).toBeDefined();
expect(entry).toBeDefined();
expect(pty.spawn).toHaveBeenCalled();
expect(mockPtyProcess.onData).toHaveBeenCalled();
expect(mockPtyProcess.onExit).toHaveBeenCalled();
});

it('should store the created pty entry', () => {
const onData = vi.fn();
const onExit = vi.fn();
const entry = ptyManager.create({ onData, onExit });

expect(ptyManager.ptys.get(entry.id)).toBe(entry);
});

it('should write data to the pty process', () => {
const onData = vi.fn();
const onExit = vi.fn();
const id = ptyManager.create({ onData, onExit });
const entry = ptyManager.create({ onData, onExit });

ptyManager.write(id, 'test data');
ptyManager.write(entry.id, 'test data');
expect(mockPtyProcess.write).toHaveBeenCalledWith('test data');
});

it('should resize the pty process', () => {
const onData = vi.fn();
const onExit = vi.fn();
const id = ptyManager.create({ onData, onExit });
const entry = ptyManager.create({ onData, onExit });

ptyManager.resize(id, 1337, 90001);
ptyManager.resize(entry.id, 1337, 90001);
expect(mockPtyProcess.resize).toHaveBeenCalledWith(1337, 90001);
});

it('should replay the buffer', () => {
const onData = vi.fn();
const onExit = vi.fn();
const id = ptyManager.create({ onData, onExit });
const entry = ptyManager.ptys.get(id);
assert(entry);
const entry = ptyManager.create({ onData, onExit });
const data = 'test data';
entry.historyBuffer.push(data);
const replayData = ptyManager.replay(id);
const replayData = ptyManager.replay(entry.id);
expect(replayData).toBe(data);
});

it('should dispose of the pty process', () => {
const onData = vi.fn();
const onExit = vi.fn();
const id = ptyManager.create({ onData, onExit });
const entry = ptyManager.create({ onData, onExit });

ptyManager.dispose(id);
ptyManager.dispose(entry.id);
expect(mockPtyProcess.kill).toHaveBeenCalled();
expect(ptyManager.ptys.has(id)).toBe(false);
expect(ptyManager.ptys.has(entry.id)).toBe(false);
});

it('should teardown all pty processes', () => {
Expand All @@ -95,12 +101,12 @@ describe('PtyManager', () => {
it('should list all pty ids', () => {
const onData = vi.fn();
const onExit = vi.fn();
const id1 = ptyManager.create({ onData, onExit });
const id2 = ptyManager.create({ onData, onExit });
const entry1 = ptyManager.create({ onData, onExit });
const entry2 = ptyManager.create({ onData, onExit });

const ids = ptyManager.list();
expect(ids).toContain(id1);
expect(ids).toContain(id2);
expect(ids).toContain(entry1.id);
expect(ids).toContain(entry2.id);
expect(ids).toHaveLength(2);
});
});
19 changes: 9 additions & 10 deletions src/lib/pty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const DEFAULT_PTY_MANAGER_OPTIONS: PtyManagerOptions = {
};

type PtyEntry = {
id: string;
process: pty.IPty;
ansiSequenceBuffer: AnsiSequenceBuffer;
historyBuffer: SlidingBuffer<string>;
Expand All @@ -37,24 +38,19 @@ export class PtyManager {
this.options = { ...DEFAULT_PTY_MANAGER_OPTIONS, ...options };
}

create = ({ onData, onExit, options }: CreatePtyArgs): string => {
create = ({ onData, onExit, options }: CreatePtyArgs): PtyEntry => {
const id = nanoid();
const shell = getShell();

const ptyProcess = pty.spawn(shell, [], {
name: process.env['TERM'] ?? 'xterm-color',
cwd: options?.cwd ?? process.env.HOME,
env: process.env,
});

const ansiSequenceBuffer = new AnsiSequenceBuffer();
const historyBuffer = new SlidingBuffer<string>(this.options.maxHistorySize);

if (options?.cmd) {
for (const cmd of options.cmd) {
ptyProcess.write(cmd);
ptyProcess.write('\r');
}
}

ptyProcess.onData((data) => {
const result = ansiSequenceBuffer.append(data);
if (!result.hasIncomplete) {
Expand All @@ -71,8 +67,11 @@ export class PtyManager {
onExit(id, exitCode);
});

this.ptys.set(id, { process: ptyProcess, ansiSequenceBuffer, historyBuffer });
return id;
const entry = { id, process: ptyProcess, ansiSequenceBuffer, historyBuffer };

this.ptys.set(id, entry);

return entry;
};

write = (id: string, data: string): void => {
Expand Down
68 changes: 46 additions & 22 deletions src/main/install-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,17 @@ export class InstallManager {
this.log.info(`> ${uvPath} ${installPythonArgs.join(' ')}\r\n`);

const installPythonResult = await withResultAsync(() =>
runProcess(uvPath, installPythonArgs, onOutput, { signal: abortController.signal })
runProcess(
uvPath,
installPythonArgs,
{
onStdout: onOutput,
onStderr: onOutput,
},
{
signal: abortController.signal,
}
)
);

if (installPythonResult.isErr()) {
Expand Down Expand Up @@ -205,9 +215,17 @@ export class InstallManager {
this.log.info(`> ${uvPath} ${createVenvArgs.join(' ')}\r\n`);

const createVenvResult = await withResultAsync(() =>
runProcess(uvPath, createVenvArgs, onOutput, {
signal: abortController.signal,
})
runProcess(
uvPath,
createVenvArgs,
{
onStdout: onOutput,
onStderr: onOutput,
},
{
signal: abortController.signal,
}
)
);

if (createVenvResult.isErr()) {
Expand Down Expand Up @@ -254,10 +272,15 @@ export class InstallManager {
this.log.info(`> ${uvPath} ${installInvokeArgs.join(' ')}\r\n`);

const installAppResult = await withResultAsync(() =>
runProcess(uvPath, installInvokeArgs, onOutput, {
cwd: location,
signal: abortController.signal,
})
runProcess(
uvPath,
installInvokeArgs,
{ onStdout: onOutput, onStderr: onOutput },
{
cwd: location,
signal: abortController.signal,
}
)
);

if (installAppResult.isErr()) {
Expand Down Expand Up @@ -344,36 +367,37 @@ export const createInstallManager = (arg: {
* Simple wrapper around `child_process.execFile` that returns a promise that resolves when the process exits with code 0.
* If the process exits with a non-zero code, the promise is rejected with an error.
*
* @param file The path to the executable
* @param args The arguments to pass to the executable
* @param onOutput A callback that is called with the both stdout _and_ stderr outputs
* @param file The path to the executable to run.
* @param args The arguments to pass to the executable.
* @param callbacks An object with `onStdout` and `onStderr` functions to handle the process's output. The output is passed as a string.
* @param options Additional options to pass to `child_process.execFile`
*/
const runProcess = (
file: string,
args: string[],
onOutput: (data: string) => void,
callbacks: {
onStdout: (data: string) => void;
onStderr: (data: string) => void;
},
options?: ObjectEncodingOptions & ExecFileOptions
): Promise<'success' | 'canceled'> => {
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const p = execFile(file, args, options);

p.on('error', (error) => {
if (p.pid !== undefined) {
// The process started but errored - handle this in the exit event
return;
}
throw error;
reject(error);
});

assert(p.stdout);
p.stdout.on('data', (data) => {
onOutput(data.toString());
p.stdout?.on('data', (data) => {
callbacks.onStdout(data.toString());
});

assert(p.stderr);
p.stderr.on('data', (data) => {
onOutput(data.toString());
p.stderr?.on('data', (data) => {
callbacks.onStderr(data.toString());
});

p.on('close', (code) => {
Expand All @@ -382,9 +406,9 @@ const runProcess = (
} else if (code === null) {
// The process was killed via signal
resolve('canceled');
} else if (code !== 0) {
} else {
// The process exited with a non-zero code
throw new Error(`Process exited with code ${code}`);
reject(new Error(`Process exited with code ${code}`));
}
});
});
Expand Down
18 changes: 13 additions & 5 deletions src/main/pty-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { IpcListener } from '@electron-toolkit/typed-ipc/main';
import { ipcMain } from 'electron';

import { PtyManager } from '@/lib/pty';
import { getActivateVenvCommand, getHomeDirectory, getInstallationDetails } from '@/main/util';
import { getActivateVenvCommand, getBundledBinPath, getHomeDirectory, getInstallationDetails } from '@/main/util';
import type { IpcEvents, IpcRendererEvents, PtyOptions } from '@/shared/types';

export const createPtyManager = (arg: {
Expand All @@ -28,17 +28,25 @@ export const createPtyManager = (arg: {
const options: PtyOptions = {
cwd: getHomeDirectory(),
};
const entry = ptyManager.create({ onData, onExit, options });

// Add the bundled bin dir to the PATH env var
if (process.platform === 'win32') {
entry.process.write(`$env:Path='${getBundledBinPath()};'+$env:Path\r`);
} else {
// macOS, Linux
entry.process.write(`export PATH="${getBundledBinPath()}:$PATH"\r`);
}

if (cwd) {
const installDetails = await getInstallationDetails(cwd);
if (installDetails.isInstalled) {
options.cmd = [getActivateVenvCommand(installDetails.path)];
options.cwd = installDetails.path;
const activateVenvCmd = getActivateVenvCommand(installDetails.path);
entry.process.write(`${activateVenvCmd}\r`);
}
}

const id = ptyManager.create({ onData, onExit, options });
return id;
return entry.id;
});
ipc.handle('terminal:dispose', (_, id) => ptyManager.dispose(id));
ipc.handle('terminal:resize', (_, id, cols, rows) => ptyManager.resize(id, cols, rows));
Expand Down
Loading
Loading