123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- var fs = require('fs');
- var path = require('path');
- var cst = require('../../constants.js')
- var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh';
- var FILE_EXECUTABLE_MODE = 1;
- function statFollowLinks() {
- return fs.statSync.apply(fs, arguments);
- }
- function isWindowsPlatform() {
- return cst.IS_WINDOWS;
- }
- function splitPath(p) {
- return p ? p.split(path.delimiter) : [];
- }
- function isExecutable(pathName) {
- try {
-
- fs.accessSync(pathName, FILE_EXECUTABLE_MODE);
- } catch (err) {
- return false;
- }
- return true;
- }
- function checkPath(pathName) {
- return fs.existsSync(pathName) && !statFollowLinks(pathName).isDirectory()
- && (isWindowsPlatform() || isExecutable(pathName));
- }
- function _which(cmd) {
- if (!cmd) console.error('must specify command');
- var options = {}
- var isWindows = isWindowsPlatform();
- var pathArray = splitPath(process.env.PATH);
- var queryMatches = [];
-
- if (cmd.indexOf('/') === -1) {
-
-
- var pathExtArray = [''];
- if (isWindows) {
-
-
- var pathExtEnv = process.env.PATHEXT || XP_DEFAULT_PATHEXT;
- pathExtArray = splitPath(pathExtEnv.toUpperCase());
- }
-
- for (var k = 0; k < pathArray.length; k++) {
-
- if (queryMatches.length > 0 && !options.all) break;
- var attempt = path.resolve(pathArray[k], cmd);
- if (isWindows) {
- attempt = attempt.toUpperCase();
- }
- var match = attempt.match(/\.[^<>:"/|?*.]+$/);
- if (match && pathExtArray.indexOf(match[0]) >= 0) {
-
-
- if (checkPath(attempt)) {
- queryMatches.push(attempt);
- break;
- }
- } else {
-
-
- for (var i = 0; i < pathExtArray.length; i++) {
- var ext = pathExtArray[i];
- var newAttempt = attempt + ext;
- if (checkPath(newAttempt)) {
- queryMatches.push(newAttempt);
- break;
- }
- }
- }
- }
- } else if (checkPath(cmd)) {
- queryMatches.push(path.resolve(cmd));
- }
- if (queryMatches.length > 0) {
- return options.all ? queryMatches : queryMatches[0];
- }
- return options.all ? [] : null;
- }
- module.exports = _which;
|