simple_config.hpp
Go to the documentation of this file.00001 #ifndef s11n_SIMPLECONFIG_HPP_INCLUDED
00002 #define s11n_SIMPLECONFIG_HPP_INCLUDED 1
00003
00004
00005
00006 #include <s11n.net/s11n/io/strtool.hpp>
00007 #include <s11n.net/s11n/s11n_debuggering_macros.hpp>
00008 #include <s11n.net/s11n/exception.hpp>
00009 #include <stdlib.h>
00010 #include <stdexcept>
00011 #include <sstream>
00012 namespace s11nlite {
00013
00014
00015
00016
00017 class simple_config
00018 {
00019 public:
00020 typedef ::s11nlite::node_type node_type;
00021 typedef ::s11nlite::node_traits node_traits;
00022 private:
00023 std::string m_base;
00024 std::string m_abs;
00025 node_type * m_node;
00026
00027 void load_node()
00028 {
00029 try
00030 {
00031 this->m_node = ::s11nlite::load_node( this->m_abs );
00032 }
00033 catch(...)
00034 {
00035 this->m_node = 0;
00036 }
00037 if( ! this->m_node )
00038 {
00039 this->m_node = node_traits::create( this->m_base );
00040 if( 0 ) CERR << "s11nlite::simple_config error: could not load node from file "
00041 << "'" << this->m_abs << "'.\n"
00042 << "Creating new node named '"<< this->m_base << "'."
00043 << "\n";
00044 }
00045 }
00046
00047
00048 void resolve_path() throw(std::runtime_error)
00049 {
00050 if( this->m_base.empty() ||
00051 (std::string::npos != this->m_base.find( '/' )) )
00052 {
00053 throw std::runtime_error( "s11n::util::simple_config: invalid base filename: "+this->m_base );
00054 }
00055 const char * home = ::getenv("HOME");
00056 if( ! home )
00057 {
00058 throw std::runtime_error( "s11n::util::simple_config: $HOME is not set! Cannot create config file!" );
00059 }
00060 ::s11n::io::strtool::entity_map env;
00061 env["HOME"] = home;
00062 std::string tmp = "${HOME}/."+m_base+".s11n";
00063 this->m_abs = ::s11n::io::strtool::expand_dollar_refs( tmp, env );
00064
00065 }
00066 public:
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076 simple_config( const std::string & basename ) throw(std::runtime_error)
00077 : m_base(basename),m_abs(),m_node(0)
00078 {
00079 this->resolve_path();
00080 this->load_node();
00081 }
00082
00083
00084
00085
00086 ~simple_config() throw()
00087 {
00088 if( ! this->m_abs.empty() )
00089 {
00090 try
00091 {
00092 s11nlite::save( *this->m_node, this->m_abs );
00093 }
00094 catch(...)
00095 {
00096 CERR << "EXCEPTION while saving simple_config to " << this->m_abs;
00097 }
00098 }
00099 delete this->m_node;
00100 }
00101
00102
00103
00104
00105
00106 std::string abs_path() const
00107 {
00108 return this->m_abs;
00109 }
00110
00111
00112
00113
00114 std::string basename() const
00115 {
00116 return this->m_base;
00117 }
00118
00119
00120
00121
00122
00123 node_type & node()
00124 {
00125 return *this->m_node;
00126 }
00127 };
00128
00129 }
00130
00131
00132 #endif // s11n_SIMPLECONFIG_HPP_INCLUDED