Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell.ts

38 lines1.2 KB

1import { execFileSync } from "node:child_process";
2​
3const PATH_CAPTURE_START = "__T3CODE_PATH_START__";
4const PATH_CAPTURE_END = "__T3CODE_PATH_END__";
5const PATH_CAPTURE_COMMAND = [
6 `printf '%s\n' '${PATH_CAPTURE_START}'`,
7 "printenv PATH",
8 `printf '%s\n' '${PATH_CAPTURE_END}'`,
9].join("; ");
10​
11type ExecFileSyncLike = (
12 file: string,
13 args: ReadonlyArray<string>,
14 options: { encoding: "utf8"; timeout: number },
15) => string;
16​
17export function extractPathFromShellOutput(output: string): string | null {
18 const startIndex = output.indexOf(PATH_CAPTURE_START);
19 if (startIndex === -1) return null;
20​
21 const valueStartIndex = startIndex + PATH_CAPTURE_START.length;
22 const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);
23 if (endIndex === -1) return null;
24​
25 const pathValue = output.slice(valueStartIndex, endIndex).trim();
26 return pathValue.length > 0 ? pathValue : null;
28​
29export function readPathFromLoginShell(
30 shell: string,
31 execFile: ExecFileSyncLike = execFileSync,
32): string | undefined {
33 const output = execFile(shell, ["-ilc", PATH_CAPTURE_COMMAND], {
34 encoding: "utf8",
35 timeout: 5000,
36 });
37 return extractPathFromShellOutput(output) ?? undefined;