Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore params and detect subtype suffix in extensions/1 #45

Merged
merged 4 commits into from
Mar 31, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
21 changes: 20 additions & 1 deletion lib/mime/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,28 @@ defmodule MIME.Application do
iex> MIME.extensions("application/json")
["json"]

iex> MIME.extensions("application/vnd.custom+xml")
["xml"]

iex> MIME.extensions("foo/bar")
[]

"""
@spec extensions(String.t()) :: [String.t()]
def extensions(type) do
mime_to_ext(downcase(type, "")) || []
mime =
type
|> strip_params()
|> downcase("")

mime_to_ext(mime) || suffix(mime) || []
end

defp suffix(type) do
case String.split(type, "+") do
[type_subtype_without_suffix, suffix] -> [suffix]
_ -> nil
end
end

@default_type "application/octet-stream"
Expand Down Expand Up @@ -161,6 +176,10 @@ defmodule MIME.Application do
end
end

defp strip_params(string) do
string |> String.split(";", parts: 2) |> hd()
wojtekmach marked this conversation as resolved.
Show resolved Hide resolved
end

defp downcase(<<h, t::binary>>, acc) when h in ?A..?Z,
do: downcase(t, <<acc::binary, h + 32>>)

Expand Down
10 changes: 9 additions & 1 deletion test/mime_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,21 @@ defmodule MIMETest do
test "valid?/1" do
assert valid?("application/json")
refute valid?("application/prs.vacation-photos")

refute valid?("application/JSON")
refute valid?("application/json; charset=utf-8")
end

test "extensions/1" do
assert "json" in extensions("application/json")
assert extensions("application/json") == ["json"]
assert extensions("application/vnd.api+json") == ["json-api"]
assert extensions("audio/amr") == ["amr"]
assert extensions("IMAGE/PNG") == ["png"]

assert extensions("application/json; charset=utf-8") == ["json"]

assert extensions("application/vnd.custom+xml") == ["xml"]
assert extensions("application/vnd.custom+xml+xml") == []
end

test "type/1" do
Expand Down