diff --git a/lib/cli.ex b/lib/cli.ex index fbad44f..b1c5881 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -4,16 +4,26 @@ defmodule Onigumo.CLI do } def main(argv) do - parsed = OptionParser.parse(argv, aliases: [C: :working_dir], strict: [working_dir: :string]) + parsed = + OptionParser.parse( + argv, + aliases: [h: :help, C: :working_dir], + strict: [help: :boolean, working_dir: :string] + ) - with {switches, [component], []} <- parsed, - {:ok, module} <- Map.fetch(@components, String.to_atom(component)) do - working_dir = Keyword.get(switches, :working_dir, File.cwd!()) - module.main(working_dir) + with {[help: true], [], []} <- parsed do + usage_message() else - {_, _, [_ | _]} -> usage_message() - {_, argv, _} when length(argv) != 1 -> usage_message() - :error -> usage_message() + _ -> + with {switches, [component], []} <- parsed, + {:ok, module} <- Map.fetch(@components, String.to_atom(component)) do + working_dir = Keyword.get(switches, :working_dir, File.cwd!()) + module.main(working_dir) + else + {_, _, [_ | _]} -> usage_message() + {_, argv, _} when length(argv) != 1 -> usage_message() + :error -> usage_message() + end end end @@ -28,6 +38,7 @@ defmodule Onigumo.CLI do COMPONENT\tOnigumo component to run, available: #{components} OPTIONS: + -h, --help\t\tPrint this help -C, --working-dir \tChange working dir to before running """) end diff --git a/test/onigumo_cli_test.exs b/test/onigumo_cli_test.exs index cefab8d..f593d9a 100644 --- a/test/onigumo_cli_test.exs +++ b/test/onigumo_cli_test.exs @@ -13,6 +13,12 @@ defmodule OnigumoCLITest do "-c" ] + @invalid_switch_combinations [ + "--help -C invalid", + "-h --invalid", + "downloader -h" + ] + @working_dir_switches [ "--working-dir", "-C" @@ -39,6 +45,12 @@ defmodule OnigumoCLITest do end end + for switches <- @invalid_switch_combinations do + test("run invalid combination of switches #{inspect(switches)} ") do + assert usage_message_printed?(fn -> Onigumo.CLI.main([unquote(switches)]) end) + end + end + @tag :tmp_dir test("run CLI with 'downloader' argument passing cwd", %{tmp_dir: tmp_dir}) do expect(OnigumoDownloaderMock, :main, fn working_dir -> working_dir end) @@ -60,6 +72,12 @@ defmodule OnigumoCLITest do end end + for switch <- ["-h", "--help"] do + test("run CLI with a #{inspect(switch)} switch") do + assert usage_message_printed?(fn -> Onigumo.CLI.main([unquote(switch)]) end) + end + end + defp usage_message_printed?(function) do output = capture_io(function) String.starts_with?(output, "Usage: onigumo ")