Skip to content

Commit

Permalink
Merge pull request #206 from nappex/cli-help
Browse files Browse the repository at this point in the history
CLI usage message
  • Loading branch information
Glutexo authored Jan 26, 2024
2 parents 4702701 + 58e365d commit f727206
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
27 changes: 23 additions & 4 deletions lib/cli.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,28 @@ defmodule Onigumo.CLI do
}

def main(argv) do
{[], [component]} = OptionParser.parse!(argv, strict: [])
{:ok, module} = Map.fetch(@components, String.to_atom(component))
root_path = File.cwd!()
module.main(root_path)
try do
{[], [component]} = OptionParser.parse!(argv, strict: [])
component
rescue
_ in [OptionParser.ParseError, MatchError] -> usage_message()
else
component ->
{:ok, module} = Map.fetch(@components, String.to_atom(component))
root_path = File.cwd!()
module.main(root_path)
end
end

defp usage_message() do
components = Enum.join(Map.keys(@components), ", ")

IO.puts("""
Usage: onigumo [COMPONENT]
Simple program that retrieves HTTP web content as structured data.
COMPONENT\tOnigumo component to run, available: #{components}
""")
end
end
12 changes: 9 additions & 3 deletions test/onigumo_cli_test.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defmodule OnigumoCLITest do
use ExUnit.Case
import ExUnit.CaptureIO
import Mox

@urls [
Expand Down Expand Up @@ -33,15 +34,20 @@ defmodule OnigumoCLITest do
end

test("run CLI with no arguments") do
assert_raise(MatchError, fn -> Onigumo.CLI.main([]) end)
assert usage_message_printed?(fn -> Onigumo.CLI.main([]) end)
end

test("run CLI with more than one argument") do
assert_raise(MatchError, fn -> Onigumo.CLI.main(["Downloader", "Parser"]) end)
assert usage_message_printed?(fn -> Onigumo.CLI.main(["Downloader", "Parser"]) end)
end

test("run CLI with invalid switch") do
assert_raise(OptionParser.ParseError, fn -> Onigumo.CLI.main(["--help"]) end)
assert usage_message_printed?(fn -> Onigumo.CLI.main(["--invalid"]) end)
end

defp usage_message_printed?(function) do
output = capture_io(function)
String.starts_with?(output, "Usage: onigumo ")
end
end
end

0 comments on commit f727206

Please sign in to comment.