1 |
|
2 | var fs = require('fs');
|
3 | var path = require('path');
|
4 | var cst = require('../../constants.js')
|
5 |
|
6 |
|
7 |
|
8 | var XP_DEFAULT_PATHEXT = '.com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh';
|
9 |
|
10 |
|
11 | var FILE_EXECUTABLE_MODE = 1;
|
12 |
|
13 | function statFollowLinks() {
|
14 | return fs.statSync.apply(fs, arguments);
|
15 | }
|
16 |
|
17 | function isWindowsPlatform() {
|
18 | return cst.IS_WINDOWS;
|
19 | }
|
20 |
|
21 |
|
22 | function splitPath(p) {
|
23 | return p ? p.split(path.delimiter) : [];
|
24 | }
|
25 |
|
26 |
|
27 |
|
28 | function isExecutable(pathName) {
|
29 | try {
|
30 |
|
31 | fs.accessSync(pathName, FILE_EXECUTABLE_MODE);
|
32 | } catch (err) {
|
33 | return false;
|
34 | }
|
35 | return true;
|
36 | }
|
37 |
|
38 | function checkPath(pathName) {
|
39 | return fs.existsSync(pathName) && !statFollowLinks(pathName).isDirectory()
|
40 | && (isWindowsPlatform() || isExecutable(pathName));
|
41 | }
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | function _which(cmd) {
|
57 | if (!cmd) console.error('must specify command');
|
58 |
|
59 | var options = {}
|
60 |
|
61 | var isWindows = isWindowsPlatform();
|
62 | var pathArray = splitPath(process.env.PATH);
|
63 |
|
64 | var queryMatches = [];
|
65 |
|
66 |
|
67 | if (cmd.indexOf('/') === -1) {
|
68 |
|
69 |
|
70 | var pathExtArray = [''];
|
71 | if (isWindows) {
|
72 |
|
73 |
|
74 | var pathExtEnv = process.env.PATHEXT || XP_DEFAULT_PATHEXT;
|
75 | pathExtArray = splitPath(pathExtEnv.toUpperCase());
|
76 | }
|
77 |
|
78 |
|
79 | for (var k = 0; k < pathArray.length; k++) {
|
80 |
|
81 | if (queryMatches.length > 0 && !options.all) break;
|
82 |
|
83 | var attempt = path.resolve(pathArray[k], cmd);
|
84 |
|
85 | if (isWindows) {
|
86 | attempt = attempt.toUpperCase();
|
87 | }
|
88 |
|
89 | var match = attempt.match(/\.[^<>:"/|?*.]+$/);
|
90 | if (match && pathExtArray.indexOf(match[0]) >= 0) {
|
91 |
|
92 |
|
93 | if (checkPath(attempt)) {
|
94 | queryMatches.push(attempt);
|
95 | break;
|
96 | }
|
97 | } else {
|
98 |
|
99 |
|
100 | for (var i = 0; i < pathExtArray.length; i++) {
|
101 | var ext = pathExtArray[i];
|
102 | var newAttempt = attempt + ext;
|
103 | if (checkPath(newAttempt)) {
|
104 | queryMatches.push(newAttempt);
|
105 | break;
|
106 | }
|
107 | }
|
108 | }
|
109 | }
|
110 | } else if (checkPath(cmd)) {
|
111 | queryMatches.push(path.resolve(cmd));
|
112 | }
|
113 |
|
114 | if (queryMatches.length > 0) {
|
115 | return options.all ? queryMatches : queryMatches[0];
|
116 | }
|
117 | return options.all ? [] : null;
|
118 | }
|
119 |
|
120 | module.exports = _which;
|