Files
smartshell/ts/classes.shellenv.ts

111 lines
3.2 KiB
TypeScript

export type TExecutor = 'sh' | 'bash';
export interface IShellEnvContructorOptions {
executor: TExecutor;
sourceFilePaths?: string[];
pathDirectories?: string[];
}
export class ShellEnv {
executor: TExecutor;
sourceFileArray: string[] = [];
pathDirArray: string[] = [];
/**
* constructor for the shellenv
*/
constructor(optionsArg: IShellEnvContructorOptions) {
this.executor = optionsArg.executor;
// add sourcefiles
if (optionsArg.sourceFilePaths) {
this.sourceFileArray = this.sourceFileArray.concat(optionsArg.sourceFilePaths);
}
// add pathDirectories
if (optionsArg.pathDirectories) {
this.pathDirArray = this.pathDirArray.concat(optionsArg.pathDirectories);
}
}
/**
* Detect if running under Windows Subsystem for Linux
*/
private static _isWSL(): boolean {
return !!(
process.env.WSL_DISTRO_NAME ||
process.env.WSLENV ||
(process.platform === 'linux' && process.env.PATH?.includes('/mnt/c/'))
);
}
/**
* imports path into the shell from env if available and returns it with
*/
private _setPath(commandStringArg: string): string {
let commandResult = commandStringArg;
let commandPaths: string[] = [];
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
if (process.env.SMARTSHELL_PATH) {
commandPaths = commandPaths.concat(process.env.SMARTSHELL_PATH.split(':'));
}
// Only filter out WSL-specific paths when actually running under WSL
if (ShellEnv._isWSL()) {
commandPaths = commandPaths.filter((commandPathArg) => {
return (
!commandPathArg.startsWith('/mnt/c/') &&
!commandPathArg.startsWith('Files/1E') &&
!commandPathArg.includes(' ')
);
});
}
commandResult = `PATH=${commandPaths.join(':')} && ${commandStringArg}`;
return commandResult;
}
/**
* add files that are going to be sourced when running a command
* @param sourceFilePathsArray
*/
addSourceFiles(sourceFilePathsArray: string[]) {
for (let sourceFilePath of sourceFilePathsArray) {
this.sourceFileArray.push(sourceFilePath);
}
}
/**
* cleans the source files array
*/
cleanSourceFiles() {
this.sourceFileArray = [];
}
public createEnvExecString(commandArg: string): string {
let commandResult = '';
let sourceString = '';
// deal with sourcestring
for (const sourceFilePath of this.sourceFileArray) {
sourceString = sourceString + `source ${sourceFilePath} && `;
}
// deal with available path
let pathString = 'PATH=$PATH';
for (const pathDir of this.pathDirArray) {
pathString += `:${pathDir}`;
}
pathString += ` && `;
// For both bash and sh executors, build the command string directly.
// The shell nesting is handled by spawn() using the appropriate shell binary.
// Previously bash executor wrapped in `bash -c '...'` which caused triple
// shell nesting (Node spawn sh -> bash -c -> command). Now spawn() uses
// shell: '/bin/bash' directly, so we don't need the extra wrapping.
commandResult = `${pathString}${sourceString}${commandArg}`;
commandResult = this._setPath(commandResult);
return commandResult;
}
}