Added a basic CLI

This commit is contained in:
Ben Shiller 2024-10-12 20:50:00 -05:00
parent caa9a46c1b
commit bf061c4a93
Signed by: shillerben
GPG Key ID: 7B4602B1FBF82986
4 changed files with 78 additions and 4 deletions

43
lib/elixir_rss/cli.ex Normal file
View File

@ -0,0 +1,43 @@
defmodule ElixirRss.CLI do
@default_host "0.0.0.0"
@default_port 8080
@default_basepath "/"
def run(argv) do
parse_args(argv)
|> process()
end
def parse_args(argv) do
OptionParser.parse(
argv,
strict: [help: :boolean,
host: :string,
port: :integer,
path: :string],
aliases: [h: :help])
|> elem(0)
|> switches_to_internal()
end
defp switches_to_internal(kwargs) do
if Keyword.get(kwargs, :help) do
:help
else
{Keyword.get(kwargs, :host, @default_host),
Keyword.get(kwargs, :port, @default_port),
Keyword.get(kwargs, :path, @default_basepath)}
end
end
defp process(:help) do
IO.puts("""
usage: elixir_rss [--host HOST] [--port PORT] [--path BASEPATH]
""")
System.halt(0)
end
defp process({host, port, path}) do
IO.puts("Host: #{host}, Port: #{port}, Basepath: #{path}")
end
end

View File

@ -1,4 +1,4 @@
defmodule ElixirRss.Fetch do defmodule ElixirRss.Http do
def fetch(url) do def fetch(url) do
url url
|> HTTPoison.get() |> HTTPoison.get()

31
test/cli_test.exs Normal file
View File

@ -0,0 +1,31 @@
defmodule CliTest do
use ExUnit.Case
doctest ElixirRss
import ElixirRss.CLI, only: [parse_args: 1]
test ":help returned for -h, --help, and default" do
assert parse_args(["-h"]) == :help
assert parse_args(["--help"]) == :help
assert parse_args(["other", "-h", "stuff"]) == :help
assert parse_args(["other", "--help", "stuff"]) == :help
end
test "all switches given" do
assert parse_args(["--host", "127.0.0.1", "--port", "80", "--path", "/path"]) == {"127.0.0.1", 80, "/path"}
end
test "defaults returned for missing args" do
assert parse_args([]) == {"0.0.0.0", 8080, "/"}
assert parse_args(["--host", "127.0.0.1"]) == {"127.0.0.1", 8080, "/"}
assert parse_args(["--port", "80"]) == {"0.0.0.0", 80, "/"}
assert parse_args(["--path", "/path"]) == {"0.0.0.0", 8080, "/path"}
assert parse_args(["--host", "127.0.0.1", "--port", "80"]) == {"127.0.0.1", 80, "/"}
assert parse_args(["--host", "127.0.0.1", "--path", "/path"]) == {"127.0.0.1", 8080, "/path"}
assert parse_args(["--port", "80", "--path", "/path"]) == {"0.0.0.0", 80, "/path"}
end
test "out of order switches" do
assert parse_args(["--port", "80", "--host", "127.0.0.1", "--path", "/path"]) == {"127.0.0.1", 80, "/path"}
end
end

View File

@ -1,8 +1,8 @@
defmodule ElixirRss.FetchTest do defmodule HttpTest do
use ExUnit.Case use ExUnit.Case
doctest ElixirRss.Fetch doctest ElixirRss
test "fetch url" do test "fetch url" do
assert ElixirRss.Fetch.fetch("https://shillerben.com") |> elem(0) == :ok assert ElixirRss.Http.fetch("https://shillerben.com") |> elem(0) == :ok
end end
end end