1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Mix.Tasks.Pleroma.Config do
10 alias Pleroma.ConfigDB
13 @shortdoc "Manages the location of the config"
14 @moduledoc File.read!("docs/administration/CLI_tasks/config.md")
16 def run(["migrate_to_db"]) do
21 def run(["migrate_from_db" | options]) do
25 OptionParser.parse!(options,
26 strict: [env: :string, delete: :boolean],
33 @spec migrate_to_db(Path.t() | nil) :: any()
34 def migrate_to_db(file_path \\ nil) do
35 if Pleroma.Config.get([:configurable_from_database]) do
40 if Pleroma.Config.get(:release) do
41 Pleroma.Config.get(:config_path)
43 "config/#{Pleroma.Config.get(:env)}.secret.exs"
47 do_migrate_to_db(config_file)
53 defp do_migrate_to_db(config_file) do
54 if File.exists?(config_file) do
55 shell_info("Migrating settings from file: #{Path.expand(config_file)}")
56 Ecto.Adapters.SQL.query!(Repo, "TRUNCATE config;")
57 Ecto.Adapters.SQL.query!(Repo, "ALTER SEQUENCE config_id_seq RESTART;")
66 |> Enum.each(&create(&1, custom_config))
68 shell_info("To migrate settings, you must define custom settings in #{config_file}.")
72 defp create(group, settings) do
74 |> Pleroma.Config.Loader.filter_group(settings)
75 |> Enum.each(fn {key, value} ->
76 {:ok, _} = ConfigDB.update_or_create(%{group: group, key: key, value: value})
78 shell_info("Settings for key #{key} migrated.")
81 shell_info("Settings for group :#{group} migrated.")
84 defp migrate_from_db(opts) do
85 if Pleroma.Config.get([:configurable_from_database]) do
86 env = opts[:env] || "prod"
89 if Pleroma.Config.get(:release) do
91 |> Pleroma.Config.get()
96 |> Path.join("#{env}.exported_from_db.secret.exs")
98 file = File.open!(config_path, [:write, :utf8])
100 IO.write(file, config_header())
104 |> Enum.each(&write_and_delete(&1, file, opts[:delete]))
106 :ok = File.close(file)
107 System.cmd("mix", ["format", config_path])
113 defp migration_error do
115 "Migration is not allowed in config. You can change this behavior by setting `configurable_from_database` to true."
119 if Code.ensure_loaded?(Config.Reader) do
120 defp config_header, do: "import Config\r\n\r\n"
121 defp read_file(config_file), do: Config.Reader.read_imports!(config_file)
123 defp config_header, do: "use Mix.Config\r\n\r\n"
124 defp read_file(config_file), do: Mix.Config.eval!(config_file)
127 defp write_and_delete(config, file, delete?) do
133 defp write(config, file) do
134 value = inspect(config.value, limit: :infinity)
136 IO.write(file, "config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
141 defp delete(config, true) do
142 {:ok, _} = Repo.delete(config)
143 shell_info("#{config.key} deleted from DB.")
146 defp delete(_config, _), do: :ok