From fffc5d32db229d1cda7e41bba1d90c183c3796c9 Mon Sep 17 00:00:00 2001 From: Glutexo Date: Sat, 21 Oct 2023 21:01:31 +0200 Subject: [PATCH] Use Map instead of Module.safe_concat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CLI argument doesn’t need to be tightly coupled to the implementation detail of components being Elixir modules. ArgumentError raised by Module.safe_concat was only a symptom of that. Replaced with a mapping of string arguments (component names) to Elixir modules. As a result MatchError is raised when unknown component is passed, instead of a rather cryptic ArgumentError from Module.safe_concat. --- lib/cli.ex | 6 +++++- test/onigumo_cli_test.exs | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/cli.ex b/lib/cli.ex index 0ea12a9..1e2553a 100644 --- a/lib/cli.ex +++ b/lib/cli.ex @@ -1,7 +1,11 @@ defmodule Onigumo.CLI do + @components %{ + :Downloader => Onigumo.Downloader + } + def main(argv) do {[], [component]} = OptionParser.parse!(argv, strict: []) - module = Module.safe_concat("Onigumo", component) + {:ok, module} = Map.fetch(@components, String.to_atom(component)) root_path = File.cwd!() module.main(root_path) end diff --git a/test/onigumo_cli_test.exs b/test/onigumo_cli_test.exs index da24245..9a54cd9 100644 --- a/test/onigumo_cli_test.exs +++ b/test/onigumo_cli_test.exs @@ -22,7 +22,7 @@ defmodule OnigumoCLITest do end test("run CLI with invalid argument") do - assert_raise(ArgumentError, fn -> Onigumo.CLI.main(["Uploader"]) end) + assert_raise(MatchError, fn -> Onigumo.CLI.main(["Uploader"]) end) end test("run CLI with no arguments") do