Skip to content

Commit ed358b9

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

File tree

1 file changed

+33
-37
lines changed

1 file changed

+33
-37
lines changed

+stdlib/create_symlink.m

Lines changed: 33 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,49 +14,45 @@
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+
% windows requires RunAsAdmin
28+
% https://www.mathworks.com/help/releases/R2024b/matlab/ref/createsymboliclink.html
29+
% ok = java.nio.file.Files.createSymbolicLink(java.io.File(link).toPath(), java.io.File(target).toPath());
30+
% Matlab Java doesn't recognize the optional argument omitted.
31+
32+
if ispc
33+
cmd = "pwsh -c " + '"' + "New-Item -ItemType SymbolicLink -Path " + link + ...
34+
" -Target " + target + '"';
35+
else
36+
cmd = "ln -s " + target + " " + link;
37+
end
38+
39+
% suppress output text on powershell
40+
[stat, ~] = system(cmd);
41+
42+
ok = stat == 0;
43+
elseif strcmp(e.identifier, "Octave:undefined-function")
44+
[err, msg] = symlink(target, link);
45+
ok = err == 0;
46+
if ~ok
47+
warning("create_symlink: %s", msg)
48+
end
49+
else
50+
warning(e.identifier, e.message)
2351
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
3252
end
3353

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-
5754
end
5855

59-
end
6056

6157
%!test
6258
%! if !ispc

0 commit comments

Comments
 (0)