/* * Copyright 2016 - 2022 Gary Talent (gary@drinkingtea.net). All rights reserved. */ #pragma once #include #include #include #include #include #include #include #include #include namespace nostalgia::studio { [[nodiscard]] ox::String configPath(const core::Context *ctx) noexcept; template ox::Result readConfig(core::Context *ctx, ox::CRStringView name) noexcept { oxAssert(ox_strcmp(name, ""), "Config type has no TypeName"); const auto path = ox::sfmt("/{}.json", name); ox::PassThroughFS fs(configPath(ctx)); const auto [buff, err] = fs.read(path); if (err) { oxErrf("Could not read config file: {}\n", toStr(err)); return err; } return ox::readOC(buff); } template ox::Result readConfig(core::Context *ctx) noexcept { constexpr auto TypeName = ox::requireModelTypeName(); return readConfig(ctx, TypeName); } template ox::Error writeConfig(core::Context *ctx, ox::CRStringView name, T *data) noexcept { oxAssert(ox_strcmp(name, ""), "Config type has no TypeName"); const auto path = ox::sfmt("/{}.json", name); ox::PassThroughFS fs(configPath(ctx)); if (const auto err = fs.mkdir("/", true)) { oxErrf("Could not create config directory: {}\n", toStr(err)); return err; } oxRequireM(buff, ox::writeOC(data)); buff.back().value = '\n'; if (const auto err = fs.write(path, buff.data(), buff.size())) { oxErrf("Could not read config file: {}\n", toStr(err)); return OxError(2, "Could not read config file"); } return OxError(0); } template ox::Error writeConfig(core::Context *ctx, T *data) noexcept { constexpr auto TypeName = ox::requireModelTypeName(); return writeConfig(ctx, TypeName, data); } template void openConfig(core::Context *ctx, const auto &name, Func f) noexcept { oxAssert(name != "", "Config type has no TypeName"); const auto c = readConfig(ctx, name); f(&c.value); } template void openConfig(core::Context *ctx, Func f) noexcept { constexpr auto TypeName = ox::requireModelTypeName(); openConfig(ctx, TypeName, f); } template void editConfig(core::Context *ctx, const auto &name, Func f) noexcept { oxAssert(ox_strcmp(name, ""), "Config type has no TypeName"); auto c = readConfig(ctx, name); f(&c.value); oxLogError(writeConfig(ctx, name, &c.value)); } template void editConfig(core::Context *ctx, Func f) noexcept { constexpr auto TypeName = ox::requireModelTypeName(); editConfig(ctx, TypeName, f); } }