aboutsummaryrefslogtreecommitdiff
path: root/lib/mix/tasks/pleroma/config.ex
blob: 1fe03088d942d1098a08f9620b520490395646ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
defmodule Mix.Tasks.Pleroma.Config do
  use Mix.Task
  alias Mix.Tasks.Pleroma.Common
  alias Pleroma.Repo
  alias Pleroma.Web.AdminAPI.Config
  @shortdoc "Manages the location of the config"
  @moduledoc """
  Manages the location of the config.

  ## Transfers config from file to DB.

      mix pleroma.config migrate_to_db

  ## Transfers config from DB to file.

      mix pleroma.config migrate_from_db ENV
  """

  def run(["migrate_to_db"]) do
    Common.start_pleroma()

    if Pleroma.Config.get([:instance, :dynamic_configuration]) do
      Application.get_all_env(:pleroma)
      |> Enum.reject(fn {k, _v} -> k in [Pleroma.Repo, :env] end)
      |> Enum.each(fn {k, v} ->
        key = to_string(k) |> String.replace("Elixir.", "")
        {:ok, _} = Config.update_or_create(%{key: key, value: v})
        Mix.shell().info("#{key} is migrated.")
      end)

      Mix.shell().info("Settings migrated.")
    else
      Mix.shell().info(
        "Migration is not allowed by config. You can change this behavior in instance settings."
      )
    end
  end

  def run(["migrate_from_db", env]) do
    Common.start_pleroma()

    if Pleroma.Config.get([:instance, :dynamic_configuration]) do
      config_path = "config/#{env}.migrated.secret.exs"

      {:ok, file} = File.open(config_path, [:write])

      Repo.all(Config)
      |> Enum.each(fn config ->
        mark = if String.starts_with?(config.key, "Pleroma."), do: ",", else: ":"

        IO.write(
          file,
          "config :pleroma, #{config.key}#{mark} #{inspect(Config.from_binary(config.value))}\r\n"
        )

        {:ok, _} = Repo.delete(config)
        Mix.shell().info("#{config.key} deleted from DB.")
      end)

      File.close(file)
      System.cmd("mix", ["format", config_path])
    else
      Mix.shell().info(
        "Migration is not allowed by config. You can change this behavior in instance settings."
      )
    end
  end
end