4ed2c978940fcac2c4fd844f2924c52a80a6124c
[akkoma] / lib / mix / tasks / pleroma / config.ex
1 defmodule Mix.Tasks.Pleroma.Config do
2 use Mix.Task
3 import Mix.Pleroma
4 alias Pleroma.Repo
5 alias Pleroma.Web.AdminAPI.Config
6 @shortdoc "Manages the location of the config"
7 @moduledoc """
8 Manages the location of the config.
9
10 ## Transfers config from file to DB.
11
12 mix pleroma.config migrate_to_db
13
14 ## Transfers config from DB to file.
15
16 mix pleroma.config migrate_from_db ENV
17 """
18
19 def run(["migrate_to_db"]) do
20 start_pleroma()
21
22 if Pleroma.Config.get([:instance, :dynamic_configuration]) do
23 Application.get_all_env(:pleroma)
24 |> Enum.reject(fn {k, _v} -> k in [Pleroma.Repo, :env] end)
25 |> Enum.each(fn {k, v} ->
26 key = to_string(k) |> String.replace("Elixir.", "")
27 {:ok, _} = Config.update_or_create(%{group: "pleroma", key: key, value: v})
28 Mix.shell().info("#{key} is migrated.")
29 end)
30
31 Mix.shell().info("Settings migrated.")
32 else
33 Mix.shell().info(
34 "Migration is not allowed by config. You can change this behavior in instance settings."
35 )
36 end
37 end
38
39 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 Repo.all(Config)
49 |> Enum.each(fn config ->
50 mark = if String.starts_with?(config.key, "Pleroma."), do: ",", else: ":"
51
52 IO.write(
53 file,
54 "config :#{config.group}, #{config.key}#{mark} #{
55 inspect(Config.from_binary(config.value))
56 }\r\n"
57 )
58
59 {:ok, _} = Repo.delete(config)
60 Mix.shell().info("#{config.key} deleted from DB.")
61 end)
62
63 File.close(file)
64 System.cmd("mix", ["format", config_path])
65 else
66 Mix.shell().info(
67 "Migration is not allowed by config. You can change this behavior in instance settings."
68 )
69 end
70 end
71 end