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

Improve get_from_path/1,2 #13

Merged
merged 1 commit into from
Nov 23, 2023
Merged
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
17 changes: 13 additions & 4 deletions lib/infer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,22 @@ defmodule Infer do
iex> Infer.get_from_path("test/docs/sample.pptx")
%Infer.Type{extension: "pptx", matcher: &Infer.Doc.pptx?/1, matcher_type: :doc, mime_type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"}

iex> Infer.get_from_path("test/docs/unknown.path")
nil

"""
@spec get_from_path(binary()) :: Infer.Type.t() | nil
def get_from_path(path, byte_size \\ 2048) do
with {:ok, io_device} <- :file.open(path, [:read, :binary]),
{:ok, binary} <- :file.read(io_device, byte_size) do
:file.close(io_device)
Enum.find(@matchers, & &1.matcher.(binary))
result = File.open(path, [:binary, :read], fn io_device ->
case IO.binread(io_device, byte_size) do
binary when is_binary(binary) -> Enum.find(@matchers, & &1.matcher.(binary))
_other -> nil
end
end)

case result do
{:ok, %Infer.Type{} = type} -> type
_other -> nil
end
end

Expand Down
Loading