Repository navigation
Expand file tree
/
Copy pathdiff2test.cpp
More file actions
1488 lines (1476 loc) · 49.6 KB
/
Copy pathdiff2test.cpp
File metadata and controls
1488 lines (1476 loc) · 49.6 KB
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <cctype>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <optional>
#include <queue>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
namespace d2t::core {
enum class Outcome {
SubsetSelected = 0,
FullSuiteSelected = 10,
FullSuiteRequired = 11,
UsageError = 64,
InputError = 65,
InternalError = 70
};
constexpr std::string_view kVersion = "0.1.1";
int exit_code(Outcome o) { return static_cast<int>(o); }
} // namespace d2t::core
namespace d2t::json {
struct Position {
std::size_t offset = 0, line = 1, column = 1;
};
struct Error {
Position position;
std::string code;
std::string message;
};
struct Null final {};
struct Value;
using Array = std::vector<Value>;
using Object = std::map<std::string, Value, std::less<>>;
struct Value {
using Storage = std::variant<Null, bool, double, std::string, Array, Object>;
Storage data;
Value() : data(Null{}) {}
explicit Value(Null v) : data(v) {}
explicit Value(bool v) : data(v) {}
explicit Value(double v) : data(v) {}
explicit Value(std::string v) : data(std::move(v)) {}
explicit Value(Array v) : data(std::move(v)) {}
explicit Value(Object v) : data(std::move(v)) {}
bool is_null() const { return std::holds_alternative<Null>(data); }
bool is_bool() const { return std::holds_alternative<bool>(data); }
bool is_number() const { return std::holds_alternative<double>(data); }
bool is_string() const { return std::holds_alternative<std::string>(data); }
bool is_array() const { return std::holds_alternative<Array>(data); }
bool is_object() const { return std::holds_alternative<Object>(data); }
const bool &as_bool() const { return std::get<bool>(data); }
const double &as_number() const { return std::get<double>(data); }
const std::string &as_string() const { return std::get<std::string>(data); }
const Array &as_array() const { return std::get<Array>(data); }
const Object &as_object() const { return std::get<Object>(data); }
};
struct ParseOptions {
std::size_t max_bytes = 64U * 1024U * 1024U, max_nesting = 256U,
max_string_bytes = 16U * 1024U * 1024U;
};
struct ParseResult {
std::optional<Value> value;
std::optional<Error> error;
bool ok() const { return value.has_value(); }
};
namespace detail {
bool cont(unsigned char c) { return (c & 0xC0U) == 0x80U; }
bool valid_utf8(std::string_view s) {
for (std::size_t i = 0; i < s.size();) {
unsigned char c = static_cast<unsigned char>(s[i]);
if (c <= 0x7F) {
++i;
continue;
}
std::size_t n = 0;
std::uint32_t cp = 0;
if ((c & 0xE0U) == 0xC0U) {
if (c < 0xC2U)
return false;
n = 2;
cp = c & 0x1FU;
} else if ((c & 0xF0U) == 0xE0U) {
n = 3;
cp = c & 0x0FU;
} else if ((c & 0xF8U) == 0xF0U) {
if (c > 0xF4U)
return false;
n = 4;
cp = c & 0x07U;
} else
return false;
if (i + n > s.size())
return false;
for (std::size_t j = 1; j < n; ++j) {
unsigned char d = static_cast<unsigned char>(s[i + j]);
if (!cont(d))
return false;
cp = (cp << 6U) | (d & 0x3FU);
}
if ((n == 3 && cp < 0x800U) || (n == 4 && cp < 0x10000U) ||
(cp >= 0xD800U && cp <= 0xDFFFU) || cp > 0x10FFFFU)
return false;
i += n;
}
return true;
}
void append_utf8(std::string &out, std::uint32_t cp) {
if (cp <= 0x7F)
out.push_back(static_cast<char>(cp));
else if (cp <= 0x7FF) {
out.push_back(static_cast<char>(0xC0U | (cp >> 6U)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3FU)));
} else if (cp <= 0xFFFF) {
out.push_back(static_cast<char>(0xE0U | (cp >> 12U)));
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3FU)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3FU)));
} else {
out.push_back(static_cast<char>(0xF0U | (cp >> 18U)));
out.push_back(static_cast<char>(0x80U | ((cp >> 12U) & 0x3FU)));
out.push_back(static_cast<char>(0x80U | ((cp >> 6U) & 0x3FU)));
out.push_back(static_cast<char>(0x80U | (cp & 0x3FU)));
}
}
int hex(char c) {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
class Parser {
std::string_view in;
ParseOptions opt;
Position pos{};
std::optional<Error> err;
bool end() const { return pos.offset >= in.size(); }
char peek() const { return end() ? '\0' : in[pos.offset]; }
char adv() {
char c = in[pos.offset++];
if (c == '\n') {
++pos.line;
pos.column = 1;
} else
++pos.column;
return c;
}
void ws() {
while (!end() && (peek() == ' ' || peek() == '\t' || peek() == '\r' ||
peek() == '\n'))
adv();
}
std::optional<Value> failv(std::string c, std::string m) {
err = Error{pos, std::move(c), std::move(m)};
return std::nullopt;
}
bool literal(std::string_view x) {
for (char c : x) {
if (end() || peek() != c)
return false;
adv();
}
return true;
}
std::optional<std::uint16_t> hex4() {
if (in.size() - pos.offset < 4) {
failv("JSON_INVALID_UNICODE_ESCAPE", "incomplete unicode escape");
return std::nullopt;
}
std::uint16_t v = 0;
for (int i = 0; i < 4; ++i) {
int d = hex(peek());
if (d < 0) {
failv("JSON_INVALID_UNICODE_ESCAPE", "invalid unicode escape");
return std::nullopt;
}
adv();
v = static_cast<std::uint16_t>((v << 4U) | static_cast<unsigned>(d));
}
return v;
}
std::optional<std::string> str() {
adv();
std::string out;
while (!end()) {
unsigned char c = static_cast<unsigned char>(peek());
if (c == '"') {
adv();
return out;
}
if (c < 0x20U) {
failv("JSON_CONTROL_IN_STRING", "control character in string");
return std::nullopt;
}
if (c != '\\') {
out.push_back(adv());
if (out.size() > opt.max_string_bytes) {
failv("JSON_STRING_TOO_LARGE", "string limit");
return std::nullopt;
}
continue;
}
adv();
if (end()) {
failv("JSON_UNTERMINATED_STRING", "unterminated string");
return std::nullopt;
}
char e = adv();
switch (e) {
case '"':
out.push_back('"');
break;
case '\\':
out.push_back('\\');
break;
case '/':
out.push_back('/');
break;
case 'b':
out.push_back('\b');
break;
case 'f':
out.push_back('\f');
break;
case 'n':
out.push_back('\n');
break;
case 'r':
out.push_back('\r');
break;
case 't':
out.push_back('\t');
break;
case 'u': {
auto a = hex4();
if (!a)
return std::nullopt;
std::uint32_t cp = *a;
if (cp >= 0xD800U && cp <= 0xDBFFU) {
if (in.size() - pos.offset < 6 || peek() != '\\' ||
in[pos.offset + 1] != 'u') {
failv("JSON_UNPAIRED_SURROGATE", "unpaired surrogate");
return std::nullopt;
}
adv();
adv();
auto b = hex4();
if (!b)
return std::nullopt;
if (*b < 0xDC00U || *b > 0xDFFFU) {
failv("JSON_UNPAIRED_SURROGATE", "unpaired surrogate");
return std::nullopt;
}
cp = 0x10000U + ((cp - 0xD800U) << 10U) +
(static_cast<std::uint32_t>(*b) - 0xDC00U);
} else if (cp >= 0xDC00U && cp <= 0xDFFFU) {
failv("JSON_UNPAIRED_SURROGATE", "unpaired surrogate");
return std::nullopt;
}
append_utf8(out, cp);
break;
}
default:
failv("JSON_INVALID_ESCAPE", "invalid escape");
return std::nullopt;
}
if (out.size() > opt.max_string_bytes) {
failv("JSON_STRING_TOO_LARGE", "string limit");
return std::nullopt;
}
}
failv("JSON_UNTERMINATED_STRING", "unterminated string");
return std::nullopt;
}
std::optional<Value> num() {
std::size_t start = pos.offset;
if (peek() == '-')
adv();
if (end())
return failv("JSON_INVALID_NUMBER", "bad number");
if (peek() == '0') {
adv();
if (!end() && std::isdigit(static_cast<unsigned char>(peek())))
return failv("JSON_INVALID_NUMBER", "leading zero");
} else if (peek() >= '1' && peek() <= '9') {
while (!end() && std::isdigit(static_cast<unsigned char>(peek())))
adv();
} else
return failv("JSON_INVALID_NUMBER", "bad number");
if (!end() && peek() == '.') {
adv();
if (end() || !std::isdigit(static_cast<unsigned char>(peek())))
return failv("JSON_INVALID_NUMBER", "bad fraction");
while (!end() && std::isdigit(static_cast<unsigned char>(peek())))
adv();
}
if (!end() && (peek() == 'e' || peek() == 'E')) {
adv();
if (!end() && (peek() == '+' || peek() == '-'))
adv();
if (end() || !std::isdigit(static_cast<unsigned char>(peek())))
return failv("JSON_INVALID_NUMBER", "bad exponent");
while (!end() && std::isdigit(static_cast<unsigned char>(peek())))
adv();
}
std::string tmp(in.substr(start, pos.offset - start));
char *ep = nullptr;
double v = std::strtod(tmp.c_str(), &ep);
if (ep != tmp.c_str() + tmp.size() || !std::isfinite(v))
return failv("JSON_INVALID_NUMBER", "number out of range");
return Value{v};
}
std::optional<Value> arr(std::size_t depth) {
if (depth > opt.max_nesting)
return failv("JSON_NESTING_LIMIT", "nesting limit");
adv();
ws();
Array a;
if (!end() && peek() == ']') {
adv();
return Value{std::move(a)};
}
while (true) {
auto v = value(depth);
if (!v)
return std::nullopt;
a.push_back(std::move(*v));
ws();
if (end())
return failv("JSON_EXPECTED_COMMA", "unterminated array");
if (peek() == ']') {
adv();
break;
}
if (peek() != ',')
return failv("JSON_EXPECTED_COMMA", "expected comma");
adv();
ws();
if (!end() && peek() == ']')
return failv("JSON_TRAILING_COMMA", "trailing comma");
}
return Value{std::move(a)};
}
std::optional<Value> obj(std::size_t depth) {
if (depth > opt.max_nesting)
return failv("JSON_NESTING_LIMIT", "nesting limit");
adv();
ws();
Object o;
if (!end() && peek() == '}') {
adv();
return Value{std::move(o)};
}
while (true) {
if (end() || peek() != '"')
return failv("JSON_EXPECTED_KEY", "expected key");
auto k = str();
if (!k)
return std::nullopt;
ws();
if (end() || peek() != ':')
return failv("JSON_EXPECTED_COLON", "expected colon");
adv();
ws();
auto v = value(depth);
if (!v)
return std::nullopt;
if (o.contains(*k))
return failv("JSON_DUPLICATE_KEY", "duplicate key");
o.emplace(std::move(*k), std::move(*v));
ws();
if (end())
return failv("JSON_EXPECTED_COMMA", "unterminated object");
if (peek() == '}') {
adv();
break;
}
if (peek() != ',')
return failv("JSON_EXPECTED_COMMA", "expected comma");
adv();
ws();
if (!end() && peek() == '}')
return failv("JSON_TRAILING_COMMA", "trailing comma");
}
return Value{std::move(o)};
}
std::optional<Value> value(std::size_t depth) {
if (depth > opt.max_nesting)
return failv("JSON_NESTING_LIMIT", "nesting limit");
if (end())
return failv("JSON_EXPECTED_VALUE", "expected value");
if (peek() == 'n') {
if (!literal("null"))
return failv("JSON_INVALID_LITERAL", "bad literal");
return Value{Null{}};
}
if (peek() == 't') {
if (!literal("true"))
return failv("JSON_INVALID_LITERAL", "bad literal");
return Value{true};
}
if (peek() == 'f') {
if (!literal("false"))
return failv("JSON_INVALID_LITERAL", "bad literal");
return Value{false};
}
if (peek() == '"') {
auto x = str();
return x ? std::optional<Value>{Value{std::move(*x)}} : std::nullopt;
}
if (peek() == '[')
return arr(depth + 1);
if (peek() == '{')
return obj(depth + 1);
if (peek() == '-' || std::isdigit(static_cast<unsigned char>(peek())))
return num();
return failv("JSON_EXPECTED_VALUE", "expected value");
}
public:
Parser(std::string_view s, ParseOptions o) : in(s), opt(o) {}
ParseResult parse() {
if (in.size() > opt.max_bytes)
return {std::nullopt, Error{pos, "JSON_INPUT_TOO_LARGE", "input limit"}};
if (!valid_utf8(in))
return {std::nullopt, Error{pos, "JSON_INVALID_UTF8", "invalid UTF-8"}};
ws();
auto v = value(0);
if (!v)
return {std::nullopt, err};
ws();
if (!end())
return {std::nullopt, Error{pos, "JSON_TRAILING_DATA", "trailing data"}};
return {std::move(v), std::nullopt};
}
};
} // namespace detail
ParseResult parse(std::string_view input, ParseOptions opt = {}) {
return detail::Parser(input, opt).parse();
}
const Value *find_member(const Value &v, std::string_view key) {
if (!v.is_object())
return nullptr;
auto it = v.as_object().find(key);
return it == v.as_object().end() ? nullptr : &it->second;
}
} // namespace d2t::json
namespace d2t::dep {
struct Error {
std::string code, message;
};
struct Rule {
std::vector<std::string> targets, prerequisites;
};
struct ParseResult {
std::vector<Rule> rules;
std::optional<Error> error;
bool ok() const { return !error.has_value(); }
};
ParseResult parse(std::string_view input) {
if (input.find('\0') != std::string_view::npos)
return {{}, Error{"DEP_NUL", "NUL byte"}};
std::string logical;
logical.reserve(input.size());
for (std::size_t i = 0; i < input.size(); ++i) {
if (input[i] == '\\' && i + 1 < input.size() && input[i + 1] == '\n') {
++i;
logical.push_back(' ');
continue;
}
if (input[i] == '\\' && i + 2 < input.size() && input[i + 1] == '\r' &&
input[i + 2] == '\n') {
i += 2;
logical.push_back(' ');
continue;
}
logical.push_back(input[i]);
}
if (!logical.empty() && logical.back() == '\\')
return {{}, Error{"DEP_TRAILING_ESCAPE", "trailing escape"}};
ParseResult out;
std::istringstream lines(logical);
std::string line;
while (std::getline(lines, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
bool esc = false;
std::size_t hash = std::string::npos, colon = std::string::npos;
for (std::size_t i = 0; i < line.size(); ++i) {
char c = line[i];
if (esc) {
esc = false;
continue;
}
if (c == '\\') {
esc = true;
continue;
}
if (c == '#') {
hash = i;
break;
}
if (c == ':' && colon == std::string::npos)
colon = i;
}
if (hash != std::string::npos)
line.resize(hash);
auto only_ws = [](std::string_view x) {
return std::all_of(x.begin(), x.end(),
[](char c) { return c == ' ' || c == '\t'; });
};
if (line.empty() || only_ws(line))
continue;
esc = false;
colon = std::string::npos;
for (std::size_t i = 0; i < line.size(); ++i) {
char c = line[i];
if (esc) {
esc = false;
continue;
}
if (c == '\\') {
esc = true;
continue;
}
if (c == ':') {
colon = i;
break;
}
}
if (colon == std::string::npos)
return {{}, Error{"DEP_MISSING_COLON", "missing rule separator"}};
auto tokens =
[](std::string_view s) -> std::optional<std::vector<std::string>> {
std::vector<std::string> v;
std::string cur;
bool escaped = false;
for (char c : s) {
if (escaped) {
cur.push_back(c);
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (c == ' ' || c == '\t') {
if (!cur.empty()) {
v.push_back(cur);
cur.clear();
}
} else
cur.push_back(c);
}
if (escaped)
return std::nullopt;
if (!cur.empty())
v.push_back(cur);
return v;
};
auto t = tokens(std::string_view(line).substr(0, colon));
auto p = tokens(std::string_view(line).substr(colon + 1));
if (!t || !p)
return {{}, Error{"DEP_TRAILING_ESCAPE", "trailing escape"}};
if (t->empty())
return {{}, Error{"DEP_EMPTY_TARGET", "empty target"}};
std::sort(p->begin(), p->end());
p->erase(std::unique(p->begin(), p->end()), p->end());
out.rules.push_back({std::move(*t), std::move(*p)});
}
return out;
}
} // namespace d2t::dep
namespace d2t::path {
enum class RootClass { Project, Build, External };
struct Normalized {
std::filesystem::path absolute, display;
RootClass root_class = RootClass::Project;
};
struct Result {
std::optional<Normalized> value;
std::string error;
bool ok() const { return value.has_value(); }
};
bool has_prefix(const std::filesystem::path &child,
const std::filesystem::path &root) {
auto c = child.begin(), r = root.begin();
for (; r != root.end(); ++r, ++c) {
if (c == child.end() || *c != *r)
return false;
}
return true;
}
Result normalize(const std::filesystem::path &raw,
const std::filesystem::path &project_root,
const std::filesystem::path &build_root,
bool allow_external = false) {
if (raw.empty())
return {std::nullopt, "empty path"};
auto p = project_root.lexically_normal();
auto b = build_root.lexically_normal();
if (!p.is_absolute() || !b.is_absolute())
return {std::nullopt, "roots must be absolute"};
std::filesystem::path abs =
(raw.is_absolute() ? raw : (p / raw)).lexically_normal();
if (has_prefix(abs, p))
return {Normalized{abs, abs.lexically_relative(p), RootClass::Project}, {}};
if (has_prefix(abs, b))
return {Normalized{abs, abs.lexically_relative(b), RootClass::Build}, {}};
if (allow_external && abs.is_absolute())
return {Normalized{abs, abs, RootClass::External}, {}};
return {std::nullopt, "path escapes declared roots"};
}
} // namespace d2t::path
namespace d2t::io {
struct ReadResult {
std::optional<std::string> data;
std::string error;
bool ok() const { return data.has_value(); }
};
ReadResult read_text(const std::filesystem::path &p,
std::size_t max_bytes = 64U * 1024U * 1024U) {
std::ifstream f(p, std::ios::binary);
if (!f)
return {std::nullopt, "cannot open file: " + p.string()};
f.seekg(0, std::ios::end);
auto n = f.tellg();
if (n < 0)
return {std::nullopt, "cannot size file: " + p.string()};
if (static_cast<std::uint64_t>(n) > max_bytes)
return {std::nullopt, "file too large: " + p.string()};
f.seekg(0);
std::string s(static_cast<std::size_t>(n), '\0');
if (!s.empty())
f.read(s.data(), static_cast<std::streamsize>(s.size()));
if (!f && !s.empty())
return {std::nullopt, "cannot read file: " + p.string()};
return {std::move(s), {}};
}
} // namespace d2t::io
namespace d2t::ctest {
struct RegisteredTest {
std::string name;
std::vector<std::string> command;
};
struct Catalogue {
std::vector<RegisteredTest> tests;
};
struct LoadResult {
std::optional<Catalogue> catalogue;
std::string error;
bool ok() const { return catalogue.has_value(); }
};
LoadResult parse_catalogue(std::string_view text) {
auto parsed = json::parse(text);
if (!parsed.ok())
return {std::nullopt, "invalid CTest JSON: " + parsed.error->code};
const auto &root = *parsed.value;
auto kind = json::find_member(root, "kind");
auto version = json::find_member(root, "version");
auto tests = json::find_member(root, "tests");
if (!kind || !kind->is_string() || kind->as_string() != "ctestInfo")
return {std::nullopt, "CTest kind must be ctestInfo"};
if (!version || !version->is_object())
return {std::nullopt, "CTest version missing"};
auto major = json::find_member(*version, "major");
if (!major || !major->is_number() || major->as_number() != 1.0)
return {std::nullopt, "unsupported CTest major version"};
if (!tests || !tests->is_array())
return {std::nullopt, "CTest tests missing"};
Catalogue out;
std::set<std::string> names;
for (const auto &tv : tests->as_array()) {
auto name = json::find_member(tv, "name");
auto command = json::find_member(tv, "command");
if (!name || !name->is_string() || name->as_string().empty())
return {std::nullopt, "invalid CTest test name"};
if (!names.insert(name->as_string()).second)
return {std::nullopt, "duplicate CTest test name"};
if (!command || !command->is_array() || command->as_array().empty())
return {std::nullopt, "invalid CTest command"};
RegisteredTest t;
t.name = name->as_string();
for (const auto &x : command->as_array()) {
if (!x.is_string())
return {std::nullopt, "non-string CTest command token"};
t.command.push_back(x.as_string());
}
out.tests.push_back(std::move(t));
}
std::sort(out.tests.begin(), out.tests.end(),
[](const auto &a, const auto &b) { return a.name < b.name; });
return {std::move(out), {}};
}
LoadResult load(const std::filesystem::path &p) {
auto r = io::read_text(p);
if (!r.ok())
return {std::nullopt, r.error};
return parse_catalogue(*r.data);
}
} // namespace d2t::ctest
namespace d2t::cmake {
struct Target {
std::string id, name, type;
std::vector<std::filesystem::path> sources, artifacts;
std::vector<std::string> dependencies;
};
struct Model {
std::filesystem::path source_root, build_root;
std::string configuration;
std::vector<Target> targets;
};
struct LoadResult {
std::optional<Model> model;
std::string error;
bool ok() const { return model.has_value(); }
};
std::optional<std::filesystem::path>
safe_child(const std::filesystem::path &root, std::string_view rel) {
std::filesystem::path p(rel);
if (p.is_absolute())
return std::nullopt;
auto abs = (root / p).lexically_normal();
if (!path::has_prefix(abs, root.lexically_normal()))
return std::nullopt;
return abs;
}
LoadResult load(const std::filesystem::path &reply,
std::optional<std::filesystem::path> explicit_index,
std::optional<std::string> config) {
std::vector<std::filesystem::path> indexes;
if (explicit_index) {
indexes.push_back(*explicit_index);
} else {
std::error_code ec;
for (const auto &e : std::filesystem::directory_iterator(reply, ec)) {
if (ec)
break;
if (e.is_regular_file() &&
e.path().filename().string().rfind("index-", 0) == 0 &&
e.path().extension() == ".json")
indexes.push_back(e.path());
}
}
if (indexes.size() != 1)
return {std::nullopt, "CMake reply index is missing or ambiguous"};
auto ir = io::read_text(indexes[0]);
if (!ir.ok())
return {std::nullopt, ir.error};
auto ip = json::parse(*ir.data);
if (!ip.ok())
return {std::nullopt, "invalid CMake index JSON"};
auto rep = json::find_member(*ip.value, "reply");
if (!rep || !rep->is_object())
return {std::nullopt, "CMake reply missing"};
auto cm = json::find_member(*rep, "codemodel-v2");
if (!cm || !cm->is_object())
return {std::nullopt, "codemodel-v2 missing"};
auto ver = json::find_member(*cm, "version");
auto jf = json::find_member(*cm, "jsonFile");
if (!ver || !jf || !jf->is_string())
return {std::nullopt, "codemodel reference invalid"};
auto maj = json::find_member(*ver, "major");
if (!maj || !maj->is_number() || maj->as_number() != 2.0)
return {std::nullopt, "unsupported codemodel major"};
auto cmfile = safe_child(reply, jf->as_string());
if (!cmfile)
return {std::nullopt, "codemodel reference escapes reply root"};
auto cr = io::read_text(*cmfile);
if (!cr.ok())
return {std::nullopt, cr.error};
auto cp = json::parse(*cr.data);
if (!cp.ok())
return {std::nullopt, "invalid codemodel JSON"};
auto paths = json::find_member(*cp.value, "paths");
auto configs = json::find_member(*cp.value, "configurations");
if (!paths || !configs || !configs->is_array())
return {std::nullopt, "codemodel structure invalid"};
auto src = json::find_member(*paths, "source");
auto build = json::find_member(*paths, "build");
if (!src || !build || !src->is_string() || !build->is_string())
return {std::nullopt, "codemodel paths invalid"};
const json::Value *chosen = nullptr;
for (const auto &c : configs->as_array()) {
auto n = json::find_member(c, "name");
if (!n || !n->is_string())
continue;
if (config) {
if (n->as_string() == *config) {
if (chosen)
return {std::nullopt, "duplicate configuration"};
chosen = &c;
}
} else {
if (chosen)
return {std::nullopt,
"multiple configurations require --configuration"};
chosen = &c;
}
}
if (!chosen)
return {std::nullopt, "configuration not found"};
auto targets = json::find_member(*chosen, "targets");
if (!targets || !targets->is_array())
return {std::nullopt, "configuration targets missing"};
Model out;
out.source_root = src->as_string();
out.build_root = build->as_string();
out.configuration = config.value_or("");
std::set<std::string> ids;
for (const auto &tr : targets->as_array()) {
auto id = json::find_member(tr, "id");
auto file = json::find_member(tr, "jsonFile");
if (!id || !file || !id->is_string() || !file->is_string())
return {std::nullopt, "target reference invalid"};
if (!ids.insert(id->as_string()).second)
return {std::nullopt, "duplicate target id"};
auto tf = safe_child(reply, file->as_string());
if (!tf)
return {std::nullopt, "target reference escapes reply root"};
auto rr = io::read_text(*tf);
if (!rr.ok())
return {std::nullopt, rr.error};
auto tp = json::parse(*rr.data);
if (!tp.ok())
return {std::nullopt, "invalid target JSON"};
auto tid = json::find_member(*tp.value, "id");
auto name = json::find_member(*tp.value, "name");
auto type = json::find_member(*tp.value, "type");
if (!tid || !name || !type || !tid->is_string() ||
tid->as_string() != id->as_string() || !name->is_string() ||
!type->is_string())
return {std::nullopt, "target identity invalid"};
Target t;
t.id = id->as_string();
t.name = name->as_string();
t.type = type->as_string();
if (auto s = json::find_member(*tp.value, "sources")) {
if (!s->is_array())
return {std::nullopt, "target sources invalid"};
for (const auto &sv : s->as_array()) {
auto p = json::find_member(sv, "path");
if (!p || !p->is_string())
return {std::nullopt, "source path invalid"};
if (auto g = json::find_member(sv, "isGenerated");
g && g->is_bool() && g->as_bool())
return {std::nullopt, "generated source unsupported"};
t.sources.emplace_back(p->as_string());
}
}
if (auto a = json::find_member(*tp.value, "artifacts")) {
if (!a->is_array())
return {std::nullopt, "target artifacts invalid"};
for (const auto &av : a->as_array()) {
auto p = json::find_member(av, "path");
if (!p || !p->is_string())
return {std::nullopt, "artifact path invalid"};
t.artifacts.emplace_back(p->as_string());
}
}
if (auto d = json::find_member(*tp.value, "dependencies")) {
if (!d->is_array())
return {std::nullopt, "target dependencies invalid"};
for (const auto &dv : d->as_array()) {
auto p = json::find_member(dv, "id");
if (!p || !p->is_string())
return {std::nullopt, "dependency id invalid"};
t.dependencies.push_back(p->as_string());
}
}
out.targets.push_back(std::move(t));
}
std::sort(out.targets.begin(), out.targets.end(),
[](const auto &a, const auto &b) { return a.id < b.id; });
return {std::move(out), {}};
}
} // namespace d2t::cmake
namespace d2t::mapping {
struct TestMapping {
std::string test_name, target_id;
};
struct Result {
std::vector<TestMapping> mappings;
std::vector<std::string> issues;
bool complete() const { return issues.empty(); }
};
Result map_tests(const ctest::Catalogue &cat, const cmake::Model &model,
const std::filesystem::path &build_root) {
std::map<std::filesystem::path, std::vector<std::string>> artifacts;
for (const auto &t : model.targets)
for (const auto &a : t.artifacts) {
auto p = (a.is_absolute() ? a : (build_root / a)).lexically_normal();
artifacts[p].push_back(t.id);
}
Result out;
for (const auto &test : cat.tests) {
std::filesystem::path cmd = test.command.front();
auto p = (cmd.is_absolute() ? cmd : (build_root / cmd)).lexically_normal();
auto it = artifacts.find(p);
if (it == artifacts.end() || it->second.size() != 1) {
out.issues.push_back("test " + test.name +
" does not map uniquely to a target artifact");
continue;
}
out.mappings.push_back({test.name, it->second.front()});
}
std::sort(
out.mappings.begin(), out.mappings.end(),
[](const auto &a, const auto &b) { return a.test_name < b.test_name; });
return out;
}
} // namespace d2t::mapping
namespace d2t::cli {
struct AnalyzeOptions {
std::filesystem::path project_root, build_root, cmake_reply, ctest_info,
dep_list;
std::string changed_files;
std::optional<std::filesystem::path> cmake_index;
std::optional<std::string> configuration;
std::string format = "human";
bool explain = false, verbose = false;
};
struct ParseResult {
bool ok = false;
AnalyzeOptions options;
std::string error;
};
void print_help(std::ostream &out) {
out << "diff2test - conservative C++ test-impact analysis\n\nUsage:\n "
"diff2test --help\n diff2test --version\n diff2test analyze "
"[project-root] [options]\n\nDefaults:\n project-root: .\n "
"build root: <project-root>/build\n changed paths: stdin\n "
"CMake reply: <build-root>/.cmake/api/v1/reply\n CTest catalogue: "
"<build-root>/ctest-info.json\n dependency list: "
"<build-root>/deps.txt\n\n"
"Overrides:\n --project-root <dir>\n --build <dir>\n --build-root "
"<dir>\n --changed-files <file|->\n --cmake-reply <dir>\n "
"--ctest-info <file>\n --dep-list <file>\n --cmake-index <file>\n "
"--configuration <name>\n --format <human|names>\n --explain\n "
"--verbose\n\nCMake, CTest, Git, and the compiler may generate input "
"externally, but diff2test never launches them or any other program "
"at "
"runtime.\n";
}
ParseResult parse_analyze(int argc, char **argv) {
ParseResult r;
std::map<std::string, std::string> v;
std::set<std::string> f;
std::optional<std::string> positional_project_root;
const std::set<std::string> vo = {
"--project-root", "--build", "--build-root", "--changed-files",
"--cmake-reply", "--cmake-index", "--ctest-info", "--dep-list",
"--configuration", "--format"};
const std::set<std::string> fo = {"--explain", "--verbose"};
for (int i = 2; i < argc; ++i) {
std::string a = argv[i];
if (vo.contains(a)) {
if (v.contains(a)) {
r.error = "repeated option: " + a;
return r;
}
if (i + 1 >= argc) {
r.error = "missing value for option: " + a;
return r;
}
v.emplace(a, argv[++i]);
} else if (fo.contains(a)) {
if (!f.insert(a).second) {
r.error = "repeated option: " + a;
return r;
}
} else if (!a.empty() && a.front() == '-') {
r.error = "unknown option: " + a;
return r;
} else {
if (positional_project_root) {
r.error = "multiple positional project roots";
return r;