Skip to content

Commit

Permalink
Improve get_from_path/2
Browse files Browse the repository at this point in the history
  • Loading branch information
daskycodes committed Nov 23, 2023
1 parent 094fc4a commit 1dde010
Showing 1 changed file with 13 additions and 4 deletions.
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

0 comments on commit 1dde010

Please sign in to comment.