From e0330fdec0eca781912fbb8b3a948a57eefe1d80 Mon Sep 17 00:00:00 2001 From: Rob Watson Date: Sat, 7 Apr 2018 10:07:31 +0200 Subject: [PATCH] Add basic CLI --- lib/amazon_history/cli.ex | 50 ++++++++++++++++++++++++++++++++ test/amazon_history/cli_test.exs | 31 ++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 lib/amazon_history/cli.ex create mode 100644 test/amazon_history/cli_test.exs diff --git a/lib/amazon_history/cli.ex b/lib/amazon_history/cli.ex new file mode 100644 index 0000000..e7e7c2d --- /dev/null +++ b/lib/amazon_history/cli.ex @@ -0,0 +1,50 @@ +defmodule AmazonHistory.CLI do + @moduledoc """ + Handle the command-line parsing for the amazon_history tool + """ + + def run(argv) do + argv + |> parse_args + |> process + end + + def process(username: username, password: password) do + IO.puts("Will continue with username: #{username}, password: #{password}") + end + + def process(_) do + IO.puts("Usage: --username --password ") + end + + @doc """ + Options: + -u/--username: Amazon username + -p/--password: Amazon password + """ + def parse_args(argv) do + OptionParser.parse( + argv, + switches: [ + help: :boolean, + username: :string, + password: :string + ], + aliases: [ + h: :help, + u: :username, + p: :password + ] + ) + |> elem(0) + |> args_to_internal_representation + end + + defp args_to_internal_representation(username: username, password: password) do + [username: username, password: password] + end + + defp args_to_internal_representation(_) do + :help + end +end diff --git a/test/amazon_history/cli_test.exs b/test/amazon_history/cli_test.exs new file mode 100644 index 0000000..a5737ec --- /dev/null +++ b/test/amazon_history/cli_test.exs @@ -0,0 +1,31 @@ +defmodule CliTest do + use ExUnit.Case + + describe "parse_args/1" do + import AmazonHistory.CLI, only: [parse_args: 1] + + test ":help returned by passing -h and --help options" do + assert parse_args(["-h"]) == :help + assert parse_args(["--help"]) == :help + end + + test ":help returned by passing only a username" do + assert parse_args(["-u", "rob"]) == :help + assert parse_args(["--username", "rob"]) == :help + end + + test ":help returned by passing only a password" do + assert parse_args(["-p", "hackme"]) == :help + assert parse_args(["--password", "hackme"]) == :help + end + + test "arguments returned by passing valid parameters" do + assert parse_args(["-u", "rob", "-p", "hackme"]) == [username: "rob", password: "hackme"] + + assert parse_args(["--username", "rob", "--password", "hackme"]) == [ + username: "rob", + password: "hackme" + ] + end + end +end