Last active
April 11, 2023 08:18
-
-
Save rob-brown/7237656 to your computer and use it in GitHub Desktop.
An Elixir sigil for executing terminal commands similar to Ruby.
This file contains 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
defmodule ExecuteSigil do | |
@doc """ | |
Handles the sigil %x. Takes the given command line string, unescapes the necessary | |
characters and replaces interpolations, executes it, and returns the | |
results as a string. | |
## Examples | |
iex> %x"echo Hello \x45\x6c\x69\x78\x69\x72\x21" | |
"Hello Elixir!\n" | |
""" | |
defmacro sigil_x({ :<<>>, _line, [string] }, []) when is_binary(string) do | |
string | |
|> Macro.unescape_string() | |
|> System.cmd() | |
end | |
defmacro sigil_x({ :<<>>, line, pieces }, []) do | |
binary = { :<<>>, line, Macro.unescape_tokens(pieces) } | |
quote do: System.cmd(unquote(binary)) | |
end | |
@doc """ | |
Handles the sigil %X. Takes the given command line string, executes it, and returns the | |
results as a string. Does not unescape characters or replace interpolations. | |
## Examples | |
iex> %X"echo Hello \x45\x6c\x69\x78\x69\x72\x21" | |
"Hello x45x6cx69x78x69x72x21\n" | |
""" | |
defmacro sigil_X({ :<<>>, _line, [string] }, []) when is_binary(string) do | |
System.cmd(string) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment