PDA

Просмотр полной версии : [10081][idea] Drop usage of DOTCONFDocument.


Astellar
18.06.2010, 22:37
В общем смотрел я на это дело, смотрел. И подумал. А зачем нужен этот велосипед вообще?

Объясняю подробнее. Формат конфигов у нас очень простой. По сути это обычный INI файл вида ключ = значение. Кроме того, мы активно используем ACE Framework. ACE предоставляет класс ACE_Ini_ImpExp (http://www.dre.vanderbilt.edu/Doxygen/5.6/html/ace/classACE__Ini__ImpExp.html), который может делать абсолютно всё, что делается сейчас.

Если кому-то интересно, выложу патч, убирающий эту зависимость от стороннего кода. Благо работает прекрасно.

Vladimir
19.06.2010, 02:15
Вообщемто согласен - используем чисто исторически с друвних времен.

Если конечно будет читать текущие конфиги с минимум особеностей то здравая идея.

Кстати насколько я помню ACE конфиги понимают кучу источников включая базы и registry. Соотвевеено использование стандартного API может позволить интересующимся для себя изменить форму хранения если сильно хочется.

Konctantin
19.06.2010, 07:14
Если кому-то интересно, выложу патч
Интересно, выкладывайте...

Astellar
19.06.2010, 11:25
Насчет хранения в базе не уверен, не видел там такого. А вот в реестре - да, хранит прекрасно. Но только под виндой, само собой.

Особенностей в общем-то две всего:

1. Нет возможности сконфигурировать чувствительность к регистру символов. Что мне в общем-то никогда не мешало.
2. Конфиг ожидается в формате[Section1]
key = value
...

...

[SectionN]
key = value
...в связи с чем придется добавить в верхушку каждого конфига по одной секции. А в будущем, возможно, сделать нормальное разбиение на секции.

Astellar
19.06.2010, 11:34
Сам патч выглядит следующим образом.
diff --git a/src/mangosd/mangosd.conf.dist.in b/src/mangosd/mangosd.conf.dist.in
index f5ba807..4da4e27 100644
--- a/src/mangosd/mangosd.conf.dist.in
+++ b/src/mangosd/mangosd.conf.dist.in
@@ -1,6 +1,8 @@
#####################################
# MaNGOS Configuration file #
#####################################
+
+[MangosdConf]
ConfVersion=2010051901

################################################## ################################################## ###############
diff --git a/src/realmd/realmd.conf.dist.in b/src/realmd/realmd.conf.dist.in
index 20e1792..75c7a27 100644
--- a/src/realmd/realmd.conf.dist.in
+++ b/src/realmd/realmd.conf.dist.in
@@ -1,6 +1,8 @@
############################################
# MaNGOS realmd configuration file #
############################################
+
+[RealmdConf]
ConfVersion=2007062001

################################################## ################################################## ###############
diff --git a/src/shared/Config/Config.cpp b/src/shared/Config/Config.cpp
index b4eeacd..c1bee65 100644
--- a/src/shared/Config/Config.cpp
+++ b/src/shared/Config/Config.cpp
@@ -22,7 +22,7 @@
INSTANTIATE_SINGLETON_1(Config);

Config::Config()
-: mIgnoreCase(true), mConf(NULL)
+: mConf(NULL)
{
}

@@ -31,9 +31,8 @@ Config::~Config()
delete mConf;
}

-bool Config::SetSource(const char *file, bool ignorecase)
+bool Config::SetSource(const char *file)
{
- mIgnoreCase = ignorecase;
mFilename = file;

return Reload();
@@ -42,43 +41,33 @@ bool Config::SetSource(const char *file, bool ignorecase)
bool Config::Reload()
{
delete mConf;
+ mConf = new ACE_Configuration_Heap;

- mConf = new DOTCONFDocument(mIgnoreCase ?
- DOTCONFDocument::CASEINSENSETIVE :
- DOTCONFDocument::CASESENSITIVE);
-
- if (mConf->setContent(mFilename.c_str()) == -1)
+ if (mConf->open() == 0)
{
- delete mConf;
- mConf = NULL;
- return false;
+ ACE_Ini_ImpExp config_importer(*mConf);
+ if (config_importer.import_config(mFilename.c_str()) == 0)
+ return true;
}

- return true;
+ delete mConf;
+ mConf = NULL;
+ return false;
}

std::string Config::GetStringDefault(const char* name, const char* def)
{
- if (!mConf)
- return std::string(def);
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
- if (!node || !node->getValue())
- return std::string(def);
-
- return std::string(node->getValue());
+ ACE_TString val;
+ return GetValue(name, val) ? val.c_str() : def;
}

bool Config::GetBoolDefault(const char* name, bool def)
{
- if (!mConf)
- return def;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
- if (!node || !node->getValue())
+ ACE_TString val;
+ if (!GetValue(name, val))
return def;

- const char* str = node->getValue();
+ const char* str = val.c_str();
if (strcmp(str, "true") == 0 || strcmp(str, "TRUE") == 0 ||
strcmp(str, "yes") == 0 || strcmp(str, "YES") == 0 ||
strcmp(str, "1") == 0)
@@ -90,25 +79,34 @@ bool Config::GetBoolDefault(const char* name, bool def)

int32 Config::GetIntDefault(const char* name, int32 def)
{
- if (!mConf)
- return def;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
- if (!node || !node->getValue())
- return def;
-
- return atoi(node->getValue());
+ ACE_TString val;
+ return GetValue(name, val) ? atoi(val.c_str()) : def;
}


float Config::GetFloatDefault(const char* name, float def)
{
+ ACE_TString val;
+ return GetValue(name, val) ? (float)atof(val.c_str()) : def;
+}
+
+bool Config::GetValue(const char *name, ACE_TString &result)
+{
if (!mConf)
- return def;
+ return false;

- DOTCONFDocumentNode const *node = mConf->findNode(name);
- if (!node || !node->getValue())
- return def;
+ ACE_TString section_name;
+ ACE_Configuration_Section_Key section_key;
+ ACE_Configuration_Section_Key root_key = mConf->root_section();
+
+ int i = 0;
+ while (mConf->enumerate_sections(root_key, i, section_name) == 0)
+ {
+ mConf->open_section(root_key, section_name.c_str(), 0, section_key);
+ if (mConf->get_string_value(section_key, name, result) == 0)
+ return true;
+ ++i;
+ }

- return (float)atof(node->getValue());
+ return false;
}
diff --git a/src/shared/Config/Config.h b/src/shared/Config/Config.h
index 2960184..af72670 100644
--- a/src/shared/Config/Config.h
+++ b/src/shared/Config/Config.h
@@ -22,7 +22,7 @@
#include <Policies/Singleton.h>
#include "Platform/Define.h"

-class DOTCONFDocument;
+class ACE_Configuration_Heap;

class MANGOS_DLL_SPEC Config
{
@@ -31,7 +31,7 @@ class MANGOS_DLL_SPEC Config
Config();
~Config();

- bool SetSource(const char *file, bool ignorecase = true);
+ bool SetSource(const char *file);
bool Reload();

std::string GetStringDefault(const char* name, const char* def);
@@ -43,9 +43,10 @@ class MANGOS_DLL_SPEC Config

private:

+ bool GetValue(const char *name, ACE_TString &result);
+
std::string mFilename;
- bool mIgnoreCase;
- DOTCONFDocument *mConf;
+ ACE_Configuration_Heap *mConf;
};

#define sConfig MaNGOS::Singleton<Config>::Instance()
diff --git a/src/shared/Config/ConfigEnv.h b/src/shared/Config/ConfigEnv.h
index e9801b6..9f2c7d3 100644
--- a/src/shared/Config/ConfigEnv.h
+++ b/src/shared/Config/ConfigEnv.h
@@ -21,7 +21,7 @@
#define CONFIGENVIRONMENT_H

#include "Common.h"
-#include "dotconfpp/dotconfpp.h"
+#include "ace/Configuration_Import_Export.h"
#include "Config.h"

#endif


Удаление файлов DOTCONFDocument в патч не включено, ибо незачем.

Vladimir
20.06.2010, 00:23
Я думаю лучше перенесу GetValue как

static bool GetValueHelper(ACE_Configuration_Heap *mConf, const char *name, ACE_TString &result)


в Config.cpp так как ради одного типа в private-методе включать в широко используемый заголовочный файл специализированный ACE-header не думаю что хорошо....

Astellar
20.06.2010, 00:33
Можно и так. Только там ведь forward declaration идёт. Заголовок подключается именно что в Config.cpp. Config.h в плане заголовочных файлов остался нетронутым.

Всё, понял про какой именно заголовок речь идёт. Который в ConfigEnv.h. Тогда да, надо менять.

Vladimir
20.06.2010, 00:49
diff --git a/src/shared/Config/ConfigEnv.h b/src/shared/Config/ConfigEnv.h
index e9801b6..9f2c7d3 100644
--- a/src/shared/Config/ConfigEnv.h
+++ b/src/shared/Config/ConfigEnv.h
@@ -21,7 +21,7 @@
#define CONFIGENVIRONMENT_H

#include "Common.h"
-#include "dotconfpp/dotconfpp.h"
+#include "ace/Configuration_Import_Export.h"

Vladimir
20.06.2010, 00:55
С описанными изменениями в [10081]. Спасибо :)