Repository navigation
Expand file tree
/
Copy pathcommands.cpp
More file actions
1974 lines (1925 loc) · 84.2 KB
/
Copy pathcommands.cpp
File metadata and controls
1974 lines (1925 loc) · 84.2 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
module mcpplibs.mtest.engine.commands;
import std;
import mcpplibs.os;
import mcpplibs.mtest.engine.config;
import mcpplibs.mtest.engine.store;
import mcpplibs.mtest.engine.select;
import mcpplibs.mtest.engine.schedule;
import mcpplibs.mtest.engine.analysis;
import mcpplibs.mtest.engine.output;
import mcpplibs.mtest.engine.exec;
import mcpplibs.mtest.engine.coverage;
import mcpplibs.mtest.engine.capability;
import mcpplibs.mtest.engine.cicheck;
import mcpplibs.mtest.engine.dag;
import mcpplibs.mtest.engine.report;
import mcpplibs.mtest.manifest;
namespace mcpplibs::mtest::engine {
namespace manifest = mcpplibs::mtest::manifest;
namespace os = mcpplibs::os;
namespace {
answer usage(std::string message) {
return {2, {{"error", message}, {"conclusion", message}}, "mtest: " + message + "\n"};
}
answer machine(std::string message) {
return {3, {{"error", message}, {"conclusion", message}}, "mtest: " + message + "\n"};
}
std::vector<std::string> strings(const json& p, const char* key) {
std::vector<std::string> out;
if (auto it = p.find(key); it != p.end()) {
if (it->is_string())
out.push_back(it->get<std::string>());
else if (it->is_array())
for (const auto& v : *it)
if (v.is_string())
out.push_back(v.get<std::string>());
}
return out;
}
// A string parameter; a list (the command line repeats `--case`) gives its first value.
std::string text_of(const json& p, const char* key, std::string fallback = {}) {
auto it = p.find(key);
if (it == p.end())
return fallback;
if (it->is_string())
return it->get<std::string>();
if (it->is_array() && !it->empty() && it->front().is_string())
return it->front().get<std::string>();
return fallback;
}
// The project: the nearest directory upward with mtest.toml, else `cwd`.
std::filesystem::path project_root(const std::filesystem::path& cwd) {
for (auto d = cwd; !d.empty(); d = d.parent_path()) {
if (std::filesystem::exists(d / "mtest.toml"))
return d;
if (d == d.parent_path())
break;
}
return cwd;
}
struct context {
config cfg;
store st;
};
std::expected<context, answer> open(const std::filesystem::path& cwd) {
const auto root = project_root(cwd);
auto c = load_config(root);
if (!c)
return std::unexpected(usage(c.error()));
auto dir = c->store.is_absolute() ? c->store : root / c->store;
return context{std::move(*c), open_store(dir)};
}
// A command line given as one string, split by spaces outside quotes (a program and its arguments).
std::vector<std::string> split_command(std::string_view s) {
std::vector<std::string> out;
std::string cur;
char quote = 0;
bool any = false;
for (char ch : s) {
if (quote) {
if (ch == quote)
quote = 0;
else
cur += ch;
continue;
}
if (ch == '"' || ch == '\'') {
quote = ch;
any = true;
continue;
}
if (std::isspace(static_cast<unsigned char>(ch))) {
if (any || !cur.empty())
out.push_back(cur);
cur.clear();
any = false;
continue;
}
cur += ch;
}
if (any || !cur.empty())
out.push_back(cur);
return out;
}
std::expected<selection_request, answer> selection_of(const context& ctx, const json& p) {
selection_request r;
r.set = text_of(p, "set");
r.cases = strings(p, "case");
r.tags = strings(p, "tag");
r.kinds = strings(p, "kind");
r.programs = strings(p, "program");
r.exclude_tags = strings(p, "exclude_tag");
r.exclude_programs = strings(p, "exclude_program");
r.failed_only = p.value("failed", false);
r.run_under = strings(p, "run_under");
if (auto e = p.find("env"); e != p.end() && e->is_object())
for (auto& item_ : e->items())
if (item_.value().is_string())
r.env.emplace_back(item_.key(), item_.value().get<std::string>());
if (auto since = text_of(p, "since"); !since.empty()) {
auto paths = changed_since(ctx.cfg.root, since);
if (!paths)
return std::unexpected(machine(paths.error()));
r.changed = *paths;
} else if (p.contains("changed")) {
r.changed = strings(p, "changed");
}
if (auto b = text_of(p, "budget"); !b.empty()) {
auto d = parse_duration(b);
if (!d)
return std::unexpected(usage(std::format("budget {} is not a duration (60s, 5m)", b)));
r.budget = d;
}
if (auto sh = text_of(p, "shard"); !sh.empty()) {
auto parts = parse_shard(sh);
if (!parts)
return std::unexpected(usage(parts.error()));
r.shard = *parts;
}
if (r.set == "pr" && !r.changed) {
// The `pr` set is the change's: against the branch a pull request merges into, else main.
const auto base = os::env::get("GITHUB_BASE_REF").value_or("");
auto paths = changed_since(ctx.cfg.root, base.empty() ? "origin/main" : "origin/" + base);
if (paths)
r.changed = *paths;
else
r.unknown_change = paths.error();
}
return r;
}
std::expected<std::vector<program_spec>, answer> programs_of(const context& ctx, const json& p) {
program_source src;
for (const auto& cmd : strings(p, "programs"))
src.commands.push_back(split_command(cmd));
if (auto it = p.find("argv"); it != p.end() && it->is_array()) {
std::vector<std::string> argv;
for (const auto& v : *it)
if (v.is_string())
argv.push_back(v.get<std::string>());
if (!argv.empty())
src.commands.push_back(argv);
}
auto programs = discover(ctx.cfg, src);
if (!programs)
return std::unexpected(machine(programs.error()));
if (programs->empty())
return std::unexpected(usage("no program to run: name one (`mtest run ./test`), declare "
"[programs.*] or [discover] in mtest.toml, "
"or set [host] kind = \"mcpp\""));
for (auto& s : *programs)
if (auto t = text_of(p, "timeout"); !t.empty())
if (auto d = parse_duration(t))
s.timeout = std::chrono::duration_cast<std::chrono::seconds>(*d);
for (auto& s : *programs)
if (auto t = text_of(p, "grace"); !t.empty())
if (auto d = parse_duration(t))
s.grace = *d;
if (p.value("isolate", false))
for (auto& s : *programs)
s.isolation = "case";
return *programs;
}
std::string describe_selection(const json& p) {
json q = p;
q.erase("programs");
q.erase("argv");
q.erase("report");
q.erase("monitor");
q.erase("group");
q.erase("sections");
return dumped(q);
}
report_options report_options_of(const context& ctx, const json& p);
answer finish_run(const context& ctx, const run_record& r, const json& p, const plan& pl) {
if (auto rep = p.find("report"); rep != p.end() && rep->is_object()) {
if (auto f = text_of(*rep, "junit"); !f.empty())
(void)os::fs::write(os::fs::from_utf8(f), junit_xml(r));
if (auto f = text_of(*rep, "html"); !f.empty())
(void)os::fs::write(os::fs::from_utf8(f), html_page(r));
if (auto f = text_of(*rep, "md"); !f.empty())
(void)os::fs::write(os::fs::from_utf8(f),
markdown_report(ctx.st, {r}, report_options_of(ctx, p)));
if (auto f = text_of(*rep, "json"); !f.empty()) {
json all = to_json(r);
all["cases"] = json::array();
for (const auto& c : r.cases)
all["cases"].push_back(to_json(c));
// The run's timeline: each program's start, duration, status and what it held.
all["timeline"] = json::array();
for (const auto& pr : r.programs)
all["timeline"].push_back(to_json(pr));
(void)os::fs::write(os::fs::from_utf8(f), dumped(all, 2) + "\n");
}
}
json failing_cases = json::array();
for (const auto& c : r.cases)
if (failing(c.status) && !c.quarantined)
failing_cases.push_back(
{{"program", c.program},
{"case", c.id},
{"kind", c.kind},
{"status", c.status},
{"where", c.failures.empty()
? std::string{}
: std::format("{}:{}", c.failures[0].file, c.failures[0].line)},
{"why", c.failures.empty() ? c.reason : c.failures[0].message},
{"again",
[&] {
for (const auto& pr : r.programs)
if (pr.name == c.program)
return reproduce_command(pr, c.id);
return reproduce_command(c.program, c.id);
}()},
{"diagnosis", c.diagnosis}});
json data = to_json(r);
data["failing"] = failing_cases;
data["notes"] = pl.notes;
data["conclusion"] =
r.status == "pass"
? std::format("{} case(s) passed in {:.1f} s", r.cases.size(), r.ms / 1000)
: r.status == "infra" ? std::string("no test failed, but a program could not be started: "
"the machine's failure (mtest explain)")
: r.status == "cancelled"
? std::string("the run was cancelled")
: std::format("{} case(s) failed; the first: {}::{} -- mtest explain --case '{}'",
failing_cases.size(),
failing_cases.empty() ? ""
: failing_cases[0]["program"].get<std::string>(),
failing_cases.empty() ? "" : failing_cases[0]["case"].get<std::string>(),
failing_cases.empty() ? "" : failing_cases[0]["case"].get<std::string>());
std::string text;
for (const auto& n : pl.notes)
text += "note: " + n + "\n";
text += summary_text(r, p.value("verbose", false));
const int status = r.status == "pass" ? 0 : r.status == "infra" ? 3 : 1;
return {status, data, text};
}
answer cmd_run(const std::filesystem::path& cwd, const json& p,
const std::function<void(const json&)>& events) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
auto programs = programs_of(*ctx, p);
if (!programs)
return programs.error();
auto sel = selection_of(*ctx, p);
if (!sel)
return sel.error();
auto pl = make_plan(ctx->cfg, ctx->st, *programs, *sel);
if (!pl)
return machine(pl.error());
// `--resume RUN` (0.7.0, M5): the cases RUN judged are not run again, and their results are
// carried into this run, so that a long run (a bench over a matrix) that was interrupted ends
// as one whole run. A case RUN could not start (infra) or never reached runs now.
std::vector<case_result> carried;
std::string resumed_id;
if (auto ref = text_of(p, "resume"); !ref.empty()) {
auto prev = load_run(ctx->st, ref);
if (!prev)
return usage(std::format("no stored run {} to resume", ref));
resumed_id = prev->id;
std::map<std::string, case_result> judged;
for (auto& c : prev->cases)
if (c.status != "infra")
judged[c.program + "::" + c.id] = c;
std::size_t kept = 0;
for (auto& u : pl->units) {
const auto before = u.cases.size();
std::erase_if(u.cases, [&](const unit_case& uc) {
auto it = judged.find(u.program.name + "::" + uc.info.id);
if (it == judged.end())
return false;
carried.push_back(it->second);
return true;
});
if (u.cases.size() != before)
u.all = false;
kept += u.cases.size();
}
std::erase_if(pl->units, [](const unit& u) { return u.cases.empty(); });
pl->selected = kept;
pl->notes.push_back(std::format("resuming run {}: {} case(s) carried, {} to run",
resumed_id, carried.size(), kept));
if (pl->units.empty()) {
json data = {{"status", "pass"},
{"resumed", resumed_id},
{"carried", carried.size()},
{"conclusion",
std::format("run {} has judged every selected case: nothing left to run",
resumed_id)}};
return {0, data, std::format("run {} has judged every selected case\n", resumed_id)};
}
}
if (pl->units.empty()) {
json data = {{"status", "pass"},
{"cases", 0},
{"notes", pl->notes},
{"conclusion", "the selection is empty: nothing ran"}};
return {0, data,
"nothing selected" +
std::string(pl->notes.empty() ? "" : ": " + pl->notes.front()) + "\n"};
}
execute_options o;
o.jobs = p.value("jobs", 0);
if (p.contains("seed") && p["seed"].is_number_unsigned())
o.seed = p["seed"].get<std::uint64_t>();
o.run_under = strings(p, "run_under");
if (auto e = p.find("env"); e != p.end() && e->is_object())
for (auto& item_ : e->items())
if (auto& k = item_.key(); true)
if (auto& v = item_.value(); true)
if (v.is_string())
o.env.emplace_back(k, v.get<std::string>());
o.fail_fast = p.value("fail_fast", false);
o.retries = p.value("retries", -1);
o.set = sel->set;
o.selection = describe_selection(p);
o.monitor = text_of(p, "monitor");
o.group = text_of(p, "group");
o.on_event = events;
// `--coverage`: the run measures the coverage map (docs/coverage.md).
std::map<std::filesystem::path, std::vector<std::string>> coverage_cases;
if (p.value("coverage", false)) {
if (ctx->cfg.coverage.objects.empty())
return usage("--coverage needs [coverage] objects and database in mtest.toml");
o.coverage_dir = ctx->st.dir / "work" / "coverage";
std::error_code ec;
std::filesystem::remove_all(*o.coverage_dir, ec);
o.coverage_strip = gcov_strip(ctx->cfg.root / os::fs::from_utf8(ctx->cfg.coverage.objects));
o.coverage_cases = &coverage_cases;
}
auto r = execute(ctx->cfg, ctx->st, *pl, o);
if (!resumed_id.empty()) {
r.resumed = resumed_id;
for (auto& c : carried)
r.cases.push_back(std::move(c));
r.counts = count(r.cases);
if (r.status == "pass" && std::ranges::any_of(r.cases, [](const case_result& c) {
return failing(c.status) && !c.quarantined;
}))
r.status = "fail";
write_run(ctx->st, r);
}
if (o.coverage_dir) {
auto m = collect_coverage(ctx->cfg, coverage_cases, r.commit);
if (!m)
pl->notes.push_back("coverage: " + m.error());
else {
write_coverage(coverage_file(ctx->st), *m);
std::size_t files = 0;
for (const auto& [_, f] : m->cases)
files = std::max(files, f.size());
pl->notes.push_back(std::format("coverage: {} case(s) mapped, at most {} file(s) each",
m->cases.size(), files));
}
std::error_code ec;
std::filesystem::remove_all(*o.coverage_dir, ec);
}
return finish_run(*ctx, r, p, *pl);
}
// `mtest coverage show|import`: the store's coverage map, or another taken in (a CI artifact).
answer cmd_coverage(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
const auto action = text_of(p, "action");
const auto file = coverage_file(ctx->st);
if (action == "import") {
const auto from = text_of(p, "from");
if (from.empty())
return usage("coverage import needs --from FILE");
auto m = read_coverage(cwd / os::fs::from_utf8(from));
if (!m)
return usage(m.error());
write_coverage(file, *m);
return {0,
{{"cases", m->cases.size()},
{"commit", m->commit},
{"conclusion", std::format("the coverage map of {} ({} case(s)) is the store's",
m->commit.substr(0, 12), m->cases.size())}},
std::format("coverage map of {} taken in: {} case(s)\n", m->commit.substr(0, 12),
m->cases.size())};
}
if (!action.empty() && action != "show")
return usage(std::format("coverage {}: the actions are show and import", action));
auto m = read_coverage(file);
if (!m)
return {0,
{{"conclusion", "the store has no coverage map: affected selection reads "
"programs' sources and cases' artifacts only"}},
"no coverage map\n"};
const bool fresh = fresh_coverage(ctx->st, ctx->cfg.coverage.max_age).has_value();
json cases = json::object();
std::string text = std::format("coverage map of {} at {}{}\n", m->commit.substr(0, 12), m->time,
fresh ? "" : " (older than [coverage] max_age: not read)");
const auto only = strings(p, "case");
for (const auto& [k, files] : m->cases) {
if (!only.empty() &&
!std::ranges::any_of(only, [&](const std::string& g) { return glob_match(g, k); }))
continue;
cases[k] = files;
text += std::format("{}: {} file(s)\n", k, files.size());
}
return {0,
{{"commit", m->commit},
{"time", m->time},
{"fresh", fresh},
{"cases", cases},
{"conclusion",
std::format("{} case(s) mapped at {}{}", m->cases.size(), m->commit.substr(0, 12),
fresh ? "" : "; older than max_age")}},
text};
}
answer cmd_plan(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
auto programs = programs_of(*ctx, p);
if (!programs)
return programs.error();
auto sel = selection_of(*ctx, p);
if (!sel)
return sel.error();
auto pl = make_plan(ctx->cfg, ctx->st, *programs, *sel);
if (!pl)
return machine(pl.error());
json units = json::array();
std::string text;
double expected = 0;
for (const auto& u : pl->units) {
json cases = json::array();
for (const auto& uc : u.cases)
cases.push_back({{"case", uc.info.id}, {"why", uc.why}, {"kind", uc.info.kind}});
units.push_back({{"program", u.program.name},
{"level", u.program.level},
{"all", u.all},
{"expected_ms", u.expected_ms},
{"cases", cases}});
expected += u.expected_ms;
text += std::format("{} ({} case(s), about {:.1f} s)\n", u.program.name, u.cases.size(),
u.expected_ms / 1000);
for (const auto& uc : u.cases)
text += std::format(" {} -- {}\n", uc.info.id, uc.why);
}
for (const auto& n : pl->notes)
text += "note: " + n + "\n";
text += std::format("{} of {} case(s) selected\n", pl->selected, pl->considered);
return {0,
{{"units", units},
{"selected", pl->selected},
{"considered", pl->considered},
{"notes", pl->notes},
{"expected_ms", expected},
{"conclusion",
std::format("{} of {} case(s) in {} program(s), about {:.1f} s of work", pl->selected,
pl->considered, pl->units.size(), expected / 1000)}},
text};
}
// `mtest list --static`: the cases the test files declare, read from their text (the static case
// manifest, lib/src/manifest.cppm), with the attributes mtest.toml and the host state. Nothing is
// built or run; a built program's own listing is the authority.
answer cmd_list_static(const std::filesystem::path& cwd) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
const auto& globs = ctx->cfg.static_globs;
if (globs.empty())
return usage(
"--static reads [static] globs in mtest.toml, or a host's tests; none is stated");
auto literal_prefix = [](std::string_view g) {
const auto wild = g.find_first_of("*?[");
const auto cut = g.substr(0, wild).rfind('/');
return cut == std::string_view::npos ? std::string{} : std::string(g.substr(0, cut + 1));
};
auto first_match = [&](const std::string& rel) -> std::optional<std::string> {
for (const auto& g : globs)
if (g.starts_with('!') && path_glob_match(std::string_view(g).substr(1), rel))
return std::nullopt;
for (const auto& g : globs)
if (!g.starts_with('!') && path_glob_match(g, rel))
return literal_prefix(g);
return std::nullopt;
};
json programs = json::array();
std::size_t total = 0;
std::string text;
std::error_code ec;
std::vector<std::filesystem::path> files;
for (std::filesystem::recursive_directory_iterator it(ctx->cfg.root, ec), end; it != end;
it.increment(ec)) {
const auto rel =
os::fs::generic_utf8(std::filesystem::relative(it->path(), ctx->cfg.root, ec));
const auto top = rel.substr(0, rel.find('/'));
if (top == ".git" || top == ".mtest" || top == "target") {
if (it->is_directory())
it.disable_recursion_pending();
continue;
}
if (it->is_regular_file(ec))
files.push_back(it->path());
}
std::ranges::sort(files);
auto read_file = [](const std::filesystem::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string((std::istreambuf_iterator<char>(in)), {});
};
// The suite types the project's C++ sources declare: a type its tests share is usually
// written in a module or a header beside them, not in a file the globs name.
std::vector<std::string> sources;
for (const auto& file : files) {
static const std::set<std::string> cxx{".cpp", ".cc", ".cxx", ".cppm", ".ixx",
".mpp", ".h", ".hh", ".hpp", ".hxx"};
if (cxx.contains(file.extension().string()))
sources.push_back(read_file(file));
}
const auto types = manifest::types_of(sources);
for (const auto& file : files) {
const auto rel = os::fs::generic_utf8(std::filesystem::relative(file, ctx->cfg.root, ec));
const auto base = first_match(rel);
if (!base)
continue;
const auto source = read_file(file);
auto name = rel.substr(base->size());
if (const auto dot = name.rfind('.');
dot != std::string::npos && name.find('/', dot) == std::string::npos)
name.erase(dot);
json cases = json::array();
program_spec program;
program.name = name;
program.kind = layout_kind(rel);
for (const auto& sc : manifest::scan(source, types)) {
case_info ci;
ci.id = sc.id;
ci.name = sc.name;
ci.file = rel;
ci.line = sc.line;
ci.kind = sc.kind;
ci.tags = sc.tags;
ci.resources = sc.resources;
ci.clauses = sc.clauses;
ci.artifacts = sc.artifacts;
apply_attributes(ctx->cfg, program, ci);
cases.push_back({{"case", ci.id},
{"name", ci.name},
{"file", ci.file},
{"line", ci.line},
{"kind", ci.kind},
{"tags", ci.tags},
{"resources", ci.resources},
{"clauses", ci.clauses},
{"artifacts", ci.artifacts}});
text += std::format("{}::{} {}:{}\n", name, ci.id, rel, ci.line);
}
total += cases.size();
programs.push_back({{"program", name}, {"file", rel}, {"cases", cases}});
}
return {0,
{{"programs", programs},
{"cases", total},
{"static", true},
{"conclusion",
std::format("{} case(s) declared in {} test file(s), read without building", total,
programs.size())}},
text +
std::format("{} case(s) in {} file(s), read statically\n", total, programs.size())};
}
answer cmd_list(const std::filesystem::path& cwd, const json& p) {
if (p.value("static", false))
return cmd_list_static(cwd);
json q = p;
if (!q.contains("set"))
q.erase("set");
return cmd_plan(cwd, q);
}
std::expected<run_record, answer> run_named(const context& ctx, const json& p,
const char* key = "run") {
const auto id = text_of(p, key, "last");
auto r = load_run(ctx.st, id);
if (!r)
return std::unexpected(usage(
std::format("no stored run {}{}", id, id == "last" ? " (run `mtest run` first)" : "")));
return *r;
}
answer cmd_status(const std::filesystem::path& cwd, const json&) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
json active = json::array();
std::string text;
for (auto& [id, prog] : active_runs(ctx->st)) {
active.push_back(prog);
text += std::format("running {}: {} of {} program(s) done, {} failed\n", id,
prog.value("done", 0), prog.value("total", 0), prog.value("failed", 0));
}
json last = nullptr;
if (auto r = load_run(ctx->st, "last")) {
last = to_json(*r);
text += std::format("last run {}: {} ({} case(s), {:.1f} s)\n", r->id, r->status,
r->cases.size(), r->ms / 1000);
}
return {0,
{{"active", active},
{"last", last},
{"conclusion", active.empty()
? (last.is_null() ? std::string("no run is stored")
: std::format("nothing runs; the last run {}",
last["status"].get<std::string>()))
: std::format("{} run(s) in progress", active.size())}},
text};
}
answer cmd_cancel(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
auto active = active_runs(ctx->st);
auto id = text_of(p, "run");
if (id.empty()) {
if (active.empty())
return usage("no run is in progress");
id = active.back().first;
}
request_cancel(ctx->st, id);
return {0,
{{"run", id},
{"conclusion", std::format("run {} stops after the programs now running", id)}},
std::format("cancelling {}: it stops after the programs now running\n", id)};
}
// The words of a list given as an array or as one comma-separated string.
std::vector<std::string> words_of(const json& p, const char* key) {
std::vector<std::string> out;
for (const auto& w : strings(p, key))
for (auto part : std::views::split(std::string_view(w), ','))
if (auto s = std::string(part.begin(), part.end()); !s.empty())
out.push_back(s);
if (out.empty())
if (auto t = text_of(p, key); !t.empty())
for (auto part : std::views::split(std::string_view(t), ','))
out.emplace_back(part.begin(), part.end());
return out;
}
report_options report_options_of(const context& ctx, const json& p) {
report_options o;
o.sections = words_of(p, "sections");
if (o.sections.empty())
o.sections = ctx.cfg.report.sections;
o.scope = text_of(p, "scope", ctx.cfg.report.scope);
o.top = p.value("top", ctx.cfg.report.top);
o.max_nodes = p.value("max_nodes", ctx.cfg.report.max_nodes);
o.title = text_of(p, "title");
return o;
}
// The runs a report is of: a group's (every stored run of it), a list, or one.
std::expected<std::vector<run_record>, answer> runs_of(const context& ctx, const json& p) {
std::vector<run_record> out;
if (auto g = text_of(p, "group"); !g.empty()) {
for (const auto& r : runs(ctx.st))
if (r.group == g)
if (auto full = load_run(ctx.st, r.id))
out.push_back(std::move(*full));
if (out.empty())
return std::unexpected(usage(std::format("no stored run of group {}", g)));
return out;
}
if (auto list = words_of(p, "runs"); !list.empty()) {
for (const auto& id : list) {
auto r = load_run(ctx.st, id);
if (!r)
return std::unexpected(usage(std::format("no stored run {}", id)));
out.push_back(std::move(*r));
}
return out;
}
auto r = run_named(ctx, p);
if (!r)
return std::unexpected(r.error());
out.push_back(std::move(*r));
return out;
}
answer cmd_report(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
const auto format = text_of(p, "format", "text");
if (format == "md") {
auto all = runs_of(*ctx, p);
if (!all)
return all.error();
auto body = markdown_report(ctx->st, *all, report_options_of(*ctx, p));
json data = {{"runs", all->size()},
{"conclusion", std::format("a report of {} run(s)", all->size())}};
if (auto out = text_of(p, "out"); !out.empty()) {
(void)os::fs::write(os::fs::from_utf8(out), body);
body = std::format("wrote {}\n", out);
}
return {0, data, body};
}
auto r = run_named(*ctx, p);
if (!r)
return r.error();
std::string body = format == "junit" ? junit_xml(*r)
: format == "html" ? html_page(*r)
: format == "json" ? std::string{}
: summary_text(*r, true);
json data = to_json(*r);
data["cases"] = json::array();
for (const auto& c : r->cases)
data["cases"].push_back(to_json(c));
data["conclusion"] = std::format("run {} {}", r->id, r->status);
if (format == "json")
body = dumped(data, 2) + "\n";
if (auto out = text_of(p, "out"); !out.empty()) {
(void)os::fs::write(os::fs::from_utf8(out), body);
body = std::format("wrote {}\n", out);
}
return {0, data, body};
}
answer cmd_diff(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
json q = p;
if (!q.contains("before"))
q["before"] = "last-1";
if (!q.contains("after"))
q["after"] = "last";
auto a = run_named(*ctx, q, "before");
if (!a)
return a.error();
auto b = run_named(*ctx, q, "after");
if (!b)
return b.error();
auto d = diff(*a, *b, p.value("ratio", 1.25));
std::string text = d["conclusion"].get<std::string>() + "\n";
for (const auto& x : d["newly_failing"])
text += std::format(" newly failing {}::{}\n", x["program"].get<std::string>(),
x["case"].get<std::string>());
for (const auto& x : d["fixed"])
text += std::format(" fixed {}::{}\n", x["program"].get<std::string>(),
x["case"].get<std::string>());
return {0, d, text};
}
answer cmd_explain(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
auto r = run_named(*ctx, p);
if (!r)
return r.error();
auto ref = text_of(p, "case");
if (ref.empty()) {
for (const auto& c : r->cases)
if (failing(c.status)) {
ref = c.program + "::" + c.id;
break;
}
if (ref.empty())
return {0,
{{"run", r->id},
{"cases", json::array()},
{"conclusion", std::format("nothing failed in run {}", r->id)}},
std::format("nothing failed in run {}\n", r->id)};
}
auto e = explain(ctx->st, *r, ref);
if (!e)
return usage(e.error());
std::string text;
for (const auto& c : (*e)["cases"]) {
text += std::format("{}::{} {} ({})\n", c["program"].get<std::string>(),
c["case"].get<std::string>(), c["status"].get<std::string>(),
c["kind_of_failure"].get<std::string>());
for (std::size_t i = 0; i < c["why"].size(); ++i) {
text +=
std::format(" {}{}\n",
i < c["where"].size() ? c["where"][i].get<std::string>() + ": " : "",
c["why"][i]["message"].get<std::string>());
if (c["why"][i].contains("expected"))
text += std::format(" expected {}\n actual {}\n",
c["why"][i]["expected"].get<std::string>(),
c["why"][i]["actual"].get<std::string>());
}
if (c.contains("output") && !c["output"]["err_tail"].get<std::string>().empty())
text += " error output (end):\n" + c["output"]["err_tail"].get<std::string>() + "\n";
if (c.contains("timeout"))
text += timeout_text(timeout_info_from(c["timeout"]), " ", 400);
if (c.contains("diagnosis"))
text += " diagnosis: " + c["diagnosis"].get<std::string>() + "\n";
text += " again: " + c["again"].get<std::string>() + "\n";
}
return {0, *e, text};
}
answer cmd_history(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
auto id = text_of(p, "case");
if (id.empty())
return usage("history needs --case <id>");
std::string program;
if (auto at = id.find("::"); at != std::string::npos) {
program = id.substr(0, at);
id = id.substr(at + 2);
}
if (auto pr = text_of(p, "program"); !pr.empty())
program = pr;
auto h = history(ctx->st, program, id, std::size_t(p.value("limit", 20)));
std::string text = h["conclusion"].get<std::string>() + "\n";
for (const auto& x : h["items"])
text += std::format(" {} {} {:.0f} ms\n", x["run"].get<std::string>(),
x["status"].get<std::string>(), x["ms"].get<double>());
return {0, h, text};
}
// A declarative query of the stored cases: each parameter narrows the rows.
answer cmd_query(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
const auto statuses = strings(p, "status");
const auto kinds = strings(p, "kind");
const auto programs = strings(p, "program");
const auto cases = strings(p, "case");
const auto tags = strings(p, "tag");
const int days = p.value("days", 0);
const std::size_t limit = std::size_t(p.value("limit", 200));
const std::size_t last_runs = std::size_t(p.value("runs", 0));
const auto cutoff = days > 0 ? std::format("{:%Y%m%d}", std::chrono::floor<std::chrono::days>(
std::chrono::system_clock::now() -
std::chrono::days{days}))
: std::string{};
auto all = runs(ctx->st);
json rows = json::array();
std::size_t scanned = 0;
for (std::size_t i = all.size(); i-- > 0 && rows.size() < limit;) {
if (!cutoff.empty() && all[i].id.substr(0, 8) < cutoff)
break;
if (last_runs && scanned++ >= last_runs)
break;
auto r = load_run(ctx->st, all[i].id);
if (!r)
continue;
for (const auto& c : r->cases) {
if (!statuses.empty() && std::ranges::find(statuses, c.status) == statuses.end())
continue;
if (!kinds.empty() && std::ranges::find(kinds, c.kind) == kinds.end())
continue;
if (!programs.empty() && !std::ranges::any_of(programs, [&](const std::string& g) {
return glob_match(g, c.program);
}))
continue;
if (!cases.empty() && !std::ranges::any_of(cases, [&](const std::string& g) {
return glob_match(g, c.id);
}))
continue;
if (!tags.empty() && !std::ranges::any_of(tags, [&](const std::string& t) {
return std::ranges::find(c.tags, t) != c.tags.end();
}))
continue;
json row = to_json(c);
row["run"] = r->id;
row["commit"] = r->commit;
rows.push_back(std::move(row));
if (rows.size() >= limit)
break;
}
}
std::string text;
for (const auto& row : rows)
text += std::format("{} {}::{} {} {:.0f} ms\n", row["run"].get<std::string>(),
row["program"].get<std::string>(), row["id"].get<std::string>(),
row["status"].get<std::string>(), row["ms"].get<double>());
return {0, {{"rows", rows}, {"conclusion", std::format("{} row(s)", rows.size())}}, text};
}
answer cmd_analyze(const std::filesystem::path& cwd, const json& p) {
auto ctx = open(cwd);
if (!ctx)
return ctx.error();
const auto metric = text_of(p, "metric", "durations");
json data;
if (metric == "flaky") {
data = flaky(ctx->st, std::size_t(p.value("runs", 30)));
} else if (metric == "trend") {
data = trend(ctx->st, std::size_t(p.value("runs", 20)), strings(p, "case"));
} else {
auto r = run_named(*ctx, p);
if (!r)
return r.error();
if (metric == "hot")
data = hot(*r, std::size_t(p.value("top", 10)));
else if (metric == "durations")
data = durations(*r);
else if (metric == "path")
data = critical_path(*r);
else if (metric == "failures")
data = failures(*r);
else if (metric == "bench") {
json items = json::array();
for (const auto& v :
judge_bench(*r, bench_baseline(ctx->st, *r, ctx->cfg.bench), ctx->cfg.bench))
items.push_back({{"program", v.program},
{"case", v.id},
{"metric", v.metric},
{"verdict", v.verdict},
{"ratio", v.ratio},
{"spread", v.spread},
{"reason", v.reason},
{"repeatable", v.repeatable}});
const auto bad =
std::ranges::count_if(items, [](const json& x) { return x["verdict"] != "pass"; });
data = {{"run", r->id},
{"items", items},
{"conclusion",
std::format("{} of {} measurement(s) do not pass", bad, items.size())}};
} else if (metric == "cost") {
double cpu = 0;
for (const auto& pr : r->programs)
cpu += pr.ms;
data = {{"run", r->id},
{"program_ms", cpu},
{"wall_ms", r->ms},
{"jobs", r->jobs},
{"conclusion", std::format("{:.1f} program-minutes over {:.1f} wall-minutes",
cpu / 60000, r->ms / 60000)}};
} else {
return usage(std::format("no metric {}: hot, durations, path, failures, flaky, bench, "
"trend, cost",
metric));
}
}
std::string text = data["conclusion"].get<std::string>() + "\n";
if (data.contains("items"))
for (const auto& x : data["items"])
text += " " + dumped(x) + "\n";
if (data.contains("groups"))
for (const auto& g : data["groups"])
text += std::format(" {} x {}\n", g["count"].get<std::size_t>(),
g["message"].get<std::string>());
return {0, data, text};
}
// The graph of a stored run (`mtest graph --run <id>`): its work and what each waited for, the
// critical path marked.
answer run_graph(const context& ctx, const json& p) {
auto r = run_named(ctx, p);
if (!r)
return r.error();
const auto g = dag_of(*r);
const auto format = text_of(p, "format", "json");
const int max_nodes = p.value("max_nodes", ctx.cfg.report.max_nodes);
json nodes = json::array(), edges = json::array();