Skip to content

Commit 6ec9b43

Browse files
committed
add is_prefix()
1 parent 9fbde32 commit 6ec9b43

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

+stdlib/is_prefix.m

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
%% IS_PREFIX is prefix a prefix of path?
2+
% canonicalization and normalization are NOT performed
3+
% duplicated slashes are dropped
4+
5+
function s = is_prefix(prefix, pth)
6+
% arguments
7+
% prefix (1,1) string
8+
% pth (1,1) string
9+
% end
10+
11+
pr = stdlib.drop_slash(prefix);
12+
p = stdlib.drop_slash(pth);
13+
14+
if ischar(pr)
15+
w = ~isempty(strfind(p, "..")) || ~isempty(strfind(pr, "..")); %#ok<STREMP>
16+
s = strfind(p, pr) == 1 && (length(p) >= length(pr));
17+
else
18+
w = contains(p, "..") || contains(pr, "..");
19+
s = startsWith(p, pr) && (strlength(p) >= strlength(pr));
20+
end
21+
22+
if ~strcmp(pr, p) && w
23+
warning("is_prefix: %s and/or %s is ambiguous input with '..' consider using stdlib.canonical() first", pr, p)
24+
end
25+
26+
end
27+
28+
%!assert(is_prefix("a", "a"))
29+
%!assert(is_prefix("a", "a/"))
30+
%!assert(is_prefix("a", "a/b"))

test/TestRelative.m

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
p_relative_to
55
p_proximate_to
66
p_is_subdir
7+
p_is_prefix
78
end
89

910

@@ -59,7 +60,7 @@
5960
end
6061

6162

62-
function [p_is_subdir] = init_is_subdir()
63+
function [p_is_subdir, p_is_prefix] = init_is_subdir()
6364

6465
p_is_subdir = {
6566
{"a/b", "a/b", false}, ...
@@ -79,6 +80,15 @@
7980
p_is_subdir{end+1} = {"/", "/", false};
8081
end
8182

83+
p_is_prefix = p_is_subdir;
84+
p_is_prefix{1}{3} = true;
85+
p_is_prefix{2}{3} = false;
86+
p_is_prefix{3}{3} = true;
87+
p_is_prefix{6}{3} = true;
88+
p_is_prefix{7}{3} = false;
89+
p_is_prefix{8}{3} = false;
90+
p_is_prefix{9}{3} = true;
91+
8292
end
8393

8494
end
@@ -110,10 +120,13 @@ function test_proximate_to(tc, p_proximate_to)
110120

111121

112122
function test_is_subdir(tc, p_is_subdir)
113-
tc.assumeTrue(stdlib.has_java)
114123
tc.verifyEqual(stdlib.is_subdir(p_is_subdir{1}, p_is_subdir{2}), p_is_subdir{3}, "subdir(" + p_is_subdir{1} + "," + p_is_subdir{2} + ")")
115124
end
116125

126+
function test_is_prefix(tc, p_is_prefix)
127+
tc.verifyEqual(stdlib.is_prefix(p_is_prefix{1}, p_is_prefix{2}), p_is_prefix{3}, "prefix(" + p_is_prefix{1} + "," + p_is_prefix{2} + ")")
128+
end
129+
117130
end
118131

119132
end

0 commit comments

Comments
 (0)