diff --git a/lib/cli.ex b/lib/cli.ex index 0e91033..6a76a11 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -4,11 +4,15 @@ defmodule Onigumo.CLI do } def main(argv) do - case OptionParser.parse(argv, strict: []) do - {[], [component], []} -> + case OptionParser.parse( + argv, + aliases: [C: :working_dir], + strict: [working_dir: :string] + ) do + {parsed_switches, [component], []} -> {:ok, module} = Map.fetch(@components, String.to_atom(component)) - root_path = File.cwd!() - module.main(root_path) + working_dir = Keyword.get(parsed_switches, :working_dir, File.cwd!()) + module.main(working_dir) _ -> usage_message() @@ -19,11 +23,14 @@ defmodule Onigumo.CLI do components = Enum.join(Map.keys(@components), ", ") IO.puts(""" - Usage: onigumo [COMPONENT] + Usage: onigumo [OPTION]... [COMPONENT] Simple program that retrieves HTTP web content as structured data. COMPONENT\tOnigumo component to run, available: #{components} + + OPTIONS: + -C, --working-dir \tChange working dir to before running """) end end diff --git a/test/onigumo_cli_test.exs b/test/onigumo_cli_test.exs index abf9d96..c0d51ba 100644 --- a/test/onigumo_cli_test.exs +++ b/test/onigumo_cli_test.exs @@ -8,6 +8,16 @@ defmodule OnigumoCLITest do "uploader" ] + @invalid_switches [ + "--invalid", + "-c" + ] + + @working_dir_switches [ + "--working-dir", + "-C" + ] + describe("Onigumo.CLI.main/1") do for argument <- @invalid_arguments do test("run CLI with invalid argument #{inspect(argument)}") do @@ -23,18 +33,33 @@ defmodule OnigumoCLITest do assert usage_message_printed?(fn -> Onigumo.CLI.main(["Downloader", "Parser"]) end) end - test("run CLI with invalid switch") do - assert usage_message_printed?(fn -> Onigumo.CLI.main(["--invalid"]) end) + for switch <- @invalid_switches do + test("run CLI with invalid switch #{inspect(switch)}") do + assert usage_message_printed?(fn -> Onigumo.CLI.main([unquote(switch)]) end) + end end @tag :tmp_dir test("run CLI with 'downloader' argument passing cwd", %{tmp_dir: tmp_dir}) do - expect(OnigumoDownloaderMock, :main, fn root_path -> root_path end) + expect(OnigumoDownloaderMock, :main, fn working_dir -> working_dir end) File.cd(tmp_dir) assert Onigumo.CLI.main(["downloader"]) == tmp_dir end + for switch <- @working_dir_switches do + @tag :tmp_dir + test("run CLI 'downloader' with #{inspect(switch)} switch", %{tmp_dir: tmp_dir}) do + expect(OnigumoDownloaderMock, :main, fn working_dir -> working_dir end) + + assert Onigumo.CLI.main(["downloader", unquote(switch), tmp_dir]) == tmp_dir + end + + test("run CLI 'downloader' with #{inspect(switch)} without any value") do + assert usage_message_printed?(fn -> Onigumo.CLI.main(["downloader", unquote(switch)]) end) + end + end + defp usage_message_printed?(function) do output = capture_io(function) String.starts_with?(output, "Usage: onigumo ")