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