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] || Mix.env()
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])
108 shell_info("Database configuration settings have been exported to config/#{env}.exported_from_db.secret.exs")
114 defp migration_error do
116 "Migration is not allowed in config. You can change this behavior by setting `config :pleroma, configurable_from_database: true`"
120 if Code.ensure_loaded?(Config.Reader) do
121 defp config_header, do: "import Config\r\n\r\n"
122 defp read_file(config_file), do: Config.Reader.read_imports!(config_file)
124 defp config_header, do: "use Mix.Config\r\n\r\n"
125 defp read_file(config_file), do: Mix.Config.eval!(config_file)
128 defp write_and_delete(config, file, delete?) do
134 defp write(config, file) do
135 value = inspect(config.value, limit: :infinity)
137 IO.write(file, "config #{inspect(config.group)}, #{inspect(config.key)}, #{value}\r\n\r\n")
142 defp delete(config, true) do
143 {:ok, _} = Repo.delete(config)
144 shell_info("#{config.key} deleted from DB.")
147 defp delete(_config, _), do: :ok