From 8ba04b0290cca8679324486102412a50d9bf153d Mon Sep 17 00:00:00 2001 From: Pascal Schmid Date: Tue, 21 May 2024 00:52:27 +0200 Subject: [PATCH] Improve parsing of params --- lib/find_old_mp3s.ex | 98 +++++++++++++++++++++++++++++++++----------- 1 file changed, 74 insertions(+), 24 deletions(-) diff --git a/lib/find_old_mp3s.ex b/lib/find_old_mp3s.ex index c9f2e95..6d330bd 100644 --- a/lib/find_old_mp3s.ex +++ b/lib/find_old_mp3s.ex @@ -4,42 +4,92 @@ defmodule FindOldMp3s.Application do """ def start(_, _) do - args = Burrito.Util.Args.get_arguments() - |> parse_options - |> execute + get_options() + |> validate_options() + |> execute() + + System.halt(0) end - defp parse_options(args) do - options = OptionParser.parse( - args, - switches: [path: :string, type: :string, help: :boolean], + defp get_options() do + Burrito.Util.Args.get_arguments() + |> OptionParser.parse( + strict: [path: :string, type: :keep, help: :boolean], aliases: [p: :path, t: :type, h: :help] ) + end - case options do - {opts, [], []} -> - {:ok, opts} + defp validate_options({[], [], []}), do: {:error, :no_parameters} - {opts, b, c} -> - {:error, :parsing_error} + defp validate_options({parsed, _argv, _errors}) do + 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 - defp execute({:error, :parsing_error}) do - IO.puts """ - Help command output - - Possible options: - Long option short option description - --help -h Show this help - --type -t Give some file audio file type ending like 'ogg' or 'mp3' - --path -p Root path to search files, search will be recursive - """ + defp execute({:error, :no_parameters}) do + IO.warn("No options given!") + print_help() System.halt(1) end - defp execute() do - System.halt(0) + 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: + Long option short option description + --help -h Show this help + --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 + + EXAMPLE + + find_old_mp3s --path "~" --type "ogg" --type "mp3" + + """) end end