Skip to content

Instantly share code, notes, and snippets.

@iboard
Last active April 15, 2020 08:07
Show Gist options
  • Save iboard/2da864d796759da619f0838077e273b0 to your computer and use it in GitHub Desktop.
Save iboard/2da864d796759da619f0838077e273b0 to your computer and use it in GitHub Desktop.
Elixir-script template for the commandline.
#!/usr/bin/env elixir
#
# A Template for writing an Elixir script to be used on the
# command-line.
#
# (c) 2019 by Andreas Altendorfer <[email protected]>
# License: Free to use without any warranty.
#
# Usage:
# 1. Add your command to strict and aliases on @opts
# 2. Implement your function (rename my_script() )
# 3. Call your script in `run()` (line 38)
#
defmodule Shell do
alias IO.{ANSI}
#
# Add your script here
#
@opts [
strict: [
cmd: :string,
my_cmd: :string
],
aliases: [
c: :cmd,
m: :my_cmd
]
]
def my_script(str, _args) do
str |> String.upcase()
end
#
# Call your script here
#
def run(args) do
args
|> case do
{[cmd: cmd], args} -> system(cmd, args)
{[my_cmd: cmd], args} -> my_script(cmd, args)
_ -> no_command()
end
end
# Default
def no_command(), do: red("ERROR: No command")
# Example: Execute a system command. e.g. `-c ls`
def system(cmd, args) do
{result, _err} = System.cmd(cmd, args)
[blue(cmd), red(inspect(args)), green(result |> String.trim())]
|> Enum.join("\n")
end
def main(args) do
OptionParser.parse!(args, @opts)
|> run
end
defp blue(str), do: [ANSI.blue(), str, ANSI.reset()] |> Enum.join()
defp green(str), do: [ANSI.green(), str, ANSI.reset()] |> Enum.join()
defp red(str), do: [ANSI.red(), str, ANSI.reset()] |> Enum.join()
end
#
# MAIN
#
System.argv()
|> Shell.main()
|> IO.puts()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment