-
-
Save coryt/00a12e73817334512263e2c9d4821795 to your computer and use it in GitHub Desktop.
Elixir-script template for the commandline.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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