Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions lib/elixir/lib/path.ex
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,32 @@ defmodule Path do
end
end

@doc """
Safely joins two paths.

Returns `{:ok, path}` if `right` is safe to append to `left`, or `:error`
otherwise. See `safe_relative/2` for the exact safety rules applied to `right`.

## Examples

iex> Path.safe_join("foo", "bar")
{:ok, "foo/bar"}

iex> Path.safe_join("foo", "../bar")
:error

iex> Path.safe_join("foo", "/bar")
:error

"""
@doc since: "1.21.0"
@spec safe_join(t, t) :: {:ok, t} | :error
def safe_join(left, right) do
with {:ok, right} <- safe_relative(right, left) do
{:ok, join(left, right)}
end
end

@doc ~S"""
Splits the path into a list at the path separator.

Expand Down
8 changes: 8 additions & 0 deletions lib/elixir/test/elixir/path_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,14 @@ defmodule PathTest do
assert Path.join(["/foo", "bar"], ["fiz", "buz"]) == "/foobar/fizbuz"
end

test "safe_join/2" do
assert {:ok, "foo/bar"} = Path.safe_join("foo", "bar")
assert {:ok, "foo"} = Path.safe_join("foo", ".")

assert :error = Path.safe_join("foo", "../bar")
assert :error = Path.safe_join("foo", "/bar")
end

test "split/1" do
assert Path.split("") == []
assert Path.split("foo") == ["foo"]
Expand Down
Loading