aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/config/ini.cpp
blob: 6c1897dd279901fbc50bdc60acb08922c2e19053 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "ini.h"

#include <util/string/strip.h>
#include <util/stream/input.h>

using namespace NConfig;

namespace {
    inline TStringBuf StripComment(TStringBuf line) {
        return line.Before('#').Before(';');
    }
}

TConfig NConfig::ParseIni(IInputStream& in) {
    TConfig ret = ConstructValue(TDict());

    {
        TConfig* cur = &ret;
        TString line;

        while (in.ReadLine(line)) {
            TStringBuf tmp = StripComment(line);
            TStringBuf stmp = StripString(tmp);

            if (stmp.empty()) {
                continue;
            }

            if (stmp[0] == '[') {
                //start section
                if (*(stmp.end() - 1) != ']') {
                    ythrow TConfigParseError() << "malformed section " << stmp;
                }

                stmp = TStringBuf(stmp.data() + 1, stmp.end() - 1);
                cur = &ret;

                while (!!stmp) {
                    TStringBuf section;

                    stmp.Split('.', section, stmp);

                    cur = &cur->GetNonConstant<TDict>()[section];
                    if (!cur->IsA<TDict>()) {
                        *cur = ConstructValue(TDict());
                    }
                }
            } else {
                //value
                TStringBuf key, value;

                tmp.Split('=', key, value);

                auto& dict = cur->GetNonConstant<TDict>();
                auto strippedValue = TString(StripString(value));
                dict[StripString(key)] = ConstructValue(strippedValue);
            }
        }
    }

    return ret;
}