-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathexecute.cppm
More file actions
1141 lines (1037 loc) · 51.3 KB
/
Copy pathexecute.cppm
File metadata and controls
1141 lines (1037 loc) · 51.3 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
// mcpp.build.execute — drives a prepared BuildContext: ninja execution,
// build cache + fast-path rebuilds, and the run/test/clean pipelines.
// Bodies moved verbatim from the CLI layer. Zero behavior change.
module;
#include <cstdio>
#include <cstdlib>
export module mcpp.build.execute;
import std;
import mcpp.build.prepare;
import mcpp.diag;
import mcpp.build.plan;
import mcpp.build.backend;
import mcpp.build.ninja;
import mcpp.bmi_cache;
import mcpp.manifest;
import mcpp.modgraph.scanner;
import mcpp.toolchain.stdmod;
import mcpp.xlings;
import mcpp.platform;
import mcpp.fetcher.progress;
import mcpp.project;
import mcpp.ui;
namespace mcpp::build {
// ─── P0: build cache for fast-path rebuilds ─────────────────────────
constexpr std::string_view kBuildCacheFile = "target/.build_cache";
constexpr int kBuildCacheMaxEntries = 4; // P3: LRU capacity
// P3: one entry per (target, fingerprint) pair.
struct BuildCacheEntry {
std::string targetTriple; // "" for default target
std::string outputDir;
std::string ninjaProgram;
std::string fingerprint; // outputDir basename
std::string runtimeEnvKey; // "-" means intentionally empty; "" means old cache
std::string runtimeEnvValue;
// mcpp#225 (E2): resolved binary run-targets, cached alongside the
// fingerprint so `mcpp run` can skip prepare_build (toolchain
// resolution + modgraph scan) on a cache hit — see build_run_target's
// fast path. name -> exe path relative to outputDir. Caches written
// before this field existed leave it empty, which the run fast-path
// treats as a miss (falls back to prepare_build once, never crashes).
std::vector<std::pair<std::string, std::string>> runTargets;
// The process environment needed to exec those targets (e.g.
// LD_LIBRARY_PATH for dep .so's not covered by the exe's own RUNPATH),
// cached the same way as runtimeEnvKey/Value above but for RUNNING the
// binary rather than invoking the toolchain. "" (default-constructed)
// means old cache / not yet resolved — the run fast-path exec's with no
// extra env in that case, matching prepare_build's behavior when
// plan.runtimeLibraryDirs is empty.
std::string runEnvKey;
std::string runEnvValue;
};
std::vector<BuildCacheEntry> read_build_cache(const std::filesystem::path& projectRoot) {
auto path = projectRoot / kBuildCacheFile;
std::ifstream f(path);
if (!f) return {};
std::string firstLine;
if (!std::getline(f, firstLine) || firstLine.empty()) return {};
// Detect legacy format (first line is an absolute path, not "[target=...]").
if (firstLine[0] != '[') {
// Legacy 4-line format: outputDir, ninjaProgram, target, fingerprint.
BuildCacheEntry e;
e.outputDir = firstLine;
std::getline(f, e.ninjaProgram);
std::getline(f, e.targetTriple);
std::getline(f, e.fingerprint);
if (e.outputDir.empty() || e.ninjaProgram.empty()) return {};
return {e};
}
// P3 multi-entry format: sections of [target=<triple>] + 3 mandatory
// lines, plus optional runtime-env lines added after toolenv moved out of
// build.ninja. Old cache entries omit them and are treated as stale.
std::vector<BuildCacheEntry> entries;
std::string line = firstLine;
while (true) {
// Parse [target=<triple>]
if (line.size() < 9 || !line.starts_with("[target=") || line.back() != ']')
break;
BuildCacheEntry e;
e.targetTriple = line.substr(8, line.size() - 9);
if (!std::getline(f, e.outputDir) || e.outputDir.empty()) break;
if (!std::getline(f, e.ninjaProgram) || e.ninjaProgram.empty()) break;
std::getline(f, e.fingerprint);
bool haveNextLine = static_cast<bool>(std::getline(f, line));
if (haveNextLine && !line.starts_with("[target=")
&& !line.starts_with("runTargets=")) {
e.runtimeEnvKey = line;
std::getline(f, e.runtimeEnvValue);
haveNextLine = static_cast<bool>(std::getline(f, line));
}
// mcpp#225 (E2): optional runTargets block. Absent on caches written
// before this field existed (or truncated/corrupt mid-block) — in
// either case e.runTargets stays empty, which the run fast-path
// treats as a miss, never a crash.
if (haveNextLine && line.starts_with("runTargets=")) {
std::size_t n = 0;
try { n = std::stoul(line.substr(11)); } catch (...) { n = 0; }
for (std::size_t i = 0; i < n && std::getline(f, line); ++i) {
auto tab = line.find('\t');
if (tab == std::string::npos) continue;
e.runTargets.emplace_back(line.substr(0, tab), line.substr(tab + 1));
}
haveNextLine = static_cast<bool>(std::getline(f, line));
}
// mcpp#225 (E2): optional run-env block (the process env needed to
// exec a cached run-target, e.g. LD_LIBRARY_PATH). Same back-compat
// contract as runTargets above.
if (haveNextLine && line.starts_with("runEnv=")) {
e.runEnvKey = line.substr(7);
std::getline(f, e.runEnvValue);
haveNextLine = static_cast<bool>(std::getline(f, line));
}
entries.push_back(std::move(e));
if (!haveNextLine || line.empty()) break;
}
return entries;
}
void write_build_cache(const std::filesystem::path& projectRoot,
const std::filesystem::path& outputDir,
const std::string& ninjaProgram,
const std::string& targetTriple,
const std::string& fingerprintHex = "",
const std::string& runtimeEnvKey = "-",
const std::string& runtimeEnvValue = "",
std::vector<std::pair<std::string, std::string>> runTargets = {},
const std::string& runEnvKey = "",
const std::string& runEnvValue = "") {
auto path = projectRoot / kBuildCacheFile;
auto entries = read_build_cache(projectRoot);
// Remove existing entry for this target (will be re-added at front).
std::erase_if(entries, [&](const BuildCacheEntry& e) {
return e.targetTriple == targetTriple;
});
// Insert at front (MRU).
BuildCacheEntry newEntry{targetTriple, outputDir.string(), ninjaProgram, fingerprintHex,
runtimeEnvKey, runtimeEnvValue, std::move(runTargets),
runEnvKey, runEnvValue};
entries.insert(entries.begin(), std::move(newEntry));
// Trim to LRU capacity.
if ((int)entries.size() > kBuildCacheMaxEntries)
entries.resize(kBuildCacheMaxEntries);
// Write P3 format.
std::error_code ec;
std::filesystem::create_directories(path.parent_path(), ec);
std::ofstream f(path, std::ios::trunc);
if (!f) return;
for (auto& e : entries) {
f << "[target=" << e.targetTriple << "]\n";
f << e.outputDir << '\n';
f << e.ninjaProgram << '\n';
f << e.fingerprint << '\n';
f << (e.runtimeEnvKey.empty() ? "-" : e.runtimeEnvKey) << '\n';
f << e.runtimeEnvValue << '\n';
// mcpp#225 (E2): run-targets + their exec env, always written (even
// when empty) so a reader never has to guess whether a missing
// block means "no targets" vs "cache predates this field" — the
// count-prefixed block is unambiguous either way, and back-compat
// for OLD caches (no such block at all) is handled on the read side.
f << "runTargets=" << e.runTargets.size() << '\n';
for (auto& [name, exe] : e.runTargets) f << name << '\t' << exe << '\n';
f << "runEnv=" << e.runEnvKey << '\n';
f << e.runEnvValue << '\n';
}
}
std::vector<std::string> read_ninja_command_prefixes(const std::filesystem::path& ninjaPath) {
std::ifstream f(ninjaPath);
if (!f) return {};
std::vector<std::string> prefixes;
std::string line;
while (std::getline(f, line)) {
auto eq = line.find('=');
if (eq == std::string::npos) continue;
auto key = line.substr(0, eq);
while (!key.empty() && std::isspace(static_cast<unsigned char>(key.back())))
key.pop_back();
// `mcpp` drives the dyndep + stage_file rules; treating it as a command
// prefix filters the echoed command line while keeping the diagnostic
// mcpp itself printed (#311).
if (key != "cxx" && key != "cc" && key != "ar" && key != "scan_deps"
&& key != "mcpp")
continue;
std::string value = line.substr(eq + 1);
while (!value.empty() && std::isspace(static_cast<unsigned char>(value.front())))
value.erase(value.begin());
while (!value.empty() && std::isspace(static_cast<unsigned char>(value.back())))
value.pop_back();
if (!value.empty())
prefixes.push_back(std::move(value));
}
return prefixes;
}
bool is_stale_ninja_failure(std::string_view output) {
return output.find("loading 'build.ninja'") != std::string_view::npos
|| output.find("loading build.ninja") != std::string_view::npos
|| output.find("unknown target") != std::string_view::npos
|| output.find("manifest 'build.ninja' still dirty") != std::string_view::npos
// A cached build.ninja can reference an input (e.g. a dependency
// source under the registry) that moved or was reinstalled since the
// graph was generated — the build fingerprint does not yet cover
// registry dep state, so the stale graph is reused. Ninja then aborts
// with this signature. Treat it as stale → drop to a full regen
// instead of hard-failing and forcing the user to `mcpp clean`.
|| output.find("missing and no known rule to make") != std::string_view::npos;
}
// mcpp#225 (E2): the (name, exe-path-relative-to-outputDir) pairs for every
// binary link unit in a resolved plan, cached alongside the build
// fingerprint so `mcpp run` can locate an executable without re-running
// prepare_build (see BuildCacheEntry::runTargets / try_fast_run below).
// TestBinary/library link units never run via `mcpp run`, so only Binary
// link units are collected.
std::vector<std::pair<std::string, std::string>>
compute_run_targets(const mcpp::build::BuildPlan& plan) {
std::vector<std::pair<std::string, std::string>> out;
for (auto& lu : plan.linkUnits) {
if (lu.kind != mcpp::build::LinkUnit::Binary) continue;
out.emplace_back(lu.targetName, lu.output.generic_string());
}
return out;
}
// mcpp#225 (E2): the process env needed to exec a run-target (e.g.
// LD_LIBRARY_PATH for dep .so's not covered by the exe's own RUNPATH).
// Shared between build_run_target's normal (prepare_build) path and its
// cached fast path so both derive the same env from the same source.
std::pair<std::string, std::string>
compute_run_env(const mcpp::build::BuildPlan& plan) {
auto key = mcpp::platform::env::runtime_library_path_key();
auto value = mcpp::platform::env::prepend_path_list(key, plan.runtimeLibraryDirs);
if (key.empty() || value.empty()) return {"", ""};
return {key, value};
}
// Compile a prepared BuildContext. Shared between `mcpp build` and `mcpp run`
// so the latter doesn't call prepare_build twice (and re-print the toolchain
// resolution banner).
export int run_build_plan(BuildContext& ctx, bool verbose, bool no_cache,
std::string_view targetOverride = "") {
if (no_cache) {
std::error_code ec;
std::filesystem::remove_all(ctx.outputDir, ec);
}
auto be = mcpp::build::make_ninja_backend();
// M5.0: print "Inferred" banner when defaults / target inference fired.
for (auto& note : ctx.manifest.inferredNotes) {
mcpp::ui::status("Inferred", note);
}
// Announce the package being built (and any deps).
// Deps that hit the BMI cache get "Cached" instead of "Compiling".
std::set<std::string> cachedNames;
for (auto& label : ctx.cachedDepLabels) {
auto sp = label.find(' ');
cachedNames.insert(sp == std::string::npos ? label : label.substr(0, sp));
}
std::set<std::string> announced;
announced.insert(ctx.manifest.package.name);
mcpp::ui::status("Compiling",
std::format("{} v{} (.)",
ctx.manifest.package.name, ctx.manifest.package.version));
for (auto& [name, spec] : ctx.manifest.dependencies) {
if (announced.contains(name)) continue;
announced.insert(name);
std::string ver = spec.isPath() ? "(path)" : std::string("v") + spec.version;
const char* verb = cachedNames.contains(name) ? "Cached" : "Compiling";
mcpp::ui::status(verb, std::format("{} {}", name, ver));
}
mcpp::build::BuildOptions opts;
opts.verbose = verbose;
auto r = be->build(ctx.plan, opts);
if (!r) {
std::fflush(stdout);
mcpp::ui::error(r.error().message);
if (!r.error().diagnosticOutput.empty()) {
std::fputs(r.error().diagnosticOutput.c_str(), stderr);
if (r.error().diagnosticOutput.back() != '\n')
std::fputc('\n', stderr);
}
return 1;
}
// M3.2: populate BMI cache for deps that did NOT hit cache.
for (auto& task : ctx.depsToPopulate) {
auto pr = mcpp::bmi_cache::populate_from(task.key, ctx.outputDir, task.artifacts);
if (!pr) {
mcpp::ui::warning(std::format(
"bmi cache populate failed for {}@{}: {}",
task.key.packageName, task.key.version, pr.error()));
}
}
// P1.5: warn if fingerprint changed from last build (explains full rebuild).
{
auto entries = read_build_cache(ctx.projectRoot);
for (auto& e : entries) {
if (e.targetTriple == targetOverride && !e.fingerprint.empty()) {
auto newFp = ctx.outputDir.filename().string();
if (e.fingerprint != newFp) {
mcpp::ui::warning(std::format(
"fingerprint changed ({} → {}), full rebuild",
e.fingerprint, newFp));
}
break;
}
}
}
// P0: save build cache for fast-path on next invocation.
if (!no_cache && !r->ninjaProgram.empty()) {
auto fpHex = ctx.outputDir.filename().string();
auto runTargets = compute_run_targets(ctx.plan);
auto [runEnvKey, runEnvValue] = compute_run_env(ctx.plan);
write_build_cache(ctx.projectRoot, ctx.outputDir, r->ninjaProgram,
std::string(targetOverride), fpHex,
r->runtimeEnvKey.empty() ? "-" : r->runtimeEnvKey,
r->runtimeEnvValue,
std::move(runTargets), runEnvKey, runEnvValue);
}
// The one place the --strict policy is settled. Degradations reported by
// the backend (e.g. a toolchain/platform combination that cannot emit a
// depfile, #257) are discovered during emission, so this has to come
// after the build rather than at the end of prepare_build. Without this
// call the whole diag channel would report and then be ignored — the
// exact failure mode it exists to prevent.
if (!mcpp::diag::flush(ctx.strict)) return 1;
mcpp::ui::finished("release", r->elapsed);
return 0;
}
// ─── P0 fast-path: skip prepare_build when build.ninja is fresh ──────
//
// On a successful build, we write `target/.build_cache` containing the
// outputDir path. On the next invocation, if build.ninja in that dir
// is newer than all source files and mcpp.toml, we invoke ninja directly
// without re-running the scanner, make_plan, or emit phases.
//
// This reduces no-change builds from ~10s to <0.5s.
// mcpp#225: is any tracked source file under `projectRoot` newer than
// `ninjaTime`? Shared by try_fast_build's and try_fast_run's freshness
// gates. Uses expand_glob's bounded ("src" prefix) + vcs/build-dir-excluded
// walk instead of a hand-rolled recursive_directory_iterator — the OLD
// staleness check here walked ALL of src/ unfiltered (harmless when src/ is
// the whole tree, but wasteful/wrong the moment a huge unrelated directory
// lives elsewhere under the project root and gets swept in by some other
// caller's broader glob; and it's the same choke-point fix as expand_glob
// itself, see scanner.cppm).
bool sources_newer_than(const std::filesystem::path& projectRoot,
std::filesystem::file_time_type ninjaTime) {
std::error_code ec;
// The root build.mcpp is a build input too — its directives shape
// build.ninja (flags, generated/selected sources). A changed program must
// abandon the fast path and fall through to prepare_build, where the
// declared-input cache decides whether it actually re-runs. Without this
// the documented "re-runs when the build.mcpp source itself changes" was
// unreachable behind a fresh build.ninja.
if (auto bp = projectRoot / "build.mcpp"; std::filesystem::exists(bp, ec)) {
auto bt = std::filesystem::last_write_time(bp, ec);
if (ec || bt > ninjaTime) return true;
}
for (auto& f : mcpp::modgraph::expand_glob(projectRoot, "src/**/*")) {
auto ext = f.extension().string();
if (ext != ".cppm" && ext != ".cpp" && ext != ".cc" &&
ext != ".cxx" && ext != ".c" && ext != ".h" && ext != ".hpp")
continue;
auto ft = std::filesystem::last_write_time(f, ec);
if (ec || ft > ninjaTime) return true;
}
return false;
}
// mcpp#225: run ninja quietly against an already-verified-fresh build.ninja.
// Shared by try_fast_build (which just reports "Finished" on success) and
// try_fast_run (which goes on to locate + exec a binary). Returns nullopt
// when ninja's failure looks like a stale-graph signature — the caller
// should abandon the fast path and fall back to a full prepare_build — or
// an exit code otherwise (0 success; 1 hard failure, diagnostics already
// printed to stderr).
std::optional<int> run_ninja_fast(const std::string& ninjaProgram,
const std::filesystem::path& outputDir,
const std::filesystem::path& ninjaPath,
bool verbose,
const std::string& runtimeEnvKey,
const std::string& runtimeEnvValue,
std::chrono::milliseconds* elapsedOut = nullptr) {
std::vector<std::string> argv{ninjaProgram};
if (!verbose) argv.push_back("--quiet");
argv.push_back("-C");
argv.push_back(outputDir.string());
if (verbose) argv.push_back("-v");
std::vector<std::pair<std::string, std::string>> childEnv;
if (runtimeEnvKey == "@env") {
// Multi-var encoding (MSVC INCLUDE/LIB/PATH/VSLANG + optional runtime
// pair): \x1f-separated k=v records in the single value slot.
std::string_view rest = runtimeEnvValue;
while (!rest.empty()) {
auto sep = rest.find('\x1f');
auto rec = rest.substr(0, sep);
if (auto eq = rec.find('='); eq != std::string_view::npos && eq > 0)
childEnv.emplace_back(std::string(rec.substr(0, eq)),
std::string(rec.substr(eq + 1)));
if (sep == std::string_view::npos) break;
rest.remove_prefix(sep + 1);
}
} else if (runtimeEnvKey != "-" && !runtimeEnvValue.empty()) {
childEnv.emplace_back(runtimeEnvKey, runtimeEnvValue);
}
auto t0 = std::chrono::steady_clock::now();
// capture_exec merges stderr into the captured output (replacing `2>&1`),
// so is_stale_ninja_failure / filter_ninja_output still see ninja errors.
auto r = mcpp::platform::process::capture_exec(argv, childEnv);
std::string out = r.output;
int status = r.exit_code;
if (status != 0) {
if (is_stale_ninja_failure(out))
return std::nullopt;
std::fflush(stdout);
mcpp::ui::error("build failed");
auto prefixes = read_ninja_command_prefixes(ninjaPath);
auto diagnostics = verbose ? out : mcpp::build::filter_ninja_output(out, prefixes);
if (!diagnostics.empty()) {
std::fputs(diagnostics.c_str(), stderr);
if (diagnostics.back() != '\n')
std::fputc('\n', stderr);
}
return 1;
}
if (verbose && !out.empty())
std::fputs(out.c_str(), stdout);
if (elapsedOut) {
*elapsedOut = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0);
}
return 0;
}
// Try to fast-path: if build.ninja is newer than all inputs, just run ninja.
// Returns exit code on fast-path, or nullopt if full rebuild needed.
export std::optional<int> try_fast_build(const std::filesystem::path& projectRoot,
bool verbose, bool no_cache,
std::string_view currentTarget = "") {
if (no_cache) return std::nullopt;
// P3: read multi-entry cache and find entry matching currentTarget.
auto entries = read_build_cache(projectRoot);
const BuildCacheEntry* match = nullptr;
for (auto& e : entries) {
if (e.targetTriple == currentTarget) { match = &e; break; }
}
if (!match) return std::nullopt;
auto outputDirStr = match->outputDir;
auto ninjaProgram = match->ninjaProgram;
// Legacy caches stored a shell-quoted path; execvp needs the raw path.
if (ninjaProgram.size() >= 2 && ninjaProgram.front() == '\''
&& ninjaProgram.back() == '\'')
ninjaProgram = ninjaProgram.substr(1, ninjaProgram.size() - 2);
auto cachedFingerprint = match->fingerprint;
auto runtimeEnvKey = match->runtimeEnvKey;
auto runtimeEnvValue = match->runtimeEnvValue;
if (runtimeEnvKey.empty())
return std::nullopt; // old cache entry; regenerate build.ninja once
// P1: verify fingerprint matches the outputDir basename.
if (!cachedFingerprint.empty()) {
auto dirBasename = std::filesystem::path(outputDirStr).filename().string();
if (dirBasename != cachedFingerprint) {
return std::nullopt;
}
}
std::error_code ec;
std::filesystem::path outputDir(outputDirStr);
auto ninjaPath = outputDir / "build.ninja";
if (!std::filesystem::exists(ninjaPath, ec)) return std::nullopt;
auto ninjaTime = std::filesystem::last_write_time(ninjaPath, ec);
if (ec) return std::nullopt;
// Check mcpp.toml
auto tomlPath = projectRoot / "mcpp.toml";
auto tomlTime = std::filesystem::last_write_time(tomlPath, ec);
if (ec || tomlTime > ninjaTime) return std::nullopt;
// mcpp#225: bounded + vcs/build-dir-excluded walk (see sources_newer_than)
// instead of a hand-rolled recursive_directory_iterator over src/.
if (sources_newer_than(projectRoot, ninjaTime)) return std::nullopt;
// All inputs are older than build.ninja → fast-path: just run ninja.
std::chrono::milliseconds elapsed{};
auto rc = run_ninja_fast(ninjaProgram, outputDir, ninjaPath, verbose,
runtimeEnvKey, runtimeEnvValue, &elapsed);
if (!rc) return std::nullopt;
if (*rc != 0) return rc;
mcpp::ui::finished("release", elapsed);
return 0;
}
// mcpp#225 (E2): `mcpp run`'s fast path. Mirrors try_fast_build's
// fingerprint/freshness gate against the SAME cache entry `mcpp build`
// wrote (targetTriple == "" — `mcpp run` never takes a --target flag), then
// on a hit runs ninja and execs the cached run-target directly — skipping
// prepare_build (toolchain resolution + full modgraph scan) entirely.
// Returns nullopt when there's no usable cache entry (build_run_target
// falls back to the full prepare_build path, which also refreshes the
// cache for next time), an exit code otherwise.
std::optional<int> try_fast_run(const std::filesystem::path& projectRoot,
const std::optional<std::string>& targetName,
std::span<const std::string> passthrough) {
auto entries = read_build_cache(projectRoot);
const BuildCacheEntry* match = nullptr;
for (auto& e : entries) {
if (e.targetTriple.empty()) { match = &e; break; }
}
if (!match || match->runTargets.empty()) return std::nullopt;
auto outputDirStr = match->outputDir;
auto ninjaProgram = match->ninjaProgram;
// Legacy caches stored a shell-quoted path; execvp needs the raw path.
if (ninjaProgram.size() >= 2 && ninjaProgram.front() == '\''
&& ninjaProgram.back() == '\'')
ninjaProgram = ninjaProgram.substr(1, ninjaProgram.size() - 2);
if (match->runtimeEnvKey.empty())
return std::nullopt; // old cache entry; go through prepare_build once
// P1: verify fingerprint matches the outputDir basename.
if (!match->fingerprint.empty()) {
auto dirBasename = std::filesystem::path(outputDirStr).filename().string();
if (dirBasename != match->fingerprint) return std::nullopt;
}
// Locate the requested run-target before doing any filesystem freshness
// work — an unrecognized name falls back to prepare_build, which gives
// a proper "no binary target 'x' found" error instead of a silent miss.
const std::pair<std::string, std::string>* chosen = nullptr;
for (auto& rt : match->runTargets) {
if (targetName && rt.first != *targetName) continue;
chosen = &rt;
if (targetName) break;
}
if (!chosen) return std::nullopt;
std::error_code ec;
std::filesystem::path outputDir(outputDirStr);
auto ninjaPath = outputDir / "build.ninja";
if (!std::filesystem::exists(ninjaPath, ec)) return std::nullopt;
auto ninjaTime = std::filesystem::last_write_time(ninjaPath, ec);
if (ec) return std::nullopt;
auto tomlPath = projectRoot / "mcpp.toml";
auto tomlTime = std::filesystem::last_write_time(tomlPath, ec);
if (ec || tomlTime > ninjaTime) return std::nullopt;
if (sources_newer_than(projectRoot, ninjaTime)) return std::nullopt;
// Fresh → run ninja (picks up any incremental object/link work) then
// exec the cached exe path directly.
auto rc = run_ninja_fast(ninjaProgram, outputDir, ninjaPath, /*verbose=*/false,
match->runtimeEnvKey, match->runtimeEnvValue);
if (!rc) return std::nullopt;
if (*rc != 0) return rc;
auto exe = outputDir / chosen->second;
auto pathCtx = mcpp::fetcher::make_path_ctx(/*cfg=*/nullptr, projectRoot);
mcpp::ui::status("Running",
std::format("`{}`", mcpp::ui::shorten_path(exe, pathCtx)));
std::println("");
std::fflush(stdout);
std::vector<std::string> argv;
argv.push_back(exe.string());
for (auto& a : passthrough) argv.push_back(a);
std::vector<std::pair<std::string, std::string>> childEnv;
if (!match->runEnvKey.empty() && !match->runEnvValue.empty())
childEnv.emplace_back(match->runEnvKey, match->runEnvValue);
return mcpp::platform::process::run_exec(argv, childEnv) == 0 ? 0 : 1;
}
// `mcpp run` driver: build, locate the binary target, exec it with the
// resolved runtime environment. `package_filter` (`-p`/`--package`) scopes
// a workspace invocation to one member — single-member only, no
// `--workspace` fan-out (running N binaries in one invocation isn't a
// coherent "run"). Threaded straight to prepare_build's BuildOverrides,
// which already does the member switch (basename OR member path — the same
// rule mcpp::project::resolve_member_dir documents for build/test).
export int build_run_target(const std::optional<std::string>& targetName,
std::span<const std::string> passthrough,
const std::string& package_filter = {}) {
// mcpp#225 (E2): reuse the resolved build cache when it's still fresh,
// skipping prepare_build's toolchain resolution + modgraph scan
// entirely — mirrors cmd_build's try_fast_build fast path. The cached
// entry was written for whichever package occupied the project root
// last time; a `-p` filter always needs prepare_build's member switch,
// so skip the fast path in that case (mirrors cmd_build's fast-path
// bypass whenever ov.package_filter is set).
if (package_filter.empty()) {
if (auto root = mcpp::project::find_manifest_root(std::filesystem::current_path())) {
if (auto rc = try_fast_run(*root, targetName, passthrough)) {
return *rc;
}
}
}
// Build first. Single prepare_build → drive build → reuse ctx to locate
// the binary, so we don't re-resolve the toolchain or re-scan modgraph.
mcpp::build::BuildOverrides ov;
ov.package_filter = package_filter;
auto ctx = prepare_build(/*print_fp=*/false, /*includeDevDeps=*/false,
/*extraTargets=*/{}, ov);
if (!ctx) { std::println(stderr, "error: {}", ctx.error()); return 2; }
if (auto rc = run_build_plan(*ctx, /*verbose=*/false, /*no_cache=*/false); rc != 0)
return rc;
// Find binary target
const mcpp::build::LinkUnit* chosen = nullptr;
for (auto& lu : ctx->plan.linkUnits) {
if (lu.kind != mcpp::build::LinkUnit::Binary) continue;
if (targetName && lu.targetName != *targetName) continue;
chosen = &lu;
if (targetName) break;
}
if (!chosen) {
std::println(stderr, "error: no binary target {}",
targetName ? std::format("'{}' found", *targetName) : "in this package");
return 2;
}
auto exe = ctx->outputDir / chosen->output;
auto pathCtx = mcpp::fetcher::make_path_ctx(/*cfg=*/nullptr, ctx->projectRoot);
mcpp::ui::status("Running",
std::format("`{}`", mcpp::ui::shorten_path(exe, pathCtx)));
std::println("");
std::fflush(stdout);
std::vector<std::string> argv;
argv.push_back(exe.string());
for (auto& a : passthrough) argv.push_back(a);
std::vector<std::pair<std::string, std::string>> childEnv;
auto [runEnvKey, runEnvValue] = compute_run_env(ctx->plan);
if (!runEnvKey.empty() && !runEnvValue.empty())
childEnv.emplace_back(runEnvKey, runEnvValue);
// Direct exec (no /bin/sh): the loader env reaches ONLY the target child,
// never mcpp or a host shell. Fixes the bundled-glibc-vs-host-libtinfo
// crash on newer-glibc distros.
return mcpp::platform::process::run_exec(argv, childEnv) == 0 ? 0 : 1;
}
export enum class TestMessageFormat { Human, Json };
export struct TestOptions {
std::string filter; // substring match on the path-based test name; empty = all
TestMessageFormat format = TestMessageFormat::Human;
bool list = false; // enumerate only, no build/run
int timeoutSecs = 0; // per-test run deadline; 0 = unlimited
};
// Minimal JSON string escaping for the --message-format json records. Same
// shape as json_escape in cmd_xpkg.cppm — kept local (15 lines) rather than
// shared across the cli/build module boundary.
static std::string test_json_escape(std::string_view s) {
std::string out;
out.reserve(s.size() + 8);
for (char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20)
out += std::format("\\u{:04x}", static_cast<unsigned char>(c));
else out += c;
}
}
return out;
}
// `mcpp test` driver: discover tests/**/*.cpp, synthesize targets, build
// with dev-deps, run each test binary, summarize.
export int run_tests(std::span<const std::string> passthrough,
BuildOverrides overrides = {},
TestOptions testOpts = {}) {
const bool json = (testOpts.format == TestMessageFormat::Json);
// JSON mode: stdout carries NDJSON only. All ui::status/info lines print
// to stdout, so silence them wholesale; errors already go to stderr.
if (json) mcpp::ui::set_quiet(true);
auto root = mcpp::project::find_manifest_root(std::filesystem::current_path());
if (!root) {
mcpp::ui::error("no mcpp.toml found in current directory or any parent");
return 2;
}
// Workspace scoping: discovery must run against the MEMBER, not the
// workspace root — otherwise `tests/**/*.cpp` globs every member's tests
// together (two `tests/main.cpp` → "duplicate test name 'main'"). When a
// member is selected (via -p, threaded as package_filter), glob from its
// dir; prepare_build below resolves the SAME member, so the two agree.
// (--workspace fans out over members at the cmd layer, one call per member.)
auto testRoot = *root;
if (auto rm = mcpp::manifest::load(*root / "mcpp.toml"); rm) {
auto member = mcpp::project::resolve_member_dir(*rm, *root, overrides.package_filter);
if (!member) { mcpp::ui::error(member.error()); return 2; }
if (!member->empty()) testRoot = *member;
}
// 1. Discover test files (scoped to the member/package).
auto testFiles = mcpp::modgraph::expand_glob(testRoot, "tests/**/*.cpp");
if (testFiles.empty()) {
std::println("no tests found in tests/");
return 0;
}
// [build].flags globs also cover tests: a glob names files — whether they
// are scanned sources or test TUs is orthogonal. Matched entries ride the
// per-target flag channel (issue #131) on the synthesized test target.
// (Feature-folded entries are prepare-time state; tests take the base
// [build].flags — sufficient for per-test compile options.)
struct TestGlobFlags {
mcpp::manifest::GlobFlags gf;
std::set<std::filesystem::path> files;
};
std::vector<TestGlobFlags> testGlobFlags;
if (auto mm = mcpp::manifest::load(testRoot / "mcpp.toml")) {
for (auto const& gf : mm->buildConfig.globFlags) {
auto hits = mcpp::modgraph::expand_glob(testRoot, gf.glob);
testGlobFlags.push_back({gf, {hits.begin(), hits.end()}});
}
}
// 2. Synthesize a Target for each test file.
// Name = path relative to tests/, extension dropped, '/' separators —
// so tests/00-a/0.cpp and tests/01-b/0.cpp coexist as '00-a/0' and
// '01-b/0' (stems alone would collide). Flat layouts keep their old
// names ('tests/smoke.cpp' → 'smoke').
std::vector<mcpp::manifest::Target> testTargets;
std::set<std::string> seenNames;
for (auto& f : testFiles) {
auto rel = std::filesystem::relative(f, testRoot / "tests");
auto name = rel.replace_extension("").generic_string();
if (!seenNames.insert(name).second) {
mcpp::ui::error(std::format(
"duplicate test name '{}' (two test files map to the same name)", name));
return 2;
}
mcpp::manifest::Target t;
t.name = name;
t.kind = mcpp::manifest::Target::TestBinary;
// Relative to the member/package root prepare_build will operate on.
t.main = std::filesystem::relative(f, testRoot).string();
for (auto const& tgf : testGlobFlags) {
if (!tgf.files.contains(f)) continue;
for (auto const& d : tgf.gf.defines) t.defines.push_back(d);
for (auto const& fl : tgf.gf.cflags) t.cflags.push_back(fl);
for (auto const& fl : tgf.gf.cxxflags) t.cxxflags.push_back(fl);
}
testTargets.push_back(std::move(t));
}
// --list: enumerate (filtered) tests and stop — no toolchain resolution,
// no build. Names/paths come straight from discovery, so this also works
// on tests that do not currently compile.
if (testOpts.list) {
std::size_t total = 0;
for (auto& t : testTargets) {
if (!testOpts.filter.empty()
&& t.name.find(testOpts.filter) == std::string::npos) continue;
++total;
auto abs = std::filesystem::absolute(testRoot / t.main)
.lexically_normal().generic_string();
if (json)
std::println("{{\"test\":\"{}\",\"main\":\"{}\"}}",
test_json_escape(t.name), test_json_escape(abs));
else
std::println("{}", t.name);
}
if (json) {
std::println("{{\"summary\":{{\"total\":{}}}}}", total);
std::fflush(stdout);
}
return 0;
}
// 3. prepare_build with dev-deps enabled + synthetic targets.
auto ctx = prepare_build(/*print_fp=*/false,
/*includeDevDeps=*/true,
std::move(testTargets),
std::move(overrides));
if (!ctx) { mcpp::ui::error(ctx.error()); return 2; }
// Filter guard. The filter selects at the build/run stage ONLY — the plan
// above always contains every test, so build.ninja and
// compile_commands.json stay complete (clangd depends on the latter; a
// filtered run must not clobber it down to one entry).
auto filter_match = [&](const mcpp::build::LinkUnit& lu) {
return lu.kind == mcpp::build::LinkUnit::TestBinary
&& (testOpts.filter.empty()
|| lu.targetName.find(testOpts.filter) != std::string::npos);
};
if (!testOpts.filter.empty()) {
bool any = false;
for (auto& lu : ctx->plan.linkUnits)
if (filter_match(lu)) { any = true; break; }
if (!any) {
if (json)
std::println("{{\"error\":\"no-tests-matched\",\"filter\":\"{}\"}}",
test_json_escape(testOpts.filter));
mcpp::ui::error(std::format("no tests match '{}'", testOpts.filter));
return 2;
}
}
// 4. "Compiling test_X (test)" lines for the test binaries.
std::set<std::string> cachedNames;
for (auto& label : ctx->cachedDepLabels) {
auto sp = label.find(' ');
cachedNames.insert(sp == std::string::npos ? label : label.substr(0, sp));
}
std::set<std::string> announced;
announced.insert(ctx->manifest.package.name);
mcpp::ui::status("Compiling",
std::format("{} v{} (.)",
ctx->manifest.package.name, ctx->manifest.package.version));
for (auto& [name, spec] : ctx->manifest.dependencies) {
if (announced.contains(name)) continue;
announced.insert(name);
std::string ver = spec.isPath() ? "(path)" : std::string("v") + spec.version;
const char* verb = cachedNames.contains(name) ? "Cached" : "Compiling";
mcpp::ui::status(verb, std::format("{} {}", name, ver));
}
for (auto& [name, spec] : ctx->manifest.devDependencies) {
if (announced.contains(name)) continue;
announced.insert(name);
std::string ver = spec.isPath() ? "(path)" : std::string("v") + spec.version;
const char* verb = cachedNames.contains(name) ? "Cached" : "Compiling";
mcpp::ui::status(verb,
std::format("{} {} (dev)", name, ver));
}
// List test binaries.
// (Per-test "Compiling" lines print in Phase B, interleaved with each
// test's own result — announcing them all up front separated the three
// pieces of one test's story across the whole output.)
// 5. Two-phase build. Phase A: package-level artifacts (everything that
// is not a test binary — libs, deps). A failure here is the PACKAGE's
// fault, not any single test's: report it as a build error, never as
// N red tests. Phase B (below): each test is built as its own ninja
// goal, so a compile failure is attributed to exactly that test and
// the rest still build and run.
struct TestResult {
std::string name;
enum class St { Pass, CompileFail, RunFail } status;
int exitCode = 0;
std::string compileOutput;
std::string runOutput;
long long durationMs = 0; // build+run wall time for THIS test
bool timedOut = false; // killed by --timeout
};
std::vector<TestResult> results;
// Streaming NDJSON: one record per test, emitted as it finishes — a
// consumer (e.g. the d2x provider) sees progress live, and a crash
// mid-run still leaves the completed records on stdout.
auto emit_json = [&](const TestResult& r) {
if (!json) return;
const char* st = r.status == TestResult::St::Pass ? "pass"
: r.status == TestResult::St::CompileFail ? "compile_fail"
: "run_fail";
std::string signal = (r.exitCode > 128 && r.exitCode < 128 + 65)
? std::to_string(r.exitCode - 128) : "null";
std::println("{{\"test\":\"{}\",\"status\":\"{}\",\"exit_code\":{},\"signal\":{},"
"\"duration_ms\":{},\"timed_out\":{},"
"\"compile_output\":\"{}\",\"run_output\":\"{}\"}}",
test_json_escape(r.name), st, r.exitCode, signal, r.durationMs,
r.timedOut ? "true" : "false",
test_json_escape(r.compileOutput), test_json_escape(r.runOutput));
std::fflush(stdout);
};
auto backend = mcpp::build::make_ninja_backend();
// Phase A goal set: every shared prerequisite — all package/dep compile
// units EXCEPT the tests' own main TUs, plus any non-test link outputs.
// In test mode the lib link unit is skipped entirely (plan.cppm), so the
// package's module objects are the only place shared breakage can show
// up; building them here is what keeps a broken src/ module a PACKAGE
// error instead of N identical per-test compile failures.
std::set<std::filesystem::path> testMains;
for (auto& lu : ctx->plan.linkUnits)
if (lu.kind == mcpp::build::LinkUnit::TestBinary && lu.entryMain)
testMains.insert(*lu.entryMain);
std::vector<std::string> pkgTargets;
for (auto& cu : ctx->plan.compileUnits)
if (!testMains.contains(cu.source))
pkgTargets.push_back(cu.object.generic_string());
for (auto& lu : ctx->plan.linkUnits)
if (lu.kind != mcpp::build::LinkUnit::TestBinary)
pkgTargets.push_back(lu.output.generic_string());
if (!pkgTargets.empty()) {
mcpp::build::BuildOptions aOpts;
aOpts.ninjaTargets = pkgTargets;
auto a = backend->build(ctx->plan, aOpts);
if (!a) {
std::fflush(stdout);
if (json)
std::println("{{\"error\":\"package\",\"compile_output\":\"{}\"}}",
test_json_escape(a.error().diagnosticOutput));
mcpp::ui::error(a.error().message);
// Surface the compiler/linker stderr (parity with run_build_plan) —
// otherwise `mcpp test` failures show only "build failed" with no
// diagnostic, which is undebuggable (notably on CI).
if (!a.error().diagnosticOutput.empty()) {
std::fputs(a.error().diagnosticOutput.c_str(), stderr);
if (a.error().diagnosticOutput.back() != '\n')
std::fputc('\n', stderr);
}
return 1;
}
// M3.2: populate BMI cache for deps that did NOT hit cache — deps
// are package-level artifacts, so this belongs right after Phase A.
for (auto& task : ctx->depsToPopulate) {
auto pr = mcpp::bmi_cache::populate_from(task.key, ctx->outputDir, task.artifacts);
if (!pr) {
mcpp::ui::warning(std::format(
"bmi cache populate failed for {}@{}: {}",
task.key.packageName, task.key.version, pr.error()));
}
}
// No "Finished test" line here: Phase A only built the shared
// prerequisites. Printing a success banner right before per-test
// failures read as a contradiction; the final summary carries timing.
}
// 6. Phase B. First a single keep-going bulk build over every selected
// test goal — ninja parallelizes across tests and a failing test does
// not stop the rest (-k 0). The result is deliberately ignored: the
// per-test loop below re-drives each goal, where successes are cache
// hits (near no-ops) and failures re-fail fast, yielding cleanly
// attributed per-test diagnostics without sacrificing parallelism.
{
mcpp::build::BuildOptions bulk;
bulk.keepGoing = true;
for (auto& lu : ctx->plan.linkUnits)
if (filter_match(lu))
bulk.ninjaTargets.push_back(lu.output.generic_string());
if (!bulk.ninjaTargets.empty())
(void)backend->build(ctx->plan, bulk);
}
// Then build + run each test in sequence; collect results.
auto t0 = std::chrono::steady_clock::now();
auto runtimeEnvKey = mcpp::platform::env::runtime_library_path_key();
auto runtimeEnvValue = mcpp::platform::env::prepend_path_list(
runtimeEnvKey, ctx->plan.runtimeLibraryDirs);
for (auto& lu : ctx->plan.linkUnits) {
if (!filter_match(lu)) continue;
auto tTest = std::chrono::steady_clock::now();
auto test_ms = [&tTest] {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - tTest).count();
};
mcpp::ui::status("Compiling", std::format("{} (test)", lu.targetName));