0e03a78728f5bc6e267d85054632a9533d9296be
[akkoma] / lib / mix / tasks / pleroma / common.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2018 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Mix.Tasks.Pleroma.Common do
6 @doc "Common functions to be reused in mix tasks"
7 def start_pleroma do
8 Application.put_env(:phoenix, :serve_endpoints, false, persistent: true)
9 {:ok, _} = Application.ensure_all_started(:pleroma)
10 end
11
12 def get_option(options, opt, prompt, defval \\ nil, defname \\ nil) do
13 Keyword.get(options, opt) || shell_prompt(prompt, defval, defname)
14 end
15
16 def shell_prompt(prompt, defval \\ nil, defname \\ nil) do
17 prompt_message = "#{prompt} [#{defname || defval}]"
18
19 input =
20 if mix_shell?(),
21 do: Mix.shell().prompt(prompt_message),
22 else: :io.get_line(prompt_message)
23
24 case input do
25 "\n" ->
26 case defval do
27 nil ->
28 shell_prompt(prompt, defval, defname)
29
30 defval ->
31 defval
32 end
33
34 input ->
35 String.trim(input)
36 end
37 end
38
39 def shell_yes?(message) do
40 shell_prompt(message, "Yn") in ~w(Yn Y y)
41 end
42
43 def shell_info(message) do
44 if mix_shell?(),
45 do: Mix.shell().info(message),
46 else: IO.puts(message)
47 end
48
49 def shell_error(message) do
50 if mix_shell?(),
51 do: Mix.shell().error(message),
52 else: IO.puts(:stderr, message)
53 end
54
55 @doc "Performs a safe check whether `Mix.shell/0` is available (does not raise if Mix is not loaded)"
56 def mix_shell?, do: :erlang.function_exported(Mix, :shell, 0)
57
58 def escape_sh_path(path) do
59 ~S(') <> String.replace(path, ~S('), ~S(\')) <> ~S(')
60 end
61 end