Skip to content

Commit 63af087

Browse files
committed
Use saner parent_path? implementation and add tests
1 parent 35a360f commit 63af087

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

apps/common/lib/lexical/path.ex

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,6 @@ defmodule Lexical.Path do
66
@doc """
77
Checks if the `parent_path` is a parent directory of the `child_path`.
88
9-
This function normalizes both paths and compares their segments to determine
10-
if the `parent_path` is a prefix of the `child_path`.
11-
129
## Examples
1310
1411
iex> Lexical.Path.parent_path?("/home/user/docs/file.txt", "/home/user")
@@ -23,13 +20,14 @@ defmodule Lexical.Path do
2320
iex> Lexical.Path.parent_path?("/home/user/docs", "/home/user/docs/subdir")
2421
false
2522
"""
23+
def parent_path?(child_path, parent_path) when byte_size(child_path) < byte_size(parent_path) do
24+
false
25+
end
26+
2627
def parent_path?(child_path, parent_path) do
2728
normalized_child = Path.expand(child_path)
2829
normalized_parent = Path.expand(parent_path)
2930

30-
child_segments = Path.split(normalized_child)
31-
parent_segments = Path.split(normalized_parent)
32-
33-
Enum.take(child_segments, length(parent_segments)) == parent_segments
31+
String.starts_with?(normalized_child, normalized_parent)
3432
end
3533
end
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
defmodule Lexical.PathTest do
2+
use ExUnit.Case, async: true
3+
4+
doctest Lexical.Path
5+
end

0 commit comments

Comments
 (0)