aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yconf/patcher/config_patcher.cpp
blob: 93b8649705f1485d1060f03f9a06337ebcac1ba8 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#include "config_patcher.h"

#include <library/cpp/yconf/patcher/unstrict_config.h>

#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_prettifier.h>

#include <util/generic/maybe.h>
#include <util/generic/ptr.h>
#include <util/generic/xrange.h>
#include <util/stream/file.h>
#include <util/string/subst.h>

#include <array>

namespace {
    class TWrapper {
    public:
        TWrapper(const TString& base, const NJson::TJsonValue& patch, const TString& prefix);

        void Patch();
        TString GetPatchedConfig() {
            Patch();
            return PatchedConfixText;
        }

    private:
        void Preprocess();
        void Postprocess();

    private:
        static const TString IncludeDirective;
        static const TString IncludeGuard;

    private:
        TString BaseConfigText;
        THolder<TUnstrictConfig> Config;
        NJson::TJsonValue JsonPatch;
        TString Prefix;
        TString PatchedConfixText;
        bool Patched;
        bool NeedsPostprocessing;
    };

    const TString TWrapper::IncludeDirective = "#include";
    const TString TWrapper::IncludeGuard = "__INCLUDE__ :";

    TWrapper::TWrapper(const TString& base, const NJson::TJsonValue& patch, const TString& prefix)
        : BaseConfigText(base)
        , JsonPatch(patch)
        , Prefix(prefix)
        , Patched(false)
        , NeedsPostprocessing(false)
    {
    }

    void TWrapper::Patch() {
        if (Patched)
            return;
        Preprocess();

        const NJson::TJsonValue::TMapType* values;
        if (!JsonPatch.GetMapPointer(&values))
            ythrow yexception() << "unable to get map pointer in the json patch.";
        for (const auto& value : *values) {
            Config->PatchEntry(value.first, value.second.GetStringRobust(), Prefix);
        }

        Postprocess();
        Patched = true;
    }

    void TWrapper::Preprocess() {
        TString parsed;
        size_t pos = BaseConfigText.find(IncludeDirective);
        if (pos != TString::npos) {
            NeedsPostprocessing = true;
            parsed = BaseConfigText.replace(pos, IncludeDirective.size(), IncludeGuard);
        } else {
            parsed = BaseConfigText;
        }
        Config.Reset(new TUnstrictConfig);
        if (!Config->ParseMemory(parsed.data())) {
            TString errors;
            Config->PrintErrors(errors);
            ythrow yexception() << "Can't parse config:" << errors;
        }
    }

    void TWrapper::Postprocess() {
        PatchedConfixText = Config->ToString();
        if (NeedsPostprocessing) {
            SubstGlobal(PatchedConfixText, IncludeGuard, IncludeDirective);
        }
    }

    void MakeDiff(
            NJson::TJsonValue& container,
            const TYandexConfig::Section* source,
            const TYandexConfig::Section* target,
            const TString& parentPrefix = TString()) {
        Y_VERIFY(target);
        const TString& prefix = parentPrefix ? (parentPrefix + ".") : parentPrefix;

        for (const auto& [name, value]: target->GetDirectives()) {
            const auto p = source ? source->GetDirectives().FindPtr(name) : nullptr;
            if (!p || TString(*p) != value) {
                container[prefix + name] = value;
            }
        }

        if (source) {
            for (const auto& [name, value] : source->GetDirectives()) {
                if (!target->GetDirectives().contains(name)) {
                    container[prefix + name] = "__remove__";
                }
            }
        }

        TMap<TCiString, std::array<TVector<const TYandexConfig::Section *>, 2>> alignedSections;

        auto fillSections = [&](const TYandexConfig::TSectionsMap& sections, size_t targetIndex) {
            for (const auto& [sectionName, section] : sections) {
                alignedSections[sectionName][targetIndex].push_back(section);
            }
        };

        if (source) {
            fillSections(source->GetAllChildren(), 0);
        }
        fillSections(target->GetAllChildren(), 1);

        for (const auto& [sectionName, pair]: alignedSections) {
            // Cannot use structured binding on std::array here because of a bug in MSVC.
            const auto& sourceSections = pair[0];
            const auto& targetSections = pair[1];
            const bool needsIndex = targetSections.size() > 1;

            if (targetSections.empty()) {
                Y_VERIFY(source);
                container[prefix + sectionName] = "__remove_all__";
            } else {
                for (const size_t i: xrange(targetSections.size())) {
                    MakeDiff(
                            container,
                            i < sourceSections.size() ? sourceSections[i] : nullptr,
                            targetSections[i],
                            !needsIndex ? prefix + sectionName : prefix + sectionName + '[' + ToString(i) + ']');
                }
                if (sourceSections.size() > targetSections.size()) {
                    container[
                        prefix +
                            sectionName +
                            '[' +
                            ToString(targetSections.size()) +
                            ':' +
                            ToString(sourceSections.size() - 1) +
                            ']'] = "__remove__";
                }
            }
        }

        if (target->GetAllChildren().empty() && target->GetDirectives().empty()) {
            container[prefix] = "__add_section__";
        }
    }
}

namespace NConfigPatcher {
    TString Patch(const TString& config, const TString& patch, const TOptions& options) {
        if (!patch) {
            return config;
        }

        NJson::TJsonValue parsedPatch;
        TStringInput ss(patch);
        if (!NJson::ReadJsonTree(&ss, true, &parsedPatch, true)) {
            ythrow yexception() << "Cannot parse patch as json";
        }
        return Patch(config, parsedPatch, options);
    }

    TString Patch(const TString& config, const NJson::TJsonValue& parsedPatch, const TOptions& options) {
        TWrapper patcher(config, parsedPatch, options.Prefix);
        return patcher.GetPatchedConfig();
    }

    TString Diff(const TString& sourceText, const TString& targetText) {
        TUnstrictConfig source;
        if (!source.ParseMemory(sourceText.data())) {
            throw yexception() << "Cannot parse source config";
        }

        TUnstrictConfig target;
        if (!target.ParseMemory(targetText.data())) {
            throw yexception() << "Cannot parse target config";
        }

        NJson::TJsonValue diff(NJson::JSON_MAP);
        MakeDiff(diff, source.GetRootSection(), target.GetRootSection());
        return NJson::PrettifyJson(diff.GetStringRobust());
    }
}