92487dd5123d669d507ec3c9c10629a461c4f516
[akkoma] / lib / mix / tasks / pleroma / config.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Mix.Tasks.Pleroma.Config do
6 use Mix.Task
7 import Mix.Pleroma
8 alias Pleroma.Repo
9 alias Pleroma.Web.AdminAPI.Config
10 @shortdoc "Manages the location of the config"
11 @moduledoc File.read!("docs/administration/CLI_tasks/config.md")
12
13 @groups [
14 :pleroma,
15 :logger,
16 :quack,
17 :mime,
18 :tesla,
19 :phoenix,
20 :cors_plug,
21 :auto_linker,
22 :esshd,
23 :ueberauth,
24 :http_signatures,
25 :web_push_encryption,
26 :joken
27 ]
28
29 def run(["migrate_to_db"]) do
30 # we want to save original logger level
31 start_pleroma(false)
32
33 if Pleroma.Config.get([:configurable_from_database]) do
34 Enum.each(@groups, &load_and_create(&1))
35 else
36 Mix.shell().info(
37 "Migration is not allowed by config. You can change this behavior in instance settings."
38 )
39 end
40 end
41
42 def run(["migrate_from_db" | options]) do
43 start_pleroma()
44
45 {opts, _} =
46 OptionParser.parse!(options,
47 strict: [env: :string, delete_from_db: :boolean],
48 aliases: [d: :delete_from_db]
49 )
50
51 with {:active?, true} <-
52 {:active?, Pleroma.Config.get([:configurable_from_database])},
53 env_path when is_binary(env_path) <- opts[:env],
54 config_path <- "config/#{env_path}.exported_from_db.secret.exs",
55 {:ok, file} <- File.open(config_path, [:write, :utf8]) do
56 IO.write(file, "use Mix.Config\r\n")
57
58 Config
59 |> Repo.all()
60 |> Enum.each(&write_to_file_with_deletion(&1, file, opts[:delete_from_db]))
61
62 File.close(file)
63 System.cmd("mix", ["format", config_path])
64 else
65 {:active?, false} ->
66 Mix.shell().info(
67 "migration is not allowed by config. You can change this behavior in instance settings."
68 )
69
70 error ->
71 Mix.shell().info("error occuried while opening file. #{inspect(error)}")
72 end
73 end
74
75 defp load_and_create(group) do
76 group
77 |> Application.get_all_env()
78 |> Enum.reject(fn {k, _v} ->
79 k in [Pleroma.Repo, Pleroma.Web.Endpoint, :env, :configurable_from_database] or
80 (group == :phoenix and k == :serve_endpoints)
81 end)
82 |> Enum.each(fn {key, value} ->
83 key = inspect(key)
84 {:ok, _} = Config.update_or_create(%{group: inspect(group), key: key, value: value})
85
86 Mix.shell().info("settings for key #{key} migrated.")
87 end)
88
89 Mix.shell().info("settings for group :#{group} migrated.")
90 end
91
92 defp write_to_file_with_deletion(config, file, with_deletion) do
93 IO.write(
94 file,
95 "config #{config.group}, #{config.key}, #{
96 inspect(Config.from_binary(config.value), limit: :infinity)
97 }\r\n\r\n"
98 )
99
100 if with_deletion do
101 {:ok, _} = Repo.delete(config)
102 Mix.shell().info("#{config.key} deleted from DB.")
103 end
104 end
105 end