Skip to content

Commit 9c25abb

Browse files
committed
which: optional find_all to find all executable
1 parent 089ba5e commit 9c25abb

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

+stdlib/which.m

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@
44
% That is, can return relative path if executable is in:
55
% * (Windows) in cwd
66
% * (all) fpath or Path contains relative paths
7+
%
8+
% find_all option finds all executables specified under PATH, instead of only the first
79

8-
function exe = which(filename, fpath, use_java)
10+
function exe = which(filename, fpath, find_all, use_java)
911
arguments
1012
filename (1,1) string
11-
fpath (1,:) string = getenv('PATH')
13+
fpath (1,:) string = string.empty
14+
find_all (1,1) logical = false
1215
use_java (1,1) logical = false
1316
end
1417

@@ -25,18 +28,24 @@
2528
end
2629

2730
% path given
31+
if isempty(fpath) || strlength(fpath) == 0
32+
fpath = string(getenv("PATH"));
33+
end
2834

2935
if isscalar(fpath)
30-
% PATH could have ~/ prefixed paths in it
31-
fpath = split(stdlib.expanduser(fpath), pathsep).';
36+
fpath = split(fpath, pathsep);
3237
end
3338
fpath = fpath(strlength(fpath)>0);
3439

35-
for p = fpath
40+
for p = fpath.'
3641
e = p + "/" + filename;
3742
if isfile(e) && stdlib.is_exe(e, use_java)
38-
exe = stdlib.posix(e);
39-
return
43+
if find_all
44+
exe(end+1) = stdlib.posix(e); %#ok<AGROW>
45+
else
46+
exe = stdlib.posix(e);
47+
return
48+
end
4049
end
4150
end
4251

test/TestWhich.m

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
function test_which_name(tc, use_java)
1111

12-
tc.verifyEmpty(stdlib.which(tempname, getenv('PATH'), use_java))
12+
tc.verifyEmpty(stdlib.which(tempname, [], use_java))
1313

1414
if ispc
1515
n = "pwsh.exe";
@@ -21,7 +21,7 @@ function test_which_name(tc, use_java)
2121
% Unix-like OS may have Matlab as alias which is not visible to
2222
% stdlib.which()
2323
% virus scanners may block stdlib.which("cmd.exe") on Windows
24-
tc.verifyNotEmpty(stdlib.which(n, getenv('PATH'), use_java))
24+
tc.verifyNotEmpty(stdlib.which(n, [], use_java))
2525

2626
end
2727

0 commit comments

Comments
 (0)