Skip to content

Commit b19ae2c

Browse files
committed
create_symlink: streamline with try,catch
1 parent 1611b44 commit b19ae2c

File tree

1 file changed

+34
-37
lines changed

1 file changed

+34
-37
lines changed

+stdlib/create_symlink.m

Lines changed: 34 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,49 +14,46 @@
1414
link (1,1) string
1515
end
1616

17-
if stdlib.isoctave()
1817

19-
[err, msg] = symlink(target, link);
20-
ok = err == 0;
21-
if ~ok
22-
warning("create_symlink: %s", msg)
18+
ok = false;
19+
20+
if stdlib.exists(link), return, end
21+
22+
try
23+
createSymbolicLink(link, target);
24+
ok = true;
25+
catch e
26+
if strcmp(e.identifier, "MATLAB:io:filesystem:symlink:NeedsAdminPerms") || ...
27+
strcmp(e.identifier, 'MATLAB:UndefinedFunction')
28+
% windows requires RunAsAdmin
29+
% https://www.mathworks.com/help/releases/R2024b/matlab/ref/createsymboliclink.html
30+
% ok = java.nio.file.Files.createSymbolicLink(java.io.File(link).toPath(), java.io.File(target).toPath());
31+
% Matlab Java doesn't recognize the optional argument omitted.
32+
33+
if ispc
34+
cmd = "pwsh -c " + '"' + "New-Item -ItemType SymbolicLink -Path " + link + ...
35+
" -Target " + target + '"';
36+
else
37+
cmd = "ln -s " + target + " " + link;
38+
end
39+
40+
% suppress output text on powershell
41+
[stat, ~] = system(cmd);
42+
43+
ok = stat == 0;
44+
elseif strcmp(e.identifier, "Octave:undefined-function")
45+
[err, msg] = symlink(target, link);
46+
ok = err == 0;
47+
if ~ok
48+
warning("create_symlink: %s", msg)
49+
end
50+
else
51+
warning(e.identifier, e.message)
2352
end
24-
25-
elseif ispc || isMATLABReleaseOlderThan("R2024b")
26-
% ok = java.nio.file.Files.createSymbolicLink(java.io.File(link).toPath(), java.io.File(target).toPath());
27-
% the above should work, but Matlab Java doesn't recognize the optional argument omitted.
28-
29-
if stdlib.exists(link)
30-
ok = false;
31-
return
3253
end
3354

34-
if ispc
35-
cmd = "pwsh -c " + '"' + "New-Item -ItemType SymbolicLink -Path " + link + ...
36-
" -Target " + target + '"';
37-
else
38-
cmd = "ln -s " + target + " " + link;
39-
end
40-
41-
% suppress output text on powershell
42-
[stat, ~] = system(cmd);
43-
44-
ok = stat == 0;
45-
46-
else
47-
% windows requires RunAsAdmin, so we don't use this on Windows
48-
% https://www.mathworks.com/help/releases/R2024b/matlab/ref/createsymboliclink.html
49-
50-
try
51-
createSymbolicLink(link, target);
52-
ok = true;
53-
catch
54-
ok = false;
55-
end
56-
5755
end
5856

59-
end
6057

6158
%!test
6259
%! if !ispc

0 commit comments

Comments
 (0)