aboutsummaryrefslogtreecommitdiff
path: root/include/jsoncons_ext/jsonpatch/jsonpatch.hpp
blob: ab4ace7648b12c8065780f4aaaedf14e2e6f9127 (plain)
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Copyright 2017 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// See https://github.com/danielaparker/jsoncons for latest version

#ifndef JSONCONS_JSONPATCH_JSONPATCH_HPP
#define JSONCONS_JSONPATCH_JSONPATCH_HPP

#include <string>
#include <vector> 
#include <memory>
#include <algorithm> // std::min
#include <utility> // std::move
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
#include <jsoncons_ext/jsonpatch/jsonpatch_error.hpp>

namespace jsoncons { namespace jsonpatch {

namespace detail {

    template <class CharT>
    struct jsonpatch_names
    {
        static std::basic_string<CharT> test_name()
        {
            static std::basic_string<CharT> name{'t','e','s','t'};
            return name;
        }
        static std::basic_string<CharT> add_name()
        {
            static std::basic_string<CharT> name{'a','d','d'};
            return name;
        }
        static std::basic_string<CharT> remove_name()
        {
            static std::basic_string<CharT> name{'r','e','m','o','v','e'};
            return name;
        }
        static std::basic_string<CharT> replace_name()
        {
            static std::basic_string<CharT> name{'r','e','p','l','a','c','e'};
            return name;
        }
        static std::basic_string<CharT> move_name()
        {
            static std::basic_string<CharT> name{'m','o','v','e'};
            return name;
        }
        static std::basic_string<CharT> copy_name()
        {
            static std::basic_string<CharT> name{'c','o','p','y'};
            return name;
        }
        static std::basic_string<CharT> op_name()
        {
            static std::basic_string<CharT> name{'o','p'};
            return name;
        }
        static std::basic_string<CharT> path_name()
        {
            static std::basic_string<CharT> name{'p','a','t','h'};
            return name;
        }
        static std::basic_string<CharT> from_name()
        {
            static std::basic_string<CharT> name{'f','r','o','m'};
            return name;
        }
        static std::basic_string<CharT> value_name()
        {
            static std::basic_string<CharT> name{'v','a','l','u','e'};
            return name;
        }
        static std::basic_string<CharT> dash_name()
        {
            static std::basic_string<CharT> name{'-'};
            return name;
        }
    };

    template<class Json>
    jsonpointer::basic_json_pointer<typename Json::char_type> definite_path(const Json& root, jsonpointer::basic_json_pointer<typename Json::char_type>& location)
    {
        using char_type = typename Json::char_type;
        using string_type = std::basic_string<char_type>;

        auto rit = location.rbegin();
        if (rit == location.rend())
        {
            return location;
        }

        if (*rit != jsonpatch_names<char_type>::dash_name())
        {
            return location;
        }

        std::vector<string_type> tokens;
        for (auto it = location.begin(); it != location.rbegin().base()-1; ++it)
        {
            tokens.push_back(*it);
        }
        jsonpointer::basic_json_pointer<char_type> pointer(tokens);

        std::error_code ec;

        Json val = jsonpointer::get(root, pointer, ec);
        if (ec || !val.is_array())
        {
            return location;
        }
        string_type last_token;
        jsoncons::detail::from_integer(val.size(), last_token);
        tokens.emplace_back(std::move(last_token));

        return jsonpointer::basic_json_pointer<char_type>(std::move(tokens));
    }

    enum class op_type {add,remove,replace};
    enum class state_type {begin,abort,commit};

    template <class Json>
    struct operation_unwinder
    {
        using char_type = typename Json::char_type;
        using string_type = std::basic_string<char_type>;
        using json_pointer_type = jsonpointer::basic_json_pointer<char_type>;

        struct entry
        {
            op_type op;
            json_pointer_type path;
            Json value;

            entry(op_type op, const json_pointer_type& path, const Json& value)
                : op(op), path(path), value(value)
            {
            }

            entry(const entry&) = default;

            entry(entry&&) = default;

            entry& operator=(const entry&) = default;

            entry& operator=(entry&&) = default;
        };

        Json& target;
        state_type state;
        std::vector<entry> stack;

        operation_unwinder(Json& j)
            : target(j), state(state_type::begin)
        {
        }

        ~operation_unwinder() noexcept
        {
            std::error_code ec;
            if (state != state_type::commit)
            {
                for (auto it = stack.rbegin(); it != stack.rend(); ++it)
                {
                    if (it->op == op_type::add)
                    {
                        jsonpointer::add(target,it->path,it->value,ec);
                        if (ec)
                        {
                            //std::cout << "add: " << it->path << std::endl;
                            break;
                        }
                    }
                    else if (it->op == op_type::remove)
                    {
                        jsonpointer::remove(target,it->path,ec);
                        if (ec)
                        {
                            //std::cout << "remove: " << it->path << std::endl;
                            break;
                        }
                    }
                    else if (it->op == op_type::replace)
                    {
                        jsonpointer::replace(target,it->path,it->value,ec);
                        if (ec)
                        {
                            //std::cout << "replace: " << it->path << std::endl;
                            break;
                        }
                    }
                }
            }
        }
    };

    template <class Json>
    Json from_diff(const Json& source, const Json& target, const typename Json::string_view_type& path)
    {
        using char_type = typename Json::char_type;

        Json result = typename Json::array();

        if (source == target)
        {
            return result;
        }

        if (source.is_array() && target.is_array())
        {
            std::size_t common = (std::min)(source.size(),target.size());
            for (std::size_t i = 0; i < common; ++i)
            {
                std::basic_string<char_type> ss(path); 
                ss.push_back('/');
                jsoncons::detail::from_integer(i,ss);
                auto temp_diff = from_diff(source[i],target[i],ss);
                result.insert(result.array_range().end(),temp_diff.array_range().begin(),temp_diff.array_range().end());
            }
            // Element in source, not in target - remove
            for (std::size_t i = source.size(); i-- > target.size();)
            {
                std::basic_string<char_type> ss(path); 
                ss.push_back('/');
                jsoncons::detail::from_integer(i,ss);
                Json val(json_object_arg);
                val.insert_or_assign(jsonpatch_names<char_type>::op_name(), jsonpatch_names<char_type>::remove_name());
                val.insert_or_assign(jsonpatch_names<char_type>::path_name(), ss);
                result.push_back(std::move(val));
            }
            // Element in target, not in source - add, 
            // Fix contributed by Alexander rog13
            for (std::size_t i = source.size(); i < target.size(); ++i)
            {
                const auto& a = target[i];
                std::basic_string<char_type> ss(path); 
                ss.push_back('/');
                jsoncons::detail::from_integer(i,ss);
                Json val(json_object_arg);
                val.insert_or_assign(jsonpatch_names<char_type>::op_name(), jsonpatch_names<char_type>::add_name());
                val.insert_or_assign(jsonpatch_names<char_type>::path_name(), ss);
                val.insert_or_assign(jsonpatch_names<char_type>::value_name(), a);
                result.push_back(std::move(val));
            }
        }
        else if (source.is_object() && target.is_object())
        {
            for (const auto& a : source.object_range())
            {
                std::basic_string<char_type> ss(path);
                ss.push_back('/'); 
                jsonpointer::escape(a.key(),ss);
                auto it = target.find(a.key());
                if (it != target.object_range().end())
                {
                    auto temp_diff = from_diff(a.value(),it->value(),ss);
                    result.insert(result.array_range().end(),temp_diff.array_range().begin(),temp_diff.array_range().end());
                }
                else
                {
                    Json val(json_object_arg);
                    val.insert_or_assign(jsonpatch_names<char_type>::op_name(), jsonpatch_names<char_type>::remove_name());
                    val.insert_or_assign(jsonpatch_names<char_type>::path_name(), ss);
                    result.push_back(std::move(val));
                }
            }
            for (const auto& a : target.object_range())
            {
                auto it = source.find(a.key());
                if (it == source.object_range().end())
                {
                    std::basic_string<char_type> ss(path); 
                    ss.push_back('/');
                    jsonpointer::escape(a.key(),ss);
                    Json val(json_object_arg);
                    val.insert_or_assign(jsonpatch_names<char_type>::op_name(), jsonpatch_names<char_type>::add_name());
                    val.insert_or_assign(jsonpatch_names<char_type>::path_name(), ss);
                    val.insert_or_assign(jsonpatch_names<char_type>::value_name(), a.value());
                    result.push_back(std::move(val));
                }
            }
        }
        else
        {
            Json val(json_object_arg);
            val.insert_or_assign(jsonpatch_names<char_type>::op_name(), jsonpatch_names<char_type>::replace_name());
            val.insert_or_assign(jsonpatch_names<char_type>::path_name(), path);
            val.insert_or_assign(jsonpatch_names<char_type>::value_name(), target);
            result.push_back(std::move(val));
        }

        return result;
    }
}

template <class Json>
void apply_patch(Json& target, const Json& patch, std::error_code& ec)
{
    using char_type = typename Json::char_type;
    using string_type = std::basic_string<char_type>;
    using json_pointer_type = jsonpointer::basic_json_pointer<char_type>;

   jsoncons::jsonpatch::detail::operation_unwinder<Json> unwinder(target);
   std::error_code local_ec;

    // Validate
     
    for (const auto& operation : patch.array_range())
    {
        unwinder.state =jsoncons::jsonpatch::detail::state_type::begin;

        auto it_op = operation.find(detail::jsonpatch_names<char_type>::op_name());
        if (it_op == operation.object_range().end())
        {
            ec = jsonpatch_errc::invalid_patch;
            unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
            return;
        }
        string_type op = it_op->value().template as<string_type>();

        auto it_path = operation.find(detail::jsonpatch_names<char_type>::path_name());
        if (it_path == operation.object_range().end())
        {
            ec = jsonpatch_errc::invalid_patch;
            unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
            return;
        }
        string_type path = it_path->value().template as<string_type>();
        auto location = json_pointer_type::parse(path, local_ec);
        if (local_ec)
        {
            ec = jsonpatch_errc::invalid_patch;
            unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
            return;
        }

        if (op ==jsoncons::jsonpatch::detail::jsonpatch_names<char_type>::test_name())
        {
            Json val = jsonpointer::get(target,location,local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::test_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            auto it_value = operation.find(detail::jsonpatch_names<char_type>::value_name());
            if (it_value == operation.object_range().end())
            {
                ec = jsonpatch_errc::invalid_patch;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            if (val != it_value->value())
            {
                ec = jsonpatch_errc::test_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
        }
        else if (op ==jsoncons::jsonpatch::detail::jsonpatch_names<char_type>::add_name())
        {
            auto it_value = operation.find(detail::jsonpatch_names<char_type>::value_name());
            if (it_value == operation.object_range().end())
            {
                ec = jsonpatch_errc::invalid_patch;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            Json val = it_value->value();
            auto npath = jsonpatch::detail::definite_path(target,location);

            std::error_code insert_ec;
            jsonpointer::add_if_absent(target,npath,val,insert_ec); // try insert without replace
            if (insert_ec) // try a replace
            {
                std::error_code select_ec;
                Json orig_val = jsonpointer::get(target,npath,select_ec);
                if (select_ec) // shouldn't happen
                {
                    ec = jsonpatch_errc::add_failed;
                    unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                    return;
                }
                std::error_code replace_ec;
                jsonpointer::replace(target,npath,val,replace_ec);
                if (replace_ec)
                {
                    ec = jsonpatch_errc::add_failed;
                    unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                    return;
                }
                unwinder.stack.emplace_back(detail::op_type::replace,npath,orig_val);
            }
            else // insert without replace succeeded
            {
                unwinder.stack.emplace_back(detail::op_type::remove,npath,Json::null());
            }
        }
        else if (op ==jsoncons::jsonpatch::detail::jsonpatch_names<char_type>::remove_name())
        {
            Json val = jsonpointer::get(target,location,local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::remove_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            jsonpointer::remove(target,location,local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::remove_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            unwinder.stack.emplace_back(detail::op_type::add, location, val);
        }
        else if (op ==jsoncons::jsonpatch::detail::jsonpatch_names<char_type>::replace_name())
        {
            Json val = jsonpointer::get(target,location,local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::replace_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            auto it_value = operation.find(detail::jsonpatch_names<char_type>::value_name());
            if (it_value == operation.object_range().end())
            {
                ec = jsonpatch_errc::invalid_patch;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            jsonpointer::replace(target, location, it_value->value(), local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::replace_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            unwinder.stack.emplace_back(detail::op_type::replace,location,val);
        }
        else if (op ==jsoncons::jsonpatch::detail::jsonpatch_names<char_type>::move_name())
        {
            auto it_from = operation.find(detail::jsonpatch_names<char_type>::from_name());
            if (it_from == operation.object_range().end())
            {
                ec = jsonpatch_errc::invalid_patch;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            string_type from = it_from->value().as_string();
            auto from_pointer = json_pointer_type::parse(from, local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::move_failed;
                unwinder.state = jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }

            Json val = jsonpointer::get(target, from_pointer, local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::move_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            jsonpointer::remove(target, from_pointer, local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::move_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            unwinder.stack.emplace_back(detail::op_type::add, from_pointer, val);
            // add
            std::error_code insert_ec;
            auto npath = jsonpatch::detail::definite_path(target,location);
            jsonpointer::add_if_absent(target,npath,val,insert_ec); // try insert without replace
            if (insert_ec) // try a replace
            {
                std::error_code select_ec;
                Json orig_val = jsonpointer::get(target,npath,select_ec);
                if (select_ec) // shouldn't happen
                {
                    ec = jsonpatch_errc::copy_failed;
                    unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                    return;
                }
                std::error_code replace_ec;
                jsonpointer::replace(target, npath, val, replace_ec);
                if (replace_ec)
                {
                    ec = jsonpatch_errc::copy_failed;
                    unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                    return;
                }
                unwinder.stack.emplace_back(jsoncons::jsonpatch::detail::op_type::replace,npath,orig_val);
            }
            else
            {
                unwinder.stack.emplace_back(detail::op_type::remove,npath,Json::null());
            }
        }
        else if (op ==jsoncons::jsonpatch::detail::jsonpatch_names<char_type>::copy_name())
        {
            auto it_from = operation.find(detail::jsonpatch_names<char_type>::from_name());
            if (it_from == operation.object_range().end())
            {
                ec = jsonpatch_errc::invalid_patch;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            string_type from = it_from->value().as_string();
            Json val = jsonpointer::get(target,from,local_ec);
            if (local_ec)
            {
                ec = jsonpatch_errc::copy_failed;
                unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                return;
            }
            // add
            auto npath = jsonpatch::detail::definite_path(target,location);
            std::error_code insert_ec;
            jsonpointer::add_if_absent(target,npath,val,insert_ec); // try insert without replace
            if (insert_ec) // Failed, try a replace
            {
                std::error_code select_ec;
                Json orig_val = jsonpointer::get(target,npath, select_ec);
                if (select_ec) // shouldn't happen
                {
                    ec = jsonpatch_errc::copy_failed;
                    unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                    return;
                }
                std::error_code replace_ec;
                jsonpointer::replace(target, npath, val,replace_ec);
                if (replace_ec)
                {
                    ec = jsonpatch_errc::copy_failed;
                    unwinder.state =jsoncons::jsonpatch::detail::state_type::abort;
                    return;
                }
                unwinder.stack.emplace_back(jsoncons::jsonpatch::detail::op_type::replace,npath,orig_val);
            }
            else
            {
                unwinder.stack.emplace_back(detail::op_type::remove,npath,Json::null());
            }
        }
    }
    if (unwinder.state ==jsoncons::jsonpatch::detail::state_type::begin)
    {
        unwinder.state =jsoncons::jsonpatch::detail::state_type::commit;
    }
}

template <class Json>
Json from_diff(const Json& source, const Json& target)
{
    std::basic_string<typename Json::char_type> path;
    return jsoncons::jsonpatch::detail::from_diff(source, target, path);
}

template <class Json>
void apply_patch(Json& target, const Json& patch)
{
    std::error_code ec;
    apply_patch(target, patch, ec);
    if (ec)
    {
        JSONCONS_THROW(jsonpatch_error(ec));
    }
}

}}

#endif