gitlab-push-triggerer/lib/triggerer.ex
2018-02-25 00:26:58 +02:00

81 lines
2.2 KiB
Elixir

defmodule Triggerer do
require Logger
@doc """
Get all matching environment variables and their values. Returns a map where keys are the transformed
paths and values are the given script paths.
## Examples
In these examples, sample env is given as argument. If no argument is given, system env is used.
iex> Triggerer.get_envs(%{"TRIGGERER_FOO" => "./test.sh"})
%{"foo" => "./test.sh"}
iex> Triggerer.get_envs(%{})
%{}
iex> Triggerer.get_envs(%{"WRONG_FORMAT" => "no", "TRIGGERER_BAR_" => "baz", "TRIGGERER_" => "no", "TRIGGERER_GO_WILD" => "/bin/true"})
%{"bar-" => "baz", "go-wild" => "/bin/true"}
"""
@spec get_envs(%{optional(String.t()) => String.t()}) :: map
def get_envs(envs \\ nil) do
envs = envs || System.get_env()
envs
|> Map.keys()
|> Enum.reduce(%{}, fn
"TRIGGERER_" <> rest = key, acc when rest != "" ->
path = transform_path(rest)
Map.put(acc, path, envs[key])
_, acc ->
acc
end)
end
@doc """
Transform a given path from environment variable style to endpoint style. That is, downcase it and
replace underscores with dashes.
## Examples
iex> Triggerer.transform_path("YKSI_KAKSI")
"yksi-kaksi"
iex> Triggerer.transform_path("FOO")
"foo"
iex> Triggerer.transform_path("ÄNKYRÄ_KÖNKYRÄ_")
"änkyrä-könkyrä-"
"""
@spec transform_path(String.t()) :: String.t()
def transform_path(path) when is_binary(path) do
String.split(path, "_")
|> Enum.map(&String.downcase/1)
|> Enum.join("-")
end
@doc """
Run given script or return an error.
"""
@spec run(String.t()) :: :ok | {:error, atom}
def run(script) do
runner = fn script ->
try do
{output, status} = System.cmd("sh", ["-c", script])
Logger.debug("Executed #{script} with return status #{status}. Output:\n\n#{output}")
rescue
err -> Logger.error("#{script} execution failed with: #{inspect(err)}")
end
end
if File.exists?(script) do
{:ok, pid} = Task.start(fn -> runner.(script) end)
Logger.debug("Started task #{script} with pid #{inspect(pid)}")
:ok
else
{:error, :file_not_found}
end
end
end