OptionParser and CLI

It’s less of a programming thing and more of a scripting thing - lots of RoR developers have never crafted a CLI, others live in IDEs creating logic that doesn’t rely on the command line. Now when it comes to shell scripting command line interface terminology is important - and Python is often used as a shell language replacement.

In your case I think Dave’s test first approach is leaving you hanging without a mental model of what is actually going on. Try this:

defmodule Issues.CLI do
  def main(argv) do
    IO.inspect argv
  end
end

Then modify the mix.exs:

  def project do
    [
      app: :issues,
      escript: [main_module: Issues.CLI], # ADD THIS LINE
      version: "0.1.0",
      elixir: "~> 1.6",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

And then run this:

$ mix escript.build
Compiling 2 files (.ex)
Generated issues app
Generated escript issues with MIX_ENV=dev

$ ./issues pragdave earmark 4
["pragdave", "earmark", "4"]
$ 

So the first thing you should notice is that the parameters are supplied to you as a list of strings - the arguments on the command line are white space delimited.

Now update cli.ex:

defmodule Issues.CLI do
  def main(argv) do
    IO.inspect(
      OptionParser.parse(
        argv,
        switches: [ help: :boolean],
        aliases: [ h: :help ]
      ))
  end
end

And run

$ mix escript.build
Compiling 1 file (.ex)
Generated escript issues with MIX_ENV=dev
$ ./issues pragdave earmark 4
{[], ["pragdave", "earmark", "4"], []}
$ ./issues --help
{[help: true], [], []}
$ ./issues -h
{[help: true], [], []}
$ ./issues -h pragdave earmark 4
{[help: true], ["pragdave", "earmark", "4"], []}
$ 
3 Likes