Last active
April 28, 2022 03:19
-
-
Save pinksynth/0ba2660cd02d0af8854dbcc3d445069b to your computer and use it in GitHub Desktop.
Get missing file type from magic numbers in Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Mix.Tasks.GetFileType do | |
use Mix.Task | |
def run([filename]) do | |
File.read!(filename) | |
|> check_magic_bytes() | |
|> IO.puts() | |
end | |
# Here's some basic file signatures, but you can easily add others as needed. | |
# https://en.wikipedia.org/wiki/List_of_file_signatures | |
defp check_magic_bytes(<<137, 80, 78, 71, 13, 10, 26, 10, _::binary>>), do: "png" | |
defp check_magic_bytes(<<37, 80, 68, 70, 45, _::binary>>), do: "pdf" | |
defp check_magic_bytes(<<73, 73, 42, 0, _::binary>>), do: "tiff" | |
defp check_magic_bytes(<<77, 77, 0, 42, _::binary>>), do: "tiff" | |
defp check_magic_bytes(<<255, 216, 255, _::binary>>), do: "jpg" | |
defp check_magic_bytes(_), do: "unknown" | |
end | |
# Usage: | |
# $ mix get_file_type ./some_png_without_extension | |
# png | |
# $ mix get_file_type ./something_not_on_list | |
# unknown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment