-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.cppm
More file actions
3201 lines (2939 loc) · 139 KB
/
cli.cppm
File metadata and controls
3201 lines (2939 loc) · 139 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.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.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.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 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;
}
}
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;
}
// Toolchain frontend lookup. Different xim packages ship the C++ frontend
// under different binary names — `gcc` ships `g++`, `musl-gcc` only ships
// the triple-prefixed `x86_64-linux-musl-g++`, etc. Returns the path to
// the frontend, or empty if none of the known candidates exist.
std::filesystem::path
toolchain_frontend(const std::filesystem::path& binDir,
std::string_view compiler)
{
std::vector<std::string> cands;
if (compiler == "musl-gcc") {
cands = {"x86_64-linux-musl-g++", "g++"};
} else if (compiler == "gcc") {
cands = {"g++"};
} else if (compiler == "clang" || compiler == "llvm") {
cands = {"clang++"};
} else if (compiler == "msvc") {
cands = {"cl.exe"};
} else {
// Unknown xpkg — try each in priority order.
cands = {"g++", "clang++", "x86_64-linux-musl-g++", "cl.exe"};
}
for (auto& c : cands) {
auto p = binDir / c;
if (std::filesystem::exists(p)) return p;
}
return {};
}
// 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;
}
// 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's gcc tarball is built with an absolute hardcoded path
// `/home/xlings/.xlings_data/subos/linux/lib/...` baked into the gcc specs
// (both as `--dynamic-linker` and `-rpath`). xim's gcc-specs-config.lua
// tries to override these but only matches `/lib64/ld-linux-x86-64.so.2`,
// not the baked-in `/home/xlings/...`, so the override silently no-ops.
//
// TODO(xim-pkgindex-upstream): file an issue against xim-pkgindex's
// gcc-specs-config.lua to also match the `/home/xlings/...` baked-in
// path. Once fixed, this whole post-install fixup can be deleted.
//
// Result: gcc compiles user binaries with PT_INTERP pointing at
// `/home/xlings/.xlings_data/...` AND an rpath pointing at the same
// non-existent directory. `elfpatch.auto` (now functional thanks to the
// patchelf bootstrap) only fixes ELF binaries it scans; it doesn't touch
// the gcc specs text file.
//
// Mcpp does the post-install spec rewrite itself:
// - The dynamic-linker path becomes <glibc_lib64>/ld-linux-x86-64.so.2.
// - The rpath becomes <glibc_lib64>:<gcc_lib64> so user binaries can find
// both libc.so.6 (glibc) and libstdc++.so.6 + libgcc_s.so.1 (gcc).
// Idempotent.
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;
constexpr std::string_view kBakedDir =
"/home/xlings/.xlings_data/subos/linux/lib";
auto kBakedLoader = std::format("{}/ld-linux-x86-64.so.2", kBakedDir);
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();
if (content.find(kBakedDir) == std::string::npos) continue;
// Order matters: replace the full loader file path first so the
// shorter dir pattern doesn't eat its prefix.
replace_all(content, kBakedLoader, loaderReplacement);
replace_all(content, kBakedDir, 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)
};
// `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());
// 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);
}
return &*cfg_opt;
};
constexpr std::string_view kCurrentPlatform =
#if defined(__linux__)
"linux";
#elif defined(__APPLE__)
"macos";
#elif defined(_WIN32)
"windows";
#else
"unknown";
#endif
// M5.5: toolchain resolution priority:
// 0. --target X / --static, looked up in [target.<triple>]
// 1. project mcpp.toml [toolchain].<platform> or .default
// 2. global ~/.mcpp/config.toml [toolchain].default
// 3. hard error (no system fallback)
auto tcSpec = m->toolchain.for_platform(kCurrentPlatform);
if (!tcSpec.has_value()) {
auto cfg = get_cfg();
if (cfg && !(*cfg)->defaultToolchain.empty()) {
tcSpec = (*cfg)->defaultToolchain;
}
}
// ─── --target / --static overrides ──────────────────────────────────
// Look up [target.<triple>] from manifest; fall back to convention
// (anything ending with "-musl" → gcc@<inherited-version>-musl + static).
auto endswith = [](std::string_view s, std::string_view suf) {
return s.size() >= suf.size()
&& s.compare(s.size() - suf.size(), suf.size(), suf) == 0;
};
if (!overrides.target_triple.empty()) {
auto it = m->targetOverrides.find(overrides.target_triple);
if (it != m->targetOverrides.end()) {
if (!it->second.toolchain.empty()) tcSpec = it->second.toolchain;
if (!it->second.linkage.empty()) m->buildConfig.linkage = it->second.linkage;
}
// Convention: "*-musl" target without an explicit `[target.X]`
// override gets the canonical musl-gcc spec the rest of mcpp
// uses internally. We can't just append "-musl" to the inherited
// toolchain version because xim doesn't have a `musl-gcc@<host
// gcc version>` for every gcc release — gcc 16.1 has no musl
// variant yet, only 9.4 / 11.5 / 13.3 / 15.1 do. Picking 15.1.0
// as the static default matches what mcpp itself uses for
// `mcpp build --target x86_64-linux-musl` (see mcpp.toml).
if (endswith(overrides.target_triple, "-musl")
&& (it == m->targetOverrides.end() || it->second.toolchain.empty()))
{
tcSpec = "gcc@15.1.0-musl";
}
if (endswith(overrides.target_triple, "-musl")
&& m->buildConfig.linkage.empty()) {
m->buildConfig.linkage = "static";
}
}
if (overrides.force_static) m->buildConfig.linkage = "static";
if (tcSpec.has_value() && *tcSpec != "system") {
// Parse "<pkg>@<version>" with an optional "-musl" libc suffix on
// the version: "gcc@15.1.0" or "gcc@15.1.0-musl".
auto at = tcSpec->find('@');
if (at == std::string::npos) {
return std::unexpected(std::format(
"[toolchain].{} = '{}' is invalid; expected '<pkg>@<version>'",
kCurrentPlatform, *tcSpec));
}
auto compiler = tcSpec->substr(0, at);
auto version = tcSpec->substr(at + 1);
// Strip xim: prefix if user wrote it explicitly
std::string indexedCompiler = compiler;
if (auto colon = compiler.find(':'); colon != std::string::npos)
indexedCompiler = compiler.substr(colon + 1);
// libc suffix: `gcc@15.1.0-musl` → xim package `xim:musl-gcc@15.1.0`,
// binary at `<root>/bin/x86_64-linux-musl-g++`.
bool isMusl = endswith(version, "-musl");
std::string ximName = indexedCompiler;
std::string ximVersion = version;
if (isMusl) {
ximVersion = version.substr(0, version.size() - 5); // drop "-musl"
ximName = "musl-" + indexedCompiler; // gcc → musl-gcc
}
std::string target = std::format("xim:{}@{}", ximName, ximVersion);
auto cfg = get_cfg();
if (!cfg) return std::unexpected(cfg.error());
mcpp::fetcher::Fetcher fetcher(**cfg);
mcpp::ui::info("Resolving", "toolchain");
CliInstallProgress progress;
auto payload = fetcher.resolve_xpkg_path(target, /*autoInstall=*/true, &progress);
if (!payload) {
return std::unexpected(std::format(
"toolchain '{}': {}", *tcSpec, payload.error().message));
}
std::string binary_name = "g++";
if (indexedCompiler == "llvm" || indexedCompiler == "clang") binary_name = "clang++";
else if (indexedCompiler == "msvc") binary_name = "cl.exe";
if (isMusl) {
// musl-gcc xpkg ships only the triple-prefixed frontends.
binary_name = "x86_64-linux-musl-g++";
}
explicit_compiler = payload->binDir / binary_name;
if (!std::filesystem::exists(explicit_compiler)) {
return std::unexpected(std::format(
"toolchain payload '{}' has no '{}' (looked at {})",
target, binary_name, explicit_compiler.string()));
}
mcpp::ui::info("Resolved",
std::format("{} → {}", *tcSpec,
mcpp::ui::shorten_path(explicit_compiler,
make_path_ctx(&**get_cfg(), *root))));
} else if (tcSpec.has_value() && *tcSpec == "system") {
// Explicit user opt-in to system PATH compiler — kept as escape hatch.
} else if (auto* opt = std::getenv("MCPP_NO_AUTO_INSTALL"); opt && *opt && *opt != '0') {
// CI / offline / test opt-out: hard-error instead of silently
// pulling ~800 MB of toolchain. Preserves the original M5.5
// contract for environments that need it.
return std::unexpected(
"no toolchain configured.\n"
" run one of:\n"
" mcpp toolchain install gcc 15.1.0-musl\n"
" mcpp toolchain default gcc@15.1.0-musl\n"
" or unset MCPP_NO_AUTO_INSTALL to let mcpp auto-install.");
} else {
// First-run UX: no project-level [toolchain], no global default,
// and the user just ran `mcpp build` (or similar). Auto-install
// mcpp's canonical default — musl-gcc 15.1.0 — so the user gets
// a portable static binary out of the box without any config. We
// pin it as the global default so the next invocation is silent.
// Users can switch any time via `mcpp toolchain default <spec>`.
std::string defaultSpec = "gcc@15.1.0-musl";
mcpp::ui::info("First run",
std::format("no toolchain configured — installing {} (musl, static) as default",
defaultSpec));
auto cfg = get_cfg();
if (!cfg) return std::unexpected(cfg.error());
mcpp::fetcher::Fetcher fetcher(**cfg);
// gcc@15.1.0-musl → xim:musl-gcc@15.1.0; binary at
// <root>/bin/x86_64-linux-musl-g++. (Same translation `cmd_toolchain`
// and the build path apply.)
std::string ximTarget = "xim:musl-gcc@15.1.0";
std::string ximBinaryRel = "x86_64-linux-musl-g++";
CliInstallProgress progress;
auto payload = fetcher.resolve_xpkg_path(ximTarget,
/*autoInstall=*/true, &progress);
if (!payload) {
return std::unexpected(std::format(
"auto-installing default toolchain {} failed: {}\n"
" you can install it manually with:\n"
" mcpp toolchain install gcc 15.1.0-musl",
defaultSpec, payload.error().message));
}
explicit_compiler = payload->binDir / ximBinaryRel;
if (!std::filesystem::exists(explicit_compiler)) {
return std::unexpected(std::format(
"default toolchain payload {} has no {} at {}",
ximTarget, ximBinaryRel, explicit_compiler.string()));
}
// Persist the default so we don't ask again next time.
if (auto wr = mcpp::config::write_default_toolchain(**cfg, defaultSpec); wr) {
(*cfg)->defaultToolchain = defaultSpec;
mcpp::ui::status("Default", std::format("set to {}", defaultSpec));
} // best-effort: a failed config write only loses the persistence,
// not the running build.
tcSpec = defaultSpec;
}
auto tc = mcpp::toolchain::detect(explicit_compiler);
if (!tc) return std::unexpected(tc.error().message);
// For musl-gcc the toolchain is fully self-contained
// (`<root>/x86_64-linux-musl/{include,lib}` is its own sysroot), and
// pointing it at mcpp's glibc subos breaks compilation. Skip the
// sysroot injection in that case — musl-gcc's `-dumpmachine` reports
// `x86_64-linux-musl`, which is also the marker we use elsewhere.
bool isMuslTc = tc->targetTriple.find("-musl") != std::string::npos;