Compare commits

...

3 Commits

Author SHA1 Message Date
Nathan Mattes ae41d2799d Add download, json-parsing 2022-01-03 18:42:15 +01:00
Nathan Mattes 9423d7ea71 Make issues more elixir-y 2022-01-03 17:49:57 +01:00
Nathan Mattes 3f17b025a9 Add docs 2022-01-03 17:41:35 +01:00
4 changed files with 78 additions and 16 deletions

3
issues/config/config.exs Normal file
View File

@ -0,0 +1,3 @@
use Mix.Config
config :issues, github_url: "https://api.github.com"

View File

@ -7,28 +7,55 @@ defmodule Issues.CLI do
"""
def run(argv) do
parse_args(argv)
argv
|> parse_args
|> process
end
@doc """
`argv` can be -h or --help, which returns :help.
Otherwise it is a github user name, project name, and (optionally)
the number of entries to format.
Return a tuple of `{ user, project, count }`, or `:help` if help was given
"""
def parse_args(argv) do
parse =
OptionParser.parse(argv,
switches: [help: :boolean],
aliases: [h: :help]
)
OptionParser.parse(argv,
switches: [help: :boolean],
aliases: [h: :help]
)
|> elem(1)
|> args_to_internal_representation
case parse do
{[help: true], _, _} ->
:help
end
{_, [user, project, count], _} ->
{user, project, String.to_integer(count)}
def args_to_internal_representation([user, project, count]) do
{ user, project, String.to_integer(count) }
end
{_, [user, project], _} ->
{user, project, @default_count}
def args_to_internal_representation([user, project]) do
{ user, project, @default_count }
end
_ ->
:help
end
def args_to_internal_representation(_) do # either bad arg or --help
:help
end
def process(:help) do
IO.puts """
usage: issues <user> <project> [count | #{@default_count}]
"""
System.halt(0)
end
def process({user, project, count}) do
Issues.GithubIssues.fetch(user, project)
|> decode_response()
end
def decode_response({:ok, body}), do: body
def decode_response({:error, error}) do
IO.puts "Error fetching from Github: #{error["message"]}"
System.halt(2)
end
end

View File

@ -0,0 +1,30 @@
defmodule Issues.GithubIssues do
@user_agent [ { "User-agent", "Elixir dave@pragprog.com" } ]
# use a module attribute to fetch the value at compile time
@github_url Application.get_env(:issues, :github_url)
def fetch(user, project) do
issues_url(user, project)
|> HTTPoison.get(@user_agent)
|> handle_response
end
def issues_url(user, project) do
"#{@github_url}/repos/#{user}/#{project}/issues"
end
def handle_response( {:ok, %{status_code: status_code, body: body}} ) do
{
status_code |> check_for_error(),
body |> Poison.Parser.parse!()
}
end
def handle_response( {_, %{status_code: _, body: body}} ) do
{ :error, body }
end
defp check_for_error(200), do: :ok
defp check_for_error(_), do: :error
end

View File

@ -21,6 +21,8 @@ defmodule Issues.MixProject do
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:httpoison, "~> 1.8.0"},
{:poison, "~> 5.0"},
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]