]> git.tdb.fi Git - builder.git/blob - source/config.cpp
61f7322e742ead72279f2d89a33f1012a4c8f497
[builder.git] / source / config.cpp
1 #include <fstream>
2 #include <msp/error.h>
3 #include <msp/path/utils.h>
4 #include <msp/time/utils.h>
5 #include "config.h"
6
7 using namespace std;
8 using namespace Msp;
9
10 void Config::add_option(const string &n, const string &v, const string &d)
11 {
12         options.insert(OptionMap::value_type(n, Option(n, v, d)));
13 }
14
15 const Config::Option &Config::get_option(const string &name) const
16 {
17         OptionMap::const_iterator i=options.find(name);
18         if(i==options.end())
19                 throw Exception("Tried to access nonexistent option "+name);
20
21         return i->second;
22 }
23
24 bool Config::is_option(const string &name) const
25 {
26         return options.count(name);
27 }
28
29 bool Config::process(const RawOptionMap &opts)
30 {
31         bool changed=false;
32         for(RawOptionMap::const_iterator i=opts.begin(); i!=opts.end(); ++i)
33         {
34                 OptionMap::iterator j=options.find(i->first);
35                 if(j!=options.end())
36                 {
37                         if(i->second!=j->second.value)
38                                 changed=true;
39                         j->second.value=i->second;
40                 }
41         }
42
43         if(changed)
44                 mtime=Time::now();
45
46         return changed;
47 }
48
49 void Config::load(const Path::Path &fn)
50 {
51         ifstream in(fn.str().c_str());
52         if(!in) return;
53
54         struct stat st;
55         Path::stat(fn, st);
56         mtime=Time::TimeStamp::from_unixtime(st.st_mtime);
57
58         Parser::Parser parser(in, fn.str());
59         Loader loader(*this);
60         loader.load(parser);
61 }
62
63 void Config::save(const Path::Path &fn) const
64 {
65         ofstream out(fn.str().c_str());
66         if(!out) return;
67         
68         for(OptionMap::const_iterator i=options.begin(); i!=options.end(); ++i)
69                 out<<"option \""<<i->second.name<<"\" \""<<i->second.value<<"\";\n";
70 }
71
72 Config::Option::Option(const string &n, const string &v, const string &d):
73         name(n),
74         defv(v),
75         descr(d),
76         value(v)
77 { }
78
79 Config::Loader::Loader(Config &c):
80         conf(c)
81 {
82         add("option", &Loader::option);
83 }
84
85 void Config::Loader::option(const string &n, const string &v)
86 {
87         OptionMap::iterator i=conf.options.find(n);
88         if(i!=conf.options.end())
89                 i->second.value=v;
90 }