Skip to content

Commit

Permalink
feat: inject path to node_modules/.bin (fixes #35) (#36)
Browse files Browse the repository at this point in the history
* feat: inject path to node_modules/.bin (fixes #35)

* feat: inject path to node_modules/.bin (fixes #35)
  • Loading branch information
gajus authored Mar 27, 2023
1 parent ea198d0 commit dfbb0f5
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions cspell.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ words:
- interruptible
- jiti
- kuizinas
- pipefail
- randomcolor
- roarr
- SIGINT
Expand Down
8 changes: 8 additions & 0 deletions src/createSpawn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ it('returns outputs', async () => {
expect(String(result?.stdout)).toEqual('Hello, World!\n');
});

it('injects path to node_modules/.bin', async () => {
const spawn = createSpawn('foo');

const result = await spawn`echo $PATH`;

expect(String(result?.stdout)).toMatch(/node_modules\/\.bin/u);
});

it('rejects if process produces an error', async () => {
const spawn = createSpawn('foo');

Expand Down
5 changes: 5 additions & 0 deletions src/createSpawn.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// cspell:words nothrow

import { findNearestDirectory } from './findNearestDirectory';
import { Logger } from './Logger';
import { type Throttle } from './types';
import chalk from 'chalk';
Expand Down Expand Up @@ -64,8 +65,12 @@ export const createSpawn = (
const colorText = chalk.hex(randomColor({ luminosity: 'dark' }));

return async (pieces: TemplateStringsArray, ...args: any[]) => {
const binPath = (await findNearestDirectory('node_modules', cwd)) + '/.bin';

$.cwd = cwd;

$.prefix = `set -euo pipefail; export PATH="${binPath}:$PATH";`;

let onStdout: (chunk: Buffer) => void;
let onStderr: (chunk: Buffer) => void;

Expand Down
32 changes: 32 additions & 0 deletions src/findNearestDirectory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import fs from 'node:fs/promises';
import path from 'node:path';

export const findNearestDirectory = async (
fileName: string,
startPath: string,
): Promise<string | null> => {
let currentPath = startPath;

// eslint-disable-next-line no-constant-condition
while (true) {
const targetPath = path.join(currentPath, fileName);

try {
await fs.access(targetPath, fs.constants.F_OK);
} catch {
const nextPath = path.resolve(currentPath, '..');

if (nextPath === currentPath) {
break;
}

currentPath = nextPath;

continue;
}

return targetPath;
}

return null;
};

0 comments on commit dfbb0f5

Please sign in to comment.