export function _which()

in node/internal.ts [344:425]


export function _which(tool: string, check?: boolean): string {
    if (!tool) {
        throw new Error('parameter \'tool\' is required');
    }

    // recursive when check=true
    if (check) {
        let result: string = _which(tool, false);
        if (result) {
            return result;
        }
        else {
            if (process.platform == 'win32') {
                throw new Error(_loc('LIB_WhichNotFound_Win', tool));
            }
            else {
                throw new Error(_loc('LIB_WhichNotFound_Linux', tool));
            }
        }
    }

    _debug(`which '${tool}'`);
    try {
        // build the list of extensions to try
        let extensions: string[] = [];
        if (process.platform == 'win32' && process.env['PATHEXT']) {
            for (let extension of process.env['PATHEXT'].split(path.delimiter)) {
                if (extension) {
                    extensions.push(extension);
                }
            }
        }

        // if it's rooted, return it if exists. otherwise return empty.
        if (_isRooted(tool)) {
            let filePath: string = _tryGetExecutablePath(tool, extensions);
            if (filePath) {
                _debug(`found: '${filePath}'`);
                return filePath;
            }

            _debug('not found');
            return '';
        }

        // if any path separators, return empty
        if (tool.indexOf('/') >= 0 || (process.platform == 'win32' && tool.indexOf('\\') >= 0)) {
            _debug('not found');
            return '';
        }

        // build the list of directories
        //
        // Note, technically "where" checks the current directory on Windows. From a task lib perspective,
        // it feels like we should not do this. Checking the current directory seems like more of a use
        // case of a shell, and the which() function exposed by the task lib should strive for consistency
        // across platforms.
        let directories: string[] = [];
        if (process.env['PATH']) {
            for (let p of process.env['PATH'].split(path.delimiter)) {
                if (p) {
                    directories.push(p);
                }
            }
        }

        // return the first match
        for (let directory of directories) {
            let filePath = _tryGetExecutablePath(directory + path.sep + tool, extensions);
            if (filePath) {
                _debug(`found: '${filePath}'`);
                return filePath;
            }
        }

        _debug('not found');
        return '';
    }
    catch (err) {
        throw new Error(_loc('LIB_OperationFailed', 'which', err.message));
    }
}