-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcli.cppm
More file actions
4066 lines (3719 loc) · 178 KB
/
cli.cppm
File metadata and controls
4066 lines (3719 loc) · 178 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.cli — top-level command dispatch.
//
// MVP commands:
// mcpp new <name>
// mcpp build [--verbose] [--print-fingerprint] [--no-cache]
// mcpp run [target] [-- args...]
// mcpp clean [--bmi-cache]
// mcpp emit xpkg [--version V] [--output FILE] (M2)
// mcpp --help / mcpp --version
module;
#include <cstdio>
#include <cstdlib>
export module mcpp.cli;
import std;
import mcpp.manifest;
import mcpp.modgraph.graph;
import mcpp.modgraph.scanner;
import mcpp.modgraph.validate;
import mcpp.toolchain.detect;
import mcpp.toolchain.fingerprint;
import mcpp.toolchain.registry;
import mcpp.toolchain.stdmod;
import mcpp.build.plan;
import mcpp.build.backend;
import mcpp.build.ninja;
import mcpp.lockfile;
import mcpp.publish.xpkg_emit;
import mcpp.pack;
import mcpp.config;
import mcpp.xlings;
import mcpp.fetcher;
import mcpp.pm.resolver; // PR-R4: extracted from cli.cppm
import mcpp.pm.commands; // PR-R5: cmd_add / cmd_remove / cmd_update live here now
import mcpp.pm.mangle; // Level 1 multi-version fallback (cross-major coexistence)
import mcpp.pm.compat; // 0.0.6: namespace field + dotted-name compat shims
import mcpp.pm.dep_spec;
import mcpp.ui;
import mcpp.bmi_cache;
import mcpp.dyndep;
import mcpp.version_req; // SemVer constraint resolution
import mcpplibs.cmdline; // M6.1: dogfooded CLI parser
export namespace mcpp::cli {
int run(int argc, char** argv);
} // namespace mcpp::cli
namespace mcpp::cli::detail {
// ----- helpers -----
//
// As of M6.1 phase 3, all CLI commands dispatch through a single
// `cmdline::App` declared in `run()` below. The previous per-command
// `cl::App` build + `parse_cmd_args(...)` double-parse is gone; each
// `cmd_*` now takes the already-parsed `ParsedArgs` and reads from it.
// `cmdline` handles `--help` / `--version` / unknown-option errors itself.
// Custom top-level help. cmdline's auto-generated `print_help` is a fine
// default but its layout (`USAGE:`, no command-specific blurbs) doesn't
// match what the e2e tests assert against — they check for `Usage:`
// (mixed case) plus `mcpp new` / `mcpp build` literals. We keep the
// canonical printer here so the docs/CHANGELOG examples don't drift
// every time cmdline tweaks its formatting.
void print_usage() {
std::println("mcpp v{} — modern C++23 build tool", mcpp::toolchain::MCPP_VERSION);
std::println("");
std::println("Usage:");
std::println("Project commands:");
std::println(" mcpp new <name> Create a new package skeleton");
std::println(" mcpp build [options] Build the current package");
std::println(" mcpp run [target] [-- args...] Build + run a binary target");
std::println(" mcpp test [-- args...] Build + run all tests/**/*.cpp");
std::println(" mcpp clean [--bmi-cache] Remove target/ (and optionally BMI cache)");
std::println(" mcpp add <pkg>[@<ver>] Add a dependency to mcpp.toml");
std::println(" mcpp remove <pkg> Remove a dependency from mcpp.toml");
std::println(" mcpp update [pkg] Re-resolve deps and rewrite mcpp.lock");
std::println(" mcpp search <keyword> Search packages in registries");
std::println(" mcpp publish [--dry-run] Publish package to default registry");
std::println(" mcpp pack [--mode <m>] Build + bundle into a distributable tarball");
std::println(" mcpp emit xpkg [-V VER] [-o FILE] Generate xpkg Lua entry");
std::println("");
std::println("Resource management:");
std::println(" mcpp toolchain install|list|default Manage mcpp's private toolchains");
std::println(" mcpp cache list|prune|clean|info Inspect/manage the global BMI cache");
std::println(" mcpp index list|add|remove|update Manage package registries");
std::println("");
std::println("About mcpp itself:");
std::println(" mcpp self doctor Diagnose mcpp environment health");
std::println(" mcpp self env Print mcpp paths and toolchain");
std::println(" mcpp self config [--mirror CN|GLOBAL] Show or modify mcpp's xlings config");
std::println(" mcpp self version Show mcpp version");
std::println(" mcpp self explain <CODE> Show extended description for an error code");
std::println(" mcpp --help / --version Help / version");
std::println("");
std::println("Build options:");
std::println(" --verbose, -v Verbose compiler output");
std::println(" --quiet, -q Suppress status output");
std::println(" --print-fingerprint Show toolchain fingerprint and 10 inputs");
std::println(" --no-cache Force-clear target/ before building");
std::println(" --no-color Disable colored output");
std::println("");
std::println("Docs: https://github.com/mcpp-community/mcpp/tree/main/docs");
}
// Locate mcpp.toml by walking upward from cwd.
std::optional<std::filesystem::path> find_manifest_root(std::filesystem::path start) {
auto p = std::filesystem::absolute(start);
while (true) {
if (std::filesystem::exists(p / "mcpp.toml")) return p;
auto parent = p.parent_path();
if (parent == p) return std::nullopt;
p = parent;
}
}
// Find the workspace root by walking upward from a member directory.
// Returns empty if no workspace root found.
std::filesystem::path find_workspace_root(const std::filesystem::path& memberRoot) {
auto p = memberRoot.parent_path();
while (true) {
if (std::filesystem::exists(p / "mcpp.toml")) {
auto m = mcpp::manifest::load(p / "mcpp.toml");
if (m && m->workspace.present) {
// Verify memberRoot is in members list
auto rel = std::filesystem::relative(memberRoot, p);
for (auto& member : m->workspace.members) {
if (rel == std::filesystem::path(member)) return p;
}
}
}
auto parent = p.parent_path();
if (parent == p) break;
p = parent;
}
return {};
}
// Merge workspace.dependencies versions into a member's deps.
void merge_workspace_deps(mcpp::manifest::Manifest& member,
const mcpp::manifest::Manifest& workspace) {
auto merge_map = [&](std::map<std::string, mcpp::manifest::DependencySpec>& deps) {
for (auto& [name, spec] : deps) {
if (!spec.inheritWorkspace) continue;
// Try exact key match first
auto it = workspace.workspace.dependencies.find(name);
if (it != workspace.workspace.dependencies.end()) {
spec.version = it->second.version;
spec.inheritWorkspace = false;
continue;
}
// Try short name for default-ns deps
auto shortIt = workspace.workspace.dependencies.find(spec.shortName);
if (shortIt != workspace.workspace.dependencies.end()) {
spec.version = shortIt->second.version;
spec.inheritWorkspace = false;
}
}
};
merge_map(member.dependencies);
merge_map(member.devDependencies);
merge_map(member.buildDependencies);
}
std::filesystem::path target_dir(const mcpp::toolchain::Toolchain& tc,
const mcpp::toolchain::Fingerprint& fp,
const std::filesystem::path& root)
{
auto triple = tc.targetTriple.empty() ? std::string{"unknown"} : tc.targetTriple;
return root / "target" / triple / fp.hex;
}
// ─── Toolchain version-spec helpers ──────────────────────────────────
//
// Partial versions: `mcpp toolchain install gcc 15` must match
// the latest installed/available 15.x.y, `gcc 15.1` matches the latest
// 15.1.y, etc. Accept either `<comp> <ver>` (two positionals) or `<comp>@<ver>`
// (one positional with `@`) — both forms are normalised here.
// Split "X.Y.Z…" into integer components. A trailing "-musl" (or any other
// non-numeric tail) is dropped — the caller has already handled the libc
// flavour and we only care about the numeric prefix for matching.
std::vector<int> parse_version_components(std::string_view s) {
std::vector<int> out;
int cur = 0;
bool any = false;
for (char c : s) {
if (c >= '0' && c <= '9') { cur = cur * 10 + (c - '0'); any = true; }
else if (c == '.') {
if (any) { out.push_back(cur); cur = 0; any = false; }
else { out.clear(); break; }
} else {
break; // non-numeric tail (e.g. "-musl")
}
}
if (any) out.push_back(cur);
return out;
}
// Pick the version from `available` that best matches `partial`:
// "" → highest version overall
// "15" → highest 15.X.Y
// "15.1" → highest 15.1.Y
// "15.1.0" → exact match (or empty if not present)
// Empty result = no match.
std::optional<std::string>
resolve_version_match(std::string_view partial,
std::vector<std::string> available)
{
if (available.empty()) return std::nullopt;
auto want = parse_version_components(partial);
auto matches = [&](const std::vector<int>& cand) {
if (want.size() > cand.size()) return false;
for (std::size_t i = 0; i < want.size(); ++i)
if (cand[i] != want[i]) return false;
return true;
};
std::optional<std::string> best;
std::vector<int> bestVec;
for (auto& v : available) {
auto comps = parse_version_components(v);
if (comps.empty()) continue;
if (!matches(comps)) continue;
if (!best || std::lexicographical_compare(
bestVec.begin(), bestVec.end(), comps.begin(), comps.end()))
{
best = v;
bestVec = std::move(comps);
}
}
return best;
}
// Enumerate installed `<pkgsDir>/xim-x-<name>/<version>/` subdirs.
std::vector<std::string>
list_installed_versions(const std::filesystem::path& pkgsDir,
std::string_view ximName)
{
std::vector<std::string> out;
auto root = pkgsDir / std::format("xim-x-{}", ximName);
std::error_code ec;
if (!std::filesystem::exists(root, ec)) return out;
for (auto& v : std::filesystem::directory_iterator(root, ec)) {
if (v.is_directory(ec)) out.push_back(v.path().filename().string());
}
return out;
}
// Look up available versions for `xim:<name>` from the locally synced index.
// Falls back to an empty list silently — the caller will then either error
// out with a clear message or just keep the partial as-is.
//
// Index layout in mcpp's sandbox is two-tier:
// <reg>/data/xim-pkgindex/pkgs/<n[0]>/<name>.lua — primary
// <reg>/data/xim-index-repos/<sub-index>/pkgs/<n[0]>/<name>.lua
// We scan both so a package living in either tier resolves.
std::vector<std::string>
list_available_xpkg_versions(const mcpp::config::GlobalConfig& cfg,
std::string_view ximName)
{
if (ximName.empty()) return {};
std::string subdir(1, ximName[0]);
std::string fname = std::string(ximName) + ".lua";
auto try_load = [&](const std::filesystem::path& p)
-> std::optional<std::vector<std::string>>
{
std::error_code ec;
if (!std::filesystem::exists(p, ec)) return std::nullopt;
std::ifstream is(p);
std::string body((std::istreambuf_iterator<char>(is)), {});
return mcpp::manifest::list_xpkg_versions(body, "linux");
};
auto data = cfg.xlingsHome() / "data";
if (auto v = try_load(data / "xim-pkgindex" / "pkgs" / subdir / fname); v)
return std::move(*v);
std::error_code ec;
auto repos = data / "xim-index-repos";
if (std::filesystem::exists(repos, ec)) {
for (auto& repo : std::filesystem::directory_iterator(repos, ec)) {
auto cand = repo.path() / "pkgs" / subdir / fname;
if (auto v = try_load(cand); v) return std::move(*v);
}
}
return {};
}
// ─── Install-time progress display ───────────────────────────────────
//
// xlings emits NDJSON events on stdout via `xlings interface install_packages
// --args ...` (see fetcher.cppm). The events we care about for UX are:
//
// {"kind":"data","dataKind":"download_progress","payload":{
// "elapsedSec": 2.0,
// "files": [{"name":"...", "downloadedBytes":..., "totalBytes":..., "finished":bool, ...}],
// ...
// }}
//
// We parse the first file in the `files` array (xlings serializes the
// currently-active download first) and feed (current, total) to a
// ui::ProgressBar so the user sees a "Downloading <pkg> [==== ]
// 45 MB / 110 MB" line.
struct InstallProgressFile {
std::string name;
double downloaded = 0;
double total = 0;
bool started = false;
bool finished = false;
};
namespace {
// Extract one `{ ... }` object starting at payload[*pos], moving *pos past
// the closing `}`. Returns the slice or empty when no object is here.
std::string_view scan_one_object(std::string_view payload, std::size_t* pos) {
auto p = *pos;
while (p < payload.size() && (payload[p] == ' ' || payload[p] == '\n')) ++p;
if (p >= payload.size() || payload[p] != '{') { *pos = p; return {}; }
auto start = p;
int depth = 0;
bool in_string = false;
for (; p < payload.size(); ++p) {
char c = payload[p];
if (in_string) {
if (c == '\\' && p + 1 < payload.size()) { ++p; continue; }
if (c == '"') in_string = false;
continue;
}
if (c == '"') in_string = true;
else if (c == '{') ++depth;
else if (c == '}') { if (--depth == 0) { ++p; break; } }
}
*pos = p;
return payload.substr(start, (p == payload.size() ? p : p) - start);
}
InstallProgressFile parse_one_install_file(std::string_view obj) {
auto get_str = [&](std::string_view key) -> std::string {
std::string n = std::format("\"{}\":\"", key);
auto q = obj.find(n);
if (q == std::string_view::npos) return "";
q += n.size();
std::string out;
while (q < obj.size() && obj[q] != '"') {
if (obj[q] == '\\' && q + 1 < obj.size()) { out.push_back(obj[q+1]); q += 2; continue; }
out.push_back(obj[q++]);
}
return out;
};
auto get_num = [&](std::string_view key) -> double {
std::string n = std::format("\"{}\":", key);
auto q = obj.find(n);
if (q == std::string_view::npos) return 0;
q += n.size();
auto e = q;
while (e < obj.size()
&& (std::isdigit(static_cast<unsigned char>(obj[e]))
|| obj[e] == '.' || obj[e] == '-' || obj[e] == '+'
|| obj[e] == 'e' || obj[e] == 'E')) ++e;
try { return std::stod(std::string(obj.substr(q, e - q))); }
catch (...) { return 0; }
};
auto get_bool = [&](std::string_view key) -> bool {
std::string n = std::format("\"{}\":", key);
auto q = obj.find(n);
if (q == std::string_view::npos) return false;
q += n.size();
return obj.size() - q >= 4 && obj.substr(q, 4) == "true";
};
InstallProgressFile f;
f.name = get_str("name");
f.downloaded = get_num("downloadedBytes");
f.total = get_num("totalBytes");
f.started = get_bool("started");
f.finished = get_bool("finished");
return f;
}
} // namespace
// Parse every entry in the payload's `files` array. xlings emits an
// array-of-files for download_progress events even when only one is
// active, and during multi-package installs (gcc → glibc / binutils /
// linux-headers / gcc-runtime / gcc) the order of entries shifts as
// each file starts and finishes. Reading just the first one would
// flicker between names and re-emit the static "Downloading <pkg>"
// line every time the first slot rotates.
std::vector<InstallProgressFile>
parse_all_install_files(std::string_view payload)
{
std::vector<InstallProgressFile> out;
constexpr std::string_view kKey{"\"files\":["};
auto p = payload.find(kKey);
if (p == std::string_view::npos) return out;
p += kKey.size();
while (p < payload.size()) {
while (p < payload.size() && (payload[p] == ' ' || payload[p] == '\n'
|| payload[p] == ',')) ++p;
if (p >= payload.size() || payload[p] == ']') break;
if (payload[p] != '{') break;
auto obj = scan_one_object(payload, &p);
if (obj.empty()) break;
auto f = parse_one_install_file(obj);
if (!f.name.empty()) out.push_back(std::move(f));
}
return out;
}
// Pull a top-level numeric field out of a payload JSON string. Cheap;
// only used for `elapsedSec` which we trust to be a plain number.
double extract_payload_number(std::string_view payload, std::string_view key) {
std::string n = std::format("\"{}\":", key);
auto q = payload.find(n);
if (q == std::string_view::npos) return 0;
q += n.size();
auto e = q;
while (e < payload.size()
&& (std::isdigit(static_cast<unsigned char>(payload[e]))
|| payload[e] == '.' || payload[e] == '-' || payload[e] == '+'
|| payload[e] == 'e' || payload[e] == 'E')) ++e;
try { return std::stod(std::string(payload.substr(q, e - q))); }
catch (...) { return 0; }
}
// Build the PathContext used to shorten user-visible paths in status
// output. project_root may be empty (for verbs that don't need it).
mcpp::ui::PathContext make_path_ctx(const mcpp::config::GlobalConfig* cfg,
std::filesystem::path project_root = {})
{
mcpp::ui::PathContext ctx;
ctx.project_root = std::move(project_root);
if (cfg) ctx.mcpp_home = cfg->mcppHome;
if (auto* h = std::getenv("HOME"); h && *h) ctx.home = h;
return ctx;
}
// Stateless adapter from `mcpp::config::BootstrapProgress` (xlings
// download_progress event) to a sticky ProgressBar. Used by
// load_or_init() during the one-time sandbox bootstrap (xim:patchelf,
// xim:ninja, plus their transitive deps).
//
// Two xlings quirks the callback has to absorb:
// 1. Each file's `finished=true` event arrives twice in a row.
// 2. During multi-package installs the `files[]` array reshuffles
// between events (the active download isn't always at slot 0).
// The fix mirrors CliInstallProgress: dedupe via a `finished_` set and
// always pick "active first if still in event, else first
// started+unfinished" rather than reading slot 0 blindly.
mcpp::config::BootstrapProgressCallback make_bootstrap_progress_callback() {
auto bar = std::make_shared<std::optional<mcpp::ui::ProgressBar>>();
auto active = std::make_shared<std::string>();
auto finished = std::make_shared<std::unordered_set<std::string>>();
return [bar, active, finished](const mcpp::config::BootstrapProgress& ev) {
// Process newly-finished entries.
for (auto& f : ev.files) {
if (finished->contains(f.name)) continue;
if (!f.finished) continue;
if (*active == f.name) {
if (*bar) (*bar)->finish();
bar->reset();
active->clear();
}
finished->insert(f.name);
}
// Pick what to display: prefer continuing with `*active` if it's
// still in the array and not finished, otherwise the first
// started+unfinished entry.
const mcpp::config::BootstrapFile* current = nullptr;
for (auto& f : ev.files) {
if (f.name == *active && !f.finished
&& !finished->contains(f.name)) { current = &f; break; }
}
if (!current) {
for (auto& f : ev.files) {
if (finished->contains(f.name)) continue;
if (f.started && !f.finished) { current = &f; break; }
}
}
if (!current) return;
if (current->name != *active) {
if (*bar) (*bar)->finish();
*active = current->name;
bar->emplace("Downloading", current->name);
}
if (current->totalBytes > 0) {
(*bar)->update_bytes(static_cast<std::size_t>(current->downloadedBytes),
static_cast<std::size_t>(current->totalBytes),
ev.elapsedSec);
}
};
}
struct CliInstallProgress : mcpp::fetcher::EventHandler {
std::optional<mcpp::ui::ProgressBar> bar_;
std::string active_;
std::unordered_set<std::string> finished_;
void on_data(const mcpp::fetcher::DataEvent& d) override {
if (d.dataKind != "download_progress") return;
auto files = parse_all_install_files(d.payloadJson);
if (files.empty()) return;
// 1. Process any newly-finished entries. Each file is reported
// twice with finished=true (xlings quirk); the `finished_`
// set dedupes both that AND the rotation case where the
// same file shows up at a different array slot in a later
// event.
for (auto& f : files) {
if (finished_.contains(f.name)) continue;
if (!f.finished) continue;
if (active_ == f.name) {
if (bar_) bar_->finish();
bar_.reset();
active_.clear();
}
finished_.insert(f.name);
}
// 2. Pick what to display. Prefer continuing with the current
// `active_` if it's still in the array and not finished —
// otherwise the first started+unfinished entry. This stops
// the bar from flickering between names when xlings reshuffles
// files[] across events during a multi-package install.
const InstallProgressFile* current = nullptr;
for (auto& f : files) {
if (f.name == active_ && !f.finished
&& !finished_.contains(f.name)) { current = &f; break; }
}
if (!current) {
for (auto& f : files) {
if (finished_.contains(f.name)) continue;
if (f.started && !f.finished) { current = &f; break; }
}
}
if (!current) return;
if (current->name != active_) {
if (bar_) bar_->finish();
active_ = current->name;
bar_.emplace("Downloading", current->name);
}
if (current->total > 0) {
double elapsed = extract_payload_number(d.payloadJson, "elapsedSec");
bar_->update_bytes(static_cast<std::size_t>(current->downloaded),
static_cast<std::size_t>(current->total),
elapsed);
}
}
~CliInstallProgress() override { if (bar_) bar_->finish(); }
};
// Compose a stable canonical compile-flags string for fingerprinting.
std::string canonical_compile_flags(const mcpp::manifest::Manifest& m) {
std::string s;
s += "-std="; s += m.language.standard;
s += " -fmodules";
return s;
}
bool is_std_module(std::string_view name) {
return name == "std" || name == "std.compat";
}
std::string trim_copy(std::string s) {
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.front())))
s.erase(0, 1);
while (!s.empty() && std::isspace(static_cast<unsigned char>(s.back())))
s.pop_back();
return s;
}
bool source_file_imports_std(const std::filesystem::path& path) {
std::ifstream is(path);
if (!is) return false;
std::string line;
while (std::getline(is, line)) {
line = trim_copy(std::move(line));
std::size_t i = std::string::npos;
if (line.starts_with("import ")) {
i = 7;
} else if (line.starts_with("export import ")) {
i = 14;
}
if (i == std::string::npos) continue;
while (i < line.size() && std::isspace(static_cast<unsigned char>(line[i])))
++i;
std::string name;
while (i < line.size()
&& (std::isalnum(static_cast<unsigned char>(line[i]))
|| line[i] == '_' || line[i] == '.' || line[i] == ':')) {
name.push_back(line[i]);
++i;
}
if (is_std_module(name)) return true;
}
return false;
}
bool graph_or_targets_import_std(const mcpp::modgraph::Graph& graph,
const mcpp::manifest::Manifest& manifest,
const std::filesystem::path& projectRoot) {
for (auto& u : graph.units) {
for (auto& req : u.requires_) {
if (is_std_module(req.logicalName))
return true;
}
}
// Some target entry files can be added to the plan after the package scan.
// Check them here so std BMI setup matches what make_plan will compile.
for (auto& t : manifest.targets) {
if (!t.main.empty() && source_file_imports_std(projectRoot / t.main))
return true;
}
return false;
}
// Run patchelf on every dynamic ELF in `dir` (recursively):
// - Set PT_INTERP to `loader` (the sandbox-local glibc loader).
// - Set RUNPATH to `rpath` (colon-separated list of sandbox lib dirs).
// Idempotent; skips static binaries and shared libs without PT_INTERP.
//
// TODO(xlings/libxpkg-upstream): xim 0.4.10's `elfpatch.auto({interpreter=...})`
// is supposed to do this in install hooks but currently scans 0 files for
// some packages (verified empirically: `binutils: elfpatch auto: 0 0 0`).
// Once the upstream legacy elfpatch path is fixed, this mcpp-side walker
// can be deleted.
void patchelf_walk(const std::filesystem::path& dir,
const std::filesystem::path& loader,
const std::string& rpath,
const std::filesystem::path& patchelfBin)
{
if (!std::filesystem::exists(dir) || !std::filesystem::exists(patchelfBin))
return;
std::error_code ec;
for (auto it = std::filesystem::recursive_directory_iterator(dir, ec);
it != std::filesystem::recursive_directory_iterator{}; it.increment(ec))
{
if (ec) { ec.clear(); continue; }
if (!it->is_regular_file(ec)) continue;
auto path = it->path();
// Skip non-ELF (cheap magic check)
std::ifstream is(path, std::ios::binary);
char m[4]{};
is.read(m, 4);
if (!is || m[0] != 0x7f || m[1] != 'E' || m[2] != 'L' || m[3] != 'F')
continue;
is.close();
// Probe PT_INTERP — skip static binaries (no interp).
auto probe = std::format("'{}' --print-interpreter '{}' 2>/dev/null",
patchelfBin.string(), path.string());
std::FILE* fp = ::popen(probe.c_str(), "r");
bool hasInterp = false;
if (fp) {
char buf[1024]{};
hasInterp = (std::fread(buf, 1, sizeof(buf) - 1, fp) > 0);
::pclose(fp);
}
if (hasInterp) {
(void)std::system(std::format(
"'{}' --set-interpreter '{}' '{}' 2>/dev/null",
patchelfBin.string(), loader.string(), path.string()).c_str());
}
// Always set RUNPATH (works on .so too — they need to find deps).
if (!rpath.empty()) {
(void)std::system(std::format(
"'{}' --set-rpath '{}' '{}' 2>/dev/null",
patchelfBin.string(), rpath, path.string()).c_str());
}
}
}
// xim bakes the installing user's XLINGS_HOME into gcc specs at install
// time (as `--dynamic-linker` and `-rpath`). When mcpp uses its own
// isolated sandbox (MCPP_HOME/registry/), the baked-in paths point to
// xlings' home, not mcpp's sandbox glibc — binaries would fail to exec.
//
// Mcpp does a post-install spec rewrite:
// - Dynamically detects the baked-in lib dir from the specs file
// - Replaces the dynamic-linker path with <glibc_lib64>/ld-linux-x86-64.so.2
// - Replaces the rpath with <glibc_lib64>:<gcc_lib64>
// Idempotent — skips if already pointing at the correct glibc.
// Extract the baked-in lib directory from a gcc specs file by finding
// the dynamic-linker path that ends with `/ld-linux-x86-64.so.2`.
// xim bakes the installing user's XLINGS_HOME into specs at install
// time, so the path varies per machine — we cannot hardcode it.
std::string detect_baked_lib_dir(const std::string& specsContent) {
constexpr std::string_view kLoader = "/ld-linux-x86-64.so.2";
auto pos = specsContent.find(kLoader);
if (pos == std::string::npos) return "";
// Walk backwards to find start of the absolute path
auto start = pos;
while (start > 0 && specsContent[start - 1] != ' '
&& specsContent[start - 1] != ':'
&& specsContent[start - 1] != ';'
&& specsContent[start - 1] != '\n') {
--start;
}
auto dir = specsContent.substr(start, pos - start);
// Sanity: must be absolute
if (dir.empty() || dir[0] != '/') return "";
// Skip if it already points to the target glibc (no fixup needed)
return dir;
}
void fixup_gcc_specs(const std::filesystem::path& gccPkgRoot,
const std::filesystem::path& glibcLibDir,
const std::filesystem::path& gccLibDir)
{
auto specsParent = gccPkgRoot / "lib" / "gcc" / "x86_64-linux-gnu";
if (!std::filesystem::exists(specsParent)) return;
auto loaderReplacement = (glibcLibDir / "ld-linux-x86-64.so.2").string();
auto rpathReplacement = std::format("{}:{}",
glibcLibDir.string(),
gccLibDir.string());
auto replace_all = [](std::string& s, std::string_view needle,
std::string_view rep)
{
for (std::size_t pos = 0;
(pos = s.find(needle, pos)) != std::string::npos;) {
s.replace(pos, needle.size(), rep);
pos += rep.size();
}
};
for (auto& sub : std::filesystem::directory_iterator(specsParent)) {
auto specs = sub.path() / "specs";
if (!std::filesystem::exists(specs)) continue;
std::ifstream is(specs);
std::stringstream ss; ss << is.rdbuf();
std::string content = ss.str();
auto bakedDir = detect_baked_lib_dir(content);
if (bakedDir.empty()) continue;
// Already pointing at the right place — no fixup needed.
if (bakedDir == glibcLibDir.string()) continue;
auto bakedLoader = bakedDir + "/ld-linux-x86-64.so.2";
// Order matters: replace the full loader file path first so the
// shorter dir pattern doesn't eat its prefix.
replace_all(content, bakedLoader, loaderReplacement);
replace_all(content, bakedDir, rpathReplacement);
std::ofstream os(specs);
os << content;
}
}
// SemVer resolution: a version spec is a "constraint" (vs. exact literal) if
// it starts with one of `^~><=` or contains a comma (multi-part), or is `*`
// or empty. Bare `1.2.3` is treated as exact for back-compat with pre-SemVer
// pinning workflows; users opt into resolution by writing `^1.2.3` etc.
// `is_version_constraint`, `kXpkgPlatform` and `resolve_semver` have moved
// to `mcpp.pm.resolver` (PR-R4 — see
// `.agents/docs/2026-05-08-pm-subsystem-architecture.md`). Call sites
// below reference the `mcpp::pm::` qualified names directly.
// --- Commands ---
int cmd_new(const mcpplibs::cmdline::ParsedArgs& parsed) {
std::string name = parsed.positional(0);
if (name.empty()) {
std::println(stderr, "error: `mcpp new` requires a package name (e.g. `mcpp new hello`)");
return 2;
}
std::filesystem::path root = std::filesystem::current_path() / name;
if (std::filesystem::exists(root)) {
std::println(stderr, "error: '{}' already exists", root.string());
return 1;
}
std::error_code ec;
std::filesystem::create_directories(root / "src", ec);
if (ec) {
std::println(stderr, "error: cannot create '{}': {}", root.string(), ec.message());
return 1;
}
// mcpp.toml
{
std::ofstream os(root / "mcpp.toml");
os << mcpp::manifest::default_template(name);
}
// src/main.cpp — template with PROJECT placeholder, replaced with `name`.
{
std::string body = R"(// PROJECT — generated by `mcpp new`
import std;
int main(int argc, char* argv[]) {
std::println("Hello from PROJECT!");
std::println("Built with import std + std::println on modular C++23.");
if (argc > 1) {
for (int i = 1; i < argc; ++i) std::println(" arg[{}] = {}", i, argv[i]);
}
return 0;
}
)";
std::size_t pos;
while ((pos = body.find("PROJECT")) != std::string::npos) {
body.replace(pos, 7, name);
}
std::ofstream os(root / "src" / "main.cpp");
os << body;
}
// tests/test_smoke.cpp — bundled smoke test (`mcpp test` works out-of-the-box).
{
std::filesystem::create_directories(root / "tests", ec);
std::ofstream os(root / "tests" / "test_smoke.cpp");
os << R"(// Smoke test — verifies the project compiles + a binary runs.
// Add more tests as tests/test_*.cpp files; mcpp test discovers them
// automatically (one binary per file).
import std;
int main() {
std::println("test_smoke: ok");
return 0;
}
)";
}
// .gitignore
{
std::ofstream os(root / ".gitignore");
os << "target/\n";
}
std::println("Created package '{}' at {}", name, root.string());
std::println("Next: cd {} && mcpp build && mcpp run (or `mcpp test`)", name);
return 0;
}
struct BuildContext {
mcpp::manifest::Manifest manifest;
mcpp::toolchain::Toolchain tc;
mcpp::toolchain::Fingerprint fp;
std::filesystem::path projectRoot;
std::filesystem::path outputDir;
std::filesystem::path stdBmi;
std::filesystem::path stdObject;
mcpp::build::BuildPlan plan;
// M3.2 BMI cache: deps that did NOT hit cache and therefore need
// populate_from(...) AFTER backend.build succeeds.
struct CacheTask {
mcpp::bmi_cache::CacheKey key;
mcpp::bmi_cache::DepArtifacts artifacts;
};
std::vector<CacheTask> depsToPopulate;
// Names of deps that DID hit cache (for ui status output).
std::vector<std::string> cachedDepLabels; // "mcpplibs.cmdline v0.0.1"
};
// Command-level overrides (--target / --static).
// Empty defaults preserve pre-existing behaviour exactly.
struct BuildOverrides {
std::string target_triple; // empty = host triple, fall through to [toolchain]
bool force_static = false; // --static (or implied by musl target)
std::string package_filter; // -p <name>: only build this workspace member
};
// `prepare_build` builds the BuildContext for any verb that compiles.
// includeDevDeps: when true, dev-dependencies are also fetched + scanned
// into the modgraph. mcpp test passes true; build/run pass false.
// extraTargets: additional Target entries (e.g. synthetic test targets)
// appended to the manifest before the modgraph runs.
// overrides: --target / --static.
std::expected<BuildContext, std::string>
prepare_build(bool print_fingerprint,
bool includeDevDeps = false,
std::vector<mcpp::manifest::Target> extraTargets = {},
BuildOverrides overrides = {}) {
auto root = find_manifest_root(std::filesystem::current_path());
if (!root) {
return std::unexpected("no mcpp.toml found in current directory or any parent");
}
auto m = mcpp::manifest::load(*root / "mcpp.toml");
if (!m) return std::unexpected(m.error().format());
// ─── Workspace handling ────────────────────────────────────────────
// If the manifest has [workspace] and is a virtual workspace (no [package]),
// or if -p filter is set, switch to the target member's manifest.
std::optional<mcpp::manifest::Manifest> wsManifest; // keep workspace manifest alive
if (m->workspace.present) {
std::string targetMember;
if (!overrides.package_filter.empty()) {
// -p <name>: find matching member by directory basename or path
for (auto& mp : m->workspace.members) {
auto basename = std::filesystem::path(mp).filename().string();
if (basename == overrides.package_filter || mp == overrides.package_filter) {
targetMember = mp;
break;
}
}
if (targetMember.empty()) {
return std::unexpected(std::format(
"workspace member '{}' not found in [workspace].members",
overrides.package_filter));
}
} else if (m->package.name.empty()) {
// Virtual workspace: find a member with a binary target, or use last member.
for (auto& mp : m->workspace.members) {
auto memberDir = *root / mp;
auto mm = mcpp::manifest::load(memberDir / "mcpp.toml");
if (!mm) continue;
for (auto& t : mm->targets) {
if (t.kind == mcpp::manifest::Target::Binary) {
targetMember = mp;
break;
}
}
if (!targetMember.empty()) break;
}
if (targetMember.empty() && !m->workspace.members.empty()) {
targetMember = m->workspace.members.back();
}
}
// else: rooted workspace with [package] — build root normally.
if (!targetMember.empty()) {
auto memberDir = *root / targetMember;
if (!std::filesystem::exists(memberDir / "mcpp.toml")) {
return std::unexpected(std::format(
"workspace member '{}' has no mcpp.toml", targetMember));
}
wsManifest = std::move(*m); // preserve workspace manifest
m = mcpp::manifest::load(memberDir / "mcpp.toml");
if (!m) return std::unexpected(std::format(
"workspace member '{}': {}", targetMember, m.error().format()));
// Merge workspace dependency versions
merge_workspace_deps(*m, *wsManifest);
// Inherit workspace toolchain if member doesn't define one
if (m->toolchain.byPlatform.empty()) {
m->toolchain = wsManifest->toolchain;
}
// Inherit workspace target overrides
for (auto& [triple, entry] : wsManifest->targetOverrides) {
if (!m->targetOverrides.contains(triple)) {
m->targetOverrides[triple] = entry;
}
}
mcpp::ui::status("Workspace", std::format("building member '{}'", targetMember));
root = memberDir;
}
} else {
// Not at workspace root — check if we're inside a workspace
auto wsRoot = find_workspace_root(*root);
if (!wsRoot.empty()) {
auto wsm = mcpp::manifest::load(wsRoot / "mcpp.toml");
if (wsm && wsm->workspace.present) {
merge_workspace_deps(*m, *wsm);
if (m->toolchain.byPlatform.empty()) {
m->toolchain = wsm->toolchain;
}
for (auto& [triple, entry] : wsm->targetOverrides) {
if (!m->targetOverrides.contains(triple)) {
m->targetOverrides[triple] = entry;
}
}
}
}
}
// Inject synthetic targets (e.g. test binaries from `mcpp test`).
for (auto& t : extraTargets) m->targets.push_back(t);
// ─── Toolchain resolution (docs/21) ────────────────────────────────
// Priority chain:
// 1. mcpp.toml [toolchain].<platform> → resolve_xpkg_path → abs path
// 2. $MCPP_HOME/registry/subos/<active>/bin/g++ (xlings sandbox subos)
// 3. $CXX env var
// 4. PATH g++ (with warning)
std::filesystem::path explicit_compiler;
std::optional<mcpp::config::GlobalConfig> cfg_opt;
auto get_cfg = [&]() -> std::expected<mcpp::config::GlobalConfig*, std::string> {
if (!cfg_opt) {
auto c = mcpp::config::load_or_init(/*quiet=*/false,
make_bootstrap_progress_callback());
if (!c) return std::unexpected(c.error().message);
cfg_opt = std::move(*c);