defmodule GithubIssues.CLI do @default_count 4 import GithubIssues.TableFormatter @moduledoc """ Handle the command line parsing and the dispatch to the various functions that end up generating a table of the last_n_issues in a github project """ def main(argv) do argv |> parse_args |> process end def process(:unknown) do IO.puts "Unknown command, please try again" System.halt(0) end def process(:help) do IO.puts """ usage: issues [count | # {@default_count} ] """ System.halt(0) end def process({user, project, count}) do GithubIssues.Engine.fetch(user, project) |> decode_response |> convert_to_list_of_maps |> sort_into_asc_order |> Enum.take(count) |> print_table_for_columns(["number", "created_at", "title"]) end def decode_response({:ok, body}) do body end def decode_response({:error, error}) do {_, message} = List.keyfind(error, "message", 0) IO.puts "Error fetching from Github: #{message}" System.halt(2) end def convert_to_list_of_maps(list) do list |> Enum.map(&Enum.into(&1, Map.new)) end def sort_into_asc_order(list) do Enum.sort(list, fn(e1, e2) -> e1["created_at"] <= e2["created_at"] end) end def parse_args(argv) do parse = OptionParser.parse(argv, switches: [help: :boolean], aliases: [h: :help]) case parse do {[help: true], _, _} -> :help {_, [user, project, count], _} -> {user, project, String.to_integer(count)} {_, [user, project], _} -> {user, project, @default_count} _ -> :unknown end end end