Skip to content

Commit

Permalink
improve: config manager context from string to source location (opent…
Browse files Browse the repository at this point in the history
…ibiabr#2955)

Change from std::string hardcoded to std::source_location from
ConfigManager functions (getNumber, getString, getBoolean, getFloat)

In addition to displaying the exact line from the log, this approach is
also more concise as it eliminates the need to pass a second argument.
  • Loading branch information
dudantas authored Oct 9, 2024
1 parent adbe715 commit 90e205d
Show file tree
Hide file tree
Showing 73 changed files with 490 additions and 491 deletions.
38 changes: 19 additions & 19 deletions src/canary_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,16 @@ int CanaryServer::run() {
try {
loadConfigLua();

logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__) ? " and 10x allowed!" : "");
logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL) ? " and 10x allowed!" : "");
#ifdef FEATURE_METRICS
metrics::Options metricsOptions;
metricsOptions.enablePrometheusExporter = g_configManager().getBoolean(METRICS_ENABLE_PROMETHEUS, __FUNCTION__);
metricsOptions.enablePrometheusExporter = g_configManager().getBoolean(METRICS_ENABLE_PROMETHEUS);
if (metricsOptions.enablePrometheusExporter) {
metricsOptions.prometheusOptions.url = g_configManager().getString(METRICS_PROMETHEUS_ADDRESS, __FUNCTION__);
metricsOptions.prometheusOptions.url = g_configManager().getString(METRICS_PROMETHEUS_ADDRESS);
}
metricsOptions.enableOStreamExporter = g_configManager().getBoolean(METRICS_ENABLE_OSTREAM, __FUNCTION__);
metricsOptions.enableOStreamExporter = g_configManager().getBoolean(METRICS_ENABLE_OSTREAM);
if (metricsOptions.enableOStreamExporter) {
metricsOptions.ostreamOptions.export_interval_millis = std::chrono::milliseconds(g_configManager().getNumber(METRICS_OSTREAM_INTERVAL, __FUNCTION__));
metricsOptions.ostreamOptions.export_interval_millis = std::chrono::milliseconds(g_configManager().getNumber(METRICS_OSTREAM_INTERVAL));
}
g_metrics().init(metricsOptions);
#endif
Expand Down Expand Up @@ -98,7 +98,7 @@ int CanaryServer::run() {

g_game().start(&serviceManager);
g_game().setGameState(GAME_STATE_NORMAL);
if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE, __FUNCTION__)) {
if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE)) {
g_game().setGameState(GAME_STATE_CLOSED);
g_logger().warn("Initialized in maintain mode!");
g_webhook().sendMessage(":yellow_square: Server is now **online** _(access restricted to staff)_");
Expand Down Expand Up @@ -132,7 +132,7 @@ int CanaryServer::run() {
return EXIT_FAILURE;
}

logger.info("{} {}", g_configManager().getString(SERVER_NAME, __FUNCTION__), "server online!");
logger.info("{} {}", g_configManager().getString(SERVER_NAME), "server online!");

serviceManager.run();

Expand All @@ -141,7 +141,7 @@ int CanaryServer::run() {
}

void CanaryServer::setWorldType() {
const std::string worldType = asLowerCaseString(g_configManager().getString(WORLD_TYPE, __FUNCTION__));
const std::string worldType = asLowerCaseString(g_configManager().getString(WORLD_TYPE));
if (worldType == "pvp") {
g_game().setWorldType(WORLD_TYPE_PVP);
} else if (worldType == "no-pvp") {
Expand All @@ -152,7 +152,7 @@ void CanaryServer::setWorldType() {
throw FailedToInitializeCanary(
fmt::format(
"Unknown world type: {}, valid world types are: pvp, no-pvp and pvp-enforced",
g_configManager().getString(WORLD_TYPE, __FUNCTION__)
g_configManager().getString(WORLD_TYPE)
)
);
}
Expand All @@ -162,11 +162,11 @@ void CanaryServer::setWorldType() {

void CanaryServer::loadMaps() const {
try {
g_game().loadMainMap(g_configManager().getString(MAP_NAME, __FUNCTION__));
g_game().loadMainMap(g_configManager().getString(MAP_NAME));

// If "mapCustomEnabled" is true on config.lua, then load the custom map
if (g_configManager().getBoolean(TOGGLE_MAP_CUSTOM, __FUNCTION__)) {
g_game().loadCustomMaps(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/world/custom/");
if (g_configManager().getBoolean(TOGGLE_MAP_CUSTOM)) {
g_game().loadCustomMaps(g_configManager().getString(DATA_DIRECTORY) + "/world/custom/");
}
Zone::refreshAll();
} catch (const std::exception &err) {
Expand All @@ -176,7 +176,7 @@ void CanaryServer::loadMaps() const {

void CanaryServer::setupHousesRent() {
RentPeriod_t rentPeriod;
std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__));
std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD));

if (strRentPeriod == "yearly") {
rentPeriod = RENTPERIOD_YEARLY;
Expand Down Expand Up @@ -289,7 +289,7 @@ void CanaryServer::loadConfigLua() {
modulesLoadHelper(g_configManager().load(), g_configManager().getConfigFileLua());

#ifdef _WIN32
const std::string &defaultPriority = g_configManager().getString(DEFAULT_PRIORITY, __FUNCTION__);
const std::string &defaultPriority = g_configManager().getString(DEFAULT_PRIORITY);
if (strcasecmp(defaultPriority.c_str(), "high") == 0) {
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
} else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) {
Expand All @@ -315,16 +315,16 @@ void CanaryServer::initializeDatabase() {

DatabaseManager::updateDatabase();

if (g_configManager().getBoolean(OPTIMIZE_DATABASE, __FUNCTION__)
if (g_configManager().getBoolean(OPTIMIZE_DATABASE)
&& !DatabaseManager::optimizeTables()) {
logger.debug("No tables were optimized");
}
}

void CanaryServer::loadModules() {
// If "USE_ANY_DATAPACK_FOLDER" is set to true then you can choose any datapack folder for your server
const auto useAnyDatapack = g_configManager().getBoolean(USE_ANY_DATAPACK_FOLDER, __FUNCTION__);
auto datapackName = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__);
const auto useAnyDatapack = g_configManager().getBoolean(USE_ANY_DATAPACK_FOLDER);
auto datapackName = g_configManager().getString(DATA_DIRECTORY);
if (!useAnyDatapack && datapackName != "data-canary" && datapackName != "data-otservbr-global") {
throw FailedToInitializeCanary(fmt::format(
"The datapack folder name '{}' is wrong, please select valid "
Expand All @@ -339,7 +339,7 @@ void CanaryServer::loadModules() {
g_luaEnvironment().initState();
}

auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__);
auto coreFolder = g_configManager().getString(CORE_DIRECTORY);
// Load appearances.dat first
modulesLoadHelper((g_game().loadAppearanceProtobuf(coreFolder + "/items/appearances.dat") == ERROR_NONE), "appearances.dat");

Expand All @@ -353,7 +353,7 @@ void CanaryServer::loadModules() {

modulesLoadHelper(Item::items.loadFromXml(), "items.xml");

const auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__);
const auto datapackFolder = g_configManager().getString(DATA_DIRECTORY);
logger.debug("Loading core scripts on folder: {}/", coreFolder);
// Load first core Lua libs
modulesLoadHelper((g_luaEnvironment().loadFile(coreFolder + "/core.lua", "core.lua") == 0), "core.lua");
Expand Down
18 changes: 9 additions & 9 deletions src/config/configmanager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ bool ConfigManager::load() {

bool ConfigManager::reload() {
const bool result = load();
if (transformToSHA1(getString(SERVER_MOTD, __FUNCTION__)) != g_game().getMotdHash()) {
if (transformToSHA1(getString(SERVER_MOTD)) != g_game().getMotdHash()) {
g_game().incrementMotdNum();
}
return result;
Expand Down Expand Up @@ -432,35 +432,35 @@ float ConfigManager::loadFloatConfig(lua_State* L, const ConfigKey_t &key, const
return value;
}

const std::string &ConfigManager::getString(const ConfigKey_t &key, std::string_view context) const {
const std::string &ConfigManager::getString(const ConfigKey_t &key, const std::source_location &location /*= std::source_location::current()*/) const {
static const std::string dummyStr;
if (configs.contains(key) && std::holds_alternative<std::string>(configs.at(key))) {
return std::get<std::string>(configs.at(key));
}
g_logger().warn("[ConfigManager::getString] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context);
g_logger().warn("[{}] accessing invalid or wrong type index: {}[{}]. Called line: {}:{}, in {}", __FUNCTION__, magic_enum::enum_name(key), fmt::underlying(key), location.line(), location.column(), location.function_name());
return dummyStr;
}

int32_t ConfigManager::getNumber(const ConfigKey_t &key, std::string_view context) const {
int32_t ConfigManager::getNumber(const ConfigKey_t &key, const std::source_location &location /*= std::source_location::current()*/) const {
if (configs.contains(key) && std::holds_alternative<int32_t>(configs.at(key))) {
return std::get<int32_t>(configs.at(key));
}
g_logger().warn("[ConfigManager::getNumber] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context);
g_logger().warn("[{}] accessing invalid or wrong type index: {}[{}]. Called line: {}:{}, in {}", __FUNCTION__, magic_enum::enum_name(key), fmt::underlying(key), location.line(), location.column(), location.function_name());
return 0;
}

bool ConfigManager::getBoolean(const ConfigKey_t &key, std::string_view context) const {
bool ConfigManager::getBoolean(const ConfigKey_t &key, const std::source_location &location /*= std::source_location::current()*/) const {
if (configs.contains(key) && std::holds_alternative<bool>(configs.at(key))) {
return std::get<bool>(configs.at(key));
}
g_logger().warn("[ConfigManager::getBoolean] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context);
g_logger().warn("[{}] accessing invalid or wrong type index: {}[{}]. Called line: {}:{}, in {}", __FUNCTION__, magic_enum::enum_name(key), fmt::underlying(key), location.line(), location.column(), location.function_name());
return false;
}

float ConfigManager::getFloat(const ConfigKey_t &key, std::string_view context) const {
float ConfigManager::getFloat(const ConfigKey_t &key, const std::source_location &location /*= std::source_location::current()*/) const {
if (configs.contains(key) && std::holds_alternative<float>(configs.at(key))) {
return std::get<float>(configs.at(key));
}
g_logger().warn("[ConfigManager::getFloat] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context);
g_logger().warn("[{}] accessing invalid or wrong type index: {}[{}]. Called line: {}:{}, in {}", __FUNCTION__, magic_enum::enum_name(key), fmt::underlying(key), location.line(), location.column(), location.function_name());
return 0.0f;
}
8 changes: 4 additions & 4 deletions src/config/configmanager.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,10 @@ class ConfigManager {
return configFileLua;
};

[[nodiscard]] const std::string &getString(const ConfigKey_t &key, std::string_view context) const;
[[nodiscard]] int32_t getNumber(const ConfigKey_t &key, std::string_view context) const;
[[nodiscard]] bool getBoolean(const ConfigKey_t &key, std::string_view context) const;
[[nodiscard]] float getFloat(const ConfigKey_t &key, std::string_view context) const;
[[nodiscard]] const std::string &getString(const ConfigKey_t &key, const std::source_location &location = std::source_location::current()) const;
[[nodiscard]] int32_t getNumber(const ConfigKey_t &key, const std::source_location &location = std::source_location::current()) const;
[[nodiscard]] bool getBoolean(const ConfigKey_t &key, const std::source_location &location = std::source_location::current()) const;
[[nodiscard]] float getFloat(const ConfigKey_t &key, const std::source_location &location = std::source_location::current()) const;

private:
phmap::flat_hash_map<ConfigKey_t, ConfigValue> configs;
Expand Down
4 changes: 2 additions & 2 deletions src/creatures/appearance/mounts/mounts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ bool Mounts::reload() {

bool Mounts::loadFromXml() {
pugi::xml_document doc;
auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/mounts.xml";
auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/mounts.xml";
pugi::xml_parse_result result = doc.load_file(folder.c_str());
if (!result) {
printXMLError(__FUNCTION__, folder, result);
Expand All @@ -28,7 +28,7 @@ bool Mounts::loadFromXml() {

for (auto mountNode : doc.child("mounts").children()) {
auto lookType = pugi::cast<uint16_t>(mountNode.attribute("clientid").value());
if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) {
if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) {
g_logger().warn("{} - An unregistered creature mount with id '{}' was blocked to prevent client crash.", __FUNCTION__, lookType);
continue;
}
Expand Down
4 changes: 2 additions & 2 deletions src/creatures/appearance/outfit/outfit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ bool Outfits::reload() {

bool Outfits::loadFromXml() {
pugi::xml_document doc;
auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/outfits.xml";
auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/outfits.xml";
pugi::xml_parse_result result = doc.load_file(folder.c_str());
if (!result) {
printXMLError(__FUNCTION__, folder, result);
Expand Down Expand Up @@ -56,7 +56,7 @@ bool Outfits::loadFromXml() {
}

if (auto lookType = pugi::cast<uint16_t>(lookTypeAttribute.value());
g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0
g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0
&& !g_game().isLookTypeRegistered(lookType)) {
g_logger().warn("[Outfits::loadFromXml] An unregistered creature looktype type with id '{}' was ignored to prevent client crash.", lookType);
continue;
Expand Down
12 changes: 6 additions & 6 deletions src/creatures/combat/combat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ bool Combat::isInPvpZone(std::shared_ptr<Creature> attacker, std::shared_ptr<Cre
}

bool Combat::isProtected(std::shared_ptr<Player> attacker, std::shared_ptr<Player> target) {
uint32_t protectionLevel = g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__);
uint32_t protectionLevel = g_configManager().getNumber(PROTECTION_LEVEL);
if (target->getLevel() < protectionLevel || attacker->getLevel() < protectionLevel) {
return true;
}
Expand Down Expand Up @@ -1006,17 +1006,17 @@ void Combat::setupChain(const std::shared_ptr<Weapon> &weapon) {
setParam(COMBAT_PARAM_BLOCKARMOR, true);
};

setChainCallback(g_configManager().getNumber(COMBAT_CHAIN_TARGETS, __FUNCTION__), 1, true);
setChainCallback(g_configManager().getNumber(COMBAT_CHAIN_TARGETS), 1, true);

switch (weaponType) {
case WEAPON_SWORD:
setCommonValues(g_configManager().getFloat(COMBAT_CHAIN_SKILL_FORMULA_SWORD, __FUNCTION__), MELEE_ATK_SWORD, CONST_ME_SLASH);
setCommonValues(g_configManager().getFloat(COMBAT_CHAIN_SKILL_FORMULA_SWORD), MELEE_ATK_SWORD, CONST_ME_SLASH);
break;
case WEAPON_CLUB:
setCommonValues(g_configManager().getFloat(COMBAT_CHAIN_SKILL_FORMULA_CLUB, __FUNCTION__), MELEE_ATK_CLUB, CONST_ME_BLACK_BLOOD);
setCommonValues(g_configManager().getFloat(COMBAT_CHAIN_SKILL_FORMULA_CLUB), MELEE_ATK_CLUB, CONST_ME_BLACK_BLOOD);
break;
case WEAPON_AXE:
setCommonValues(g_configManager().getFloat(COMBAT_CHAIN_SKILL_FORMULA_AXE, __FUNCTION__), MELEE_ATK_AXE, CONST_ANI_WHIRLWINDAXE);
setCommonValues(g_configManager().getFloat(COMBAT_CHAIN_SKILL_FORMULA_AXE), MELEE_ATK_AXE, CONST_ANI_WHIRLWINDAXE);
break;
}

Expand Down Expand Up @@ -1059,7 +1059,7 @@ bool Combat::doCombatChain(std::shared_ptr<Creature> caster, std::shared_ptr<Cre
int i = 0;
for (const auto &[from, toVector] : targets) {
auto combat = this;
auto delay = i * std::max<int32_t>(50, g_configManager().getNumber(COMBAT_CHAIN_DELAY, __FUNCTION__));
auto delay = i * std::max<int32_t>(50, g_configManager().getNumber(COMBAT_CHAIN_DELAY));
++i;
for (auto to : toVector) {
auto nextTarget = g_game().getCreatureByID(to);
Expand Down
8 changes: 4 additions & 4 deletions src/creatures/combat/condition.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1302,7 +1302,7 @@ uint32_t ConditionRegeneration::getHealthTicks(std::shared_ptr<Creature> creatur
std::shared_ptr<Player> player = creature->getPlayer();

if (player != nullptr && isBuff) {
return healthTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__);
return healthTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN);
}

return healthTicks;
Expand All @@ -1312,7 +1312,7 @@ uint32_t ConditionRegeneration::getManaTicks(std::shared_ptr<Creature> creature)
std::shared_ptr<Player> player = creature->getPlayer();

if (player != nullptr && isBuff) {
return manaTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__);
return manaTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN);
}

return manaTicks;
Expand Down Expand Up @@ -2326,7 +2326,7 @@ void ConditionOutfit::serialize(PropWriteStream &propWriteStream) {
}

bool ConditionOutfit::startCondition(std::shared_ptr<Creature> creature) {
if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) {
if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) {
g_logger().warn("[ConditionOutfit::startCondition] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType);
return false;
}
Expand Down Expand Up @@ -2358,7 +2358,7 @@ void ConditionOutfit::endCondition(std::shared_ptr<Creature> creature) {
}

void ConditionOutfit::addCondition(std::shared_ptr<Creature> creature, const std::shared_ptr<Condition> addCondition) {
if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) {
if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) {
g_logger().warn("[ConditionOutfit::addCondition] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType);
return;
}
Expand Down
8 changes: 4 additions & 4 deletions src/creatures/combat/spells.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ Spells::Spells() = default;
Spells::~Spells() = default;

TalkActionResult_t Spells::playerSaySpell(std::shared_ptr<Player> player, std::string &words) {
auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__);
auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT);
auto tile = player->getTile();
if (maxOnline > 1 && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && tile && !tile->hasFlag(TILESTATE_PROTECTIONZONE)) {
auto maxOutsizePZ = g_configManager().getNumber(MAX_PLAYERS_OUTSIDE_PZ_PER_ACCOUNT, __FUNCTION__);
auto maxOutsizePZ = g_configManager().getNumber(MAX_PLAYERS_OUTSIDE_PZ_PER_ACCOUNT);
auto accountPlayers = g_game().getPlayersByAccount(player->getAccount());
int countOutsizePZ = 0;
for (const auto &accountPlayer : accountPlayers) {
Expand Down Expand Up @@ -669,7 +669,7 @@ void Spell::applyCooldownConditions(std::shared_ptr<Player> player) const {
WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName());
bool isUpgraded = getWheelOfDestinyUpgraded() && static_cast<uint8_t>(spellGrade) > 0;
// Safety check to prevent division by zero
auto rateCooldown = g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__);
auto rateCooldown = g_configManager().getFloat(RATE_SPELL_COOLDOWN);
if (std::abs(rateCooldown) < std::numeric_limits<float>::epsilon()) {
rateCooldown = 0.1; // Safe minimum value
}
Expand Down Expand Up @@ -1048,7 +1048,7 @@ bool RuneSpell::executeUse(std::shared_ptr<Player> player, std::shared_ptr<Item>
}

postCastSpell(player);
if (hasCharges && item && g_configManager().getBoolean(REMOVE_RUNE_CHARGES, __FUNCTION__)) {
if (hasCharges && item && g_configManager().getBoolean(REMOVE_RUNE_CHARGES)) {
int32_t newCount = std::max<int32_t>(0, item->getItemCount() - 1);
g_game().transformItem(item, item->getID(), newCount);
player->updateSupplyTracker(item);
Expand Down
Loading

0 comments on commit 90e205d

Please sign in to comment.