Skip to content

Commit

Permalink
add is_prefix()
Browse files Browse the repository at this point in the history
  • Loading branch information
scivision committed Dec 15, 2024
1 parent 9fbde32 commit 6ec9b43
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
30 changes: 30 additions & 0 deletions +stdlib/is_prefix.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
%% IS_PREFIX is prefix a prefix of path?
% canonicalization and normalization are NOT performed
% duplicated slashes are dropped

function s = is_prefix(prefix, pth)
% arguments
% prefix (1,1) string
% pth (1,1) string
% end

pr = stdlib.drop_slash(prefix);
p = stdlib.drop_slash(pth);

if ischar(pr)
w = ~isempty(strfind(p, "..")) || ~isempty(strfind(pr, "..")); %#ok<STREMP>
s = strfind(p, pr) == 1 && (length(p) >= length(pr));
else
w = contains(p, "..") || contains(pr, "..");
s = startsWith(p, pr) && (strlength(p) >= strlength(pr));
end

if ~strcmp(pr, p) && w
warning("is_prefix: %s and/or %s is ambiguous input with '..' consider using stdlib.canonical() first", pr, p)
end

end

%!assert(is_prefix("a", "a"))
%!assert(is_prefix("a", "a/"))
%!assert(is_prefix("a", "a/b"))
17 changes: 15 additions & 2 deletions test/TestRelative.m
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
p_relative_to
p_proximate_to
p_is_subdir
p_is_prefix
end


Expand Down Expand Up @@ -59,7 +60,7 @@
end


function [p_is_subdir] = init_is_subdir()
function [p_is_subdir, p_is_prefix] = init_is_subdir()

p_is_subdir = {
{"a/b", "a/b", false}, ...
Expand All @@ -79,6 +80,15 @@
p_is_subdir{end+1} = {"/", "/", false};
end

p_is_prefix = p_is_subdir;
p_is_prefix{1}{3} = true;
p_is_prefix{2}{3} = false;
p_is_prefix{3}{3} = true;
p_is_prefix{6}{3} = true;
p_is_prefix{7}{3} = false;
p_is_prefix{8}{3} = false;
p_is_prefix{9}{3} = true;

end

end
Expand Down Expand Up @@ -110,10 +120,13 @@ function test_proximate_to(tc, p_proximate_to)


function test_is_subdir(tc, p_is_subdir)
tc.assumeTrue(stdlib.has_java)
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} + ")")
end

function test_is_prefix(tc, p_is_prefix)
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} + ")")
end

end

end

0 comments on commit 6ec9b43

Please sign in to comment.