aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.config/write.cc
blob: 2b451bd25c1843c554ccb8100f79ada8b0cd3e3e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
 * This source code is released into the public domain.
 */

module;

#include <expected>
#include <filesystem>
#include <format>
#include <utility>

import nihil;
import nihil.ucl;

module nihil.config;

namespace nihil::config {

auto write_to(std::filesystem::path const &filename)
	-> std::expected<void, nihil::error>
try {
	auto uclconfig = ucl::map<ucl::object>();

	// Add all the options to the UCL object.
	for (auto const &option : store::get().all()) {
		if (option.is_default())
			continue;

		uclconfig.insert({option.name(), option.to_ucl()});
	}

	auto ucl_text = std::format("{:c}", uclconfig);
	auto ret = safe_write_file(filename, ucl_text);
	if (!ret)
		return std::unexpected(nihil::error(
			std::format("cannot write {}", filename.string()),
			ret.error()));

	return {};
} catch (ucl::error const &exc) {
	return std::unexpected(nihil::error(
			"failed to serialize configuration",
			nihil::error(exc.what())));
}

};