Current section
Files
Jump to
Current section
Files
lib/fluminus/util.ex
defmodule Fluminus.Util do
@moduledoc """
A collection of common methods in Fluminus.
"""
alias Fluminus.HTTPClient
@doc """
Sanitises filename according to Unix standard.
"""
@spec sanitise_filename(String.t()) :: String.t()
def sanitise_filename(name) when is_binary(name) do
# According to http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html:
# The bytes composing the name shall not contain the <NUL> or <slash> characters
String.replace(name, ~r|[/\0]|, "-")
end
@doc """
Downloads the given url to a destination path generated by the provided function.
This function will return `{:error, :exists}` if the file already exists.
"""
@spec download((() -> {:ok, String.t()} | {:error, any()}), Path.t(), bool()) :: :ok | {:error, :exists | any()}
def download(f, destination, verbose) when is_function(f) do
with {:exists?, false} <- {:exists?, File.exists?(destination)},
{:ok, url} <- f.(),
:ok <- HTTPClient.download(%HTTPClient{}, url, destination, false, [], verbose) do
:ok
else
{:exists?, true} -> {:error, :exists}
{:error, reason} -> {:error, reason}
end
end
end