Improve parsing of params

This commit is contained in:
2024-05-21 00:52:27 +02:00
parent 841f776854
commit 8ba04b0290

View File

@@ -4,42 +4,92 @@ defmodule FindOldMp3s.Application do
""" """
def start(_, _) do def start(_, _) do
args = Burrito.Util.Args.get_arguments() get_options()
|> parse_options |> validate_options()
|> execute |> execute()
System.halt(0)
end end
defp parse_options(args) do defp get_options() do
options = OptionParser.parse( Burrito.Util.Args.get_arguments()
args, |> OptionParser.parse(
switches: [path: :string, type: :string, help: :boolean], strict: [path: :string, type: :keep, help: :boolean],
aliases: [p: :path, t: :type, h: :help] aliases: [p: :path, t: :type, h: :help]
) )
end
case options do defp validate_options({[], [], []}), do: {:error, :no_parameters}
{opts, [], []} ->
{:ok, opts}
{opts, b, c} -> defp validate_options({parsed, _argv, _errors}) do
{:error, :parsing_error} cond do
Keyword.has_key?(parsed, :help) ->
{:error, :show_help}
Keyword.has_key?(parsed, :path) and Keyword.has_key?(parsed, :type) ->
{:ok, parsed}
true ->
{:error, :missing_parameter}
end end
end end
defp execute({:error, :parsing_error}) do defp execute({:error, :no_parameters}) do
IO.puts """ IO.warn("No options given!")
Help command output
print_help()
System.halt(1)
end
defp execute({:error, :show_help}) do
print_help()
System.halt(1)
end
defp execute({:error, :missing_parameter}) do
IO.warn("Both parameters 'type' and 'path' must be set!")
print_help()
System.halt(1)
end
defp execute({:ok, opts}) do
file_types =
Keyword.get_values(opts, :type)
|> Enum.join(",")
file_path =
Keyword.get(opts, :path)
|> Path.expand()
files = Path.wildcard("#{file_path}/**/*.{#{file_types}}")
if Enum.empty?(files) do
IO.puts("No files found")
System.halt(0)
end
Enum.each(files, fn file -> IO.puts(file) end)
end
defp print_help() do
IO.puts("""
This command will find audio files with low bitrates in a folder folder (recursively) and shows the bitrate and
path to those files.
DESCRIPTION
Possible options: Possible options:
Long option short option description Long option short option description
--help -h Show this help --help -h Show this help
--type -t Give some file audio file type ending like 'ogg' or 'mp3' --type -t Give some file audio file type ending like 'ogg' or 'mp3' - can be used multiple
times
--path -p Root path to search files, search will be recursive --path -p Root path to search files, search will be recursive
"""
System.halt(1) EXAMPLE
end
defp execute() do find_old_mp3s --path "~" --type "ogg" --type "mp3"
System.halt(0)
""")
end end
end end