config.ex 1.96 KB
Newer Older
1 2
defmodule Mix.Tasks.Pleroma.Config do
  use Mix.Task
3
  import Mix.Pleroma
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
  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
20
    start_pleroma()
21 22 23 24 25 26

    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.", "")
27
        {:ok, _} = Config.update_or_create(%{group: "pleroma", key: key, value: v})
28 29 30 31 32 33 34 35 36 37 38 39
        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
40
    start_pleroma()
41 42

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

      {:ok, file} = File.open(config_path, [:write])
46
      IO.write(file, "use Mix.Config\r\n")
47 48 49 50 51 52 53

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

        IO.write(
          file,
54 55 56
          "config :#{config.group}, #{config.key}#{mark} #{
            inspect(Config.from_binary(config.value))
          }\r\n"
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        )

        {: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