-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathpackage_fetcher.cppm
More file actions
750 lines (655 loc) · 29.3 KB
/
package_fetcher.cppm
File metadata and controls
750 lines (655 loc) · 29.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
// mcpp.pm.package_fetcher — subprocess-based xlings interface client (NDJSON over stdio).
//
// Each Fetcher::call() invokes:
// XLINGS_HOME=<cfg.xlingsHome()> <cfg.xlingsBinary> interface <cap> --args '{...}'
// then parses the NDJSON event stream emitted on stdout.
//
// Wire format reference: xlings/src/interface.cppm.
module;
#include <cstdio>
#include <cstdlib>
export module mcpp.pm.package_fetcher;
import std;
import mcpp.config;
import mcpp.pm.compat;
import mcpp.pm.index_spec;
import mcpp.xlings;
import mcpp.libs.toml; // re-used for tiny JSON-ish parsing? no — stick with manual
export namespace mcpp::pm {
// --- Events parsed from NDJSON (aliases to mcpp::xlings types) ---
enum class EventKind { Progress, Log, Data, Error, Heartbeat, Result };
using ProgressEvent = mcpp::xlings::ProgressEvent;
using LogEvent = mcpp::xlings::LogEvent;
using DataEvent = mcpp::xlings::DataEvent;
using ErrorEvent = mcpp::xlings::ErrorEvent;
using ResultEvent = mcpp::xlings::ResultEvent;
using Event = mcpp::xlings::Event;
// --- Listener interface (alias to mcpp::xlings::EventHandler) ---
using EventHandler = mcpp::xlings::EventHandler;
// --- Capability invocation ---
struct CallError {
std::string message;
};
using CallResult = mcpp::xlings::CallResult;
class Fetcher {
public:
explicit Fetcher(const config::GlobalConfig& cfg) : cfg_(cfg) {}
// Generic capability call. The handler (if non-null) receives streaming
// events. On success returns aggregate CallResult.
std::expected<CallResult, CallError>
call(std::string_view capability,
std::string_view argsJson,
EventHandler* handler = nullptr);
// High-level helpers (parsed payload for common ops).
struct SearchHit {
std::string source; // "mcpplibs"
std::string name;
std::string description;
};
std::expected<std::vector<SearchHit>, CallError>
search(std::string_view keyword);
struct PackageInstall {
std::string name;
std::string version;
std::string action; // "download" | "skip" | ...
std::string url;
std::string sha256;
};
// Plan: report what install_packages WOULD do, no side effects.
std::expected<std::vector<PackageInstall>, CallError>
plan_install(const std::vector<std::string>& targets);
// Actually install. Streams progress events to the handler if set.
std::expected<CallResult, CallError>
install(const std::vector<std::string>& targets,
EventHandler* handler = nullptr);
// List + manage index repos.
struct RepoInfo { std::string name, url; bool isDefault; };
std::expected<std::vector<RepoInfo>, CallError> list_repos();
std::expected<void, CallError> add_repo(std::string_view name, std::string_view url);
std::expected<void, CallError> remove_repo(std::string_view name);
// ─── Namespace-aware overloads (canonical, 0.0.10+) ────────────
//
// These are the primary APIs. They use structured (namespace, shortName)
// to look up packages, with compat fallback candidates generated by
// mcpp::pm::compat::xpkg_lua_candidates / install_dir_candidates.
// Install path for an installed package. Returns the directory under
// $MCPP_HOME/registry/data/xpkgs/<dir>/<version>/ if it exists.
std::optional<std::filesystem::path>
install_path(std::string_view ns, std::string_view shortName,
std::string_view version) const;
// Read the raw xpkg .lua file content for a package from the cloned
// index. Uses namespace-aware candidate filenames.
std::optional<std::string>
read_xpkg_lua(std::string_view ns, std::string_view shortName) const;
// Read the raw xpkg .lua file content from a local path index.
// Used for [indices] entries with `path = "/some/dir"`.
static std::optional<std::string>
read_xpkg_lua_from_path(const std::filesystem::path& indexPath,
std::string_view shortName);
// Read xpkg .lua from a project-level data directory (.mcpp/data/).
// Used for custom git indices whose clone lives under the project's
// .mcpp/ directory rather than the global xlings home.
static std::optional<std::string>
read_xpkg_lua_from_project_data(const std::filesystem::path& projectDir,
std::string_view ns,
std::string_view shortName);
// Install path under a project-level data directory (.mcpp/data/xpkgs/).
static std::optional<std::filesystem::path>
install_path_from_project_data(const std::filesystem::path& projectDir,
std::string_view ns,
std::string_view shortName,
std::string_view version);
// ─── Legacy overloads (COMPAT, remove in 1.0.0) ─────────────
//
// Accept a raw package name string and infer namespace from it.
// New code should use the (ns, shortName) overloads above.
std::optional<std::filesystem::path>
install_path(std::string_view name, std::string_view version) const;
std::optional<std::string>
read_xpkg_lua(std::string_view package_name) const;
// Unified xpkg payload (one xlings package's installed location and its
// standard subdirs). Returned by resolve_xpkg_path().
struct XpkgPayload {
std::filesystem::path root; // xpkg install root
std::filesystem::path binDir; // root/bin/ (or empty)
std::filesystem::path libDir; // root/lib/ (or empty)
std::filesystem::path includeDir; // root/include/ (or empty)
std::filesystem::path sourceDir; // primary source subdir (or root)
bool hasBin = false;
bool hasLib = false;
bool hasInclude = false;
};
// Resolve a target like "xim:gcc@15.1.0" or "name@1.0" to its xpkg
// payload location. Auto-installs via xlings if missing and
// autoInstall is true.
//
// Target syntax:
// "<index>:<name>@<version>" explicit index namespace
// "<name>@<version>" uses xim namespace by default
std::expected<XpkgPayload, CallError>
resolve_xpkg_path(std::string_view target,
bool autoInstall,
EventHandler* handler = nullptr);
private:
const config::GlobalConfig& cfg_;
// Build the env-prefixed command for a capability call.
std::string build_command(std::string_view capability,
std::string_view argsJson) const;
};
} // namespace mcpp::pm
namespace mcpp::pm {
namespace {
// JSON extraction and NDJSON parsing are now in mcpp::xlings.
// Bring them into this TU's anonymous namespace for use by search/plan_install
// helper code that still needs extract_string/extract_object.
using mcpp::xlings::extract_string;
using mcpp::xlings::extract_int;
using mcpp::xlings::extract_bool;
using mcpp::xlings::extract_object;
using mcpp::xlings::parse_event_line;
using mcpp::xlings::shq;
} // namespace
std::string Fetcher::build_command(std::string_view capability,
std::string_view argsJson) const
{
mcpp::xlings::Env env{ cfg_.xlingsBinary, cfg_.xlingsHome() };
return mcpp::xlings::build_interface_command(env, capability, argsJson);
}
std::expected<CallResult, CallError>
Fetcher::call(std::string_view capability,
std::string_view argsJson,
EventHandler* handler)
{
mcpp::xlings::Env env{ cfg_.xlingsBinary, cfg_.xlingsHome() };
auto r = mcpp::xlings::call(env, capability, argsJson, handler);
if (!r) return std::unexpected(CallError{r.error()});
return *r;
}
// --- Helpers ---
namespace {
// Build args JSON for vector<string> targets.
std::string make_targets_args(const std::vector<std::string>& targets,
bool yes = false)
{
std::string out = "{\"targets\":[";
for (std::size_t i = 0; i < targets.size(); ++i) {
out += "\"" + targets[i] + "\"";
if (i + 1 < targets.size()) out += ",";
}
out += "]";
if (yes) out += ",\"yes\":true";
out += "}";
return out;
}
} // namespace
std::expected<std::vector<Fetcher::SearchHit>, CallError>
Fetcher::search(std::string_view keyword) {
auto args = std::format("{{\"keyword\":\"{}\"}}", keyword);
auto r = call("search_packages", args);
if (!r) return std::unexpected(r.error());
std::vector<SearchHit> hits;
for (auto& d : r->dataEvents) {
if (d.dataKind != "styled_list") continue;
// payload: {"items":[["name","desc"], ...], "title":"..."}
// Crude parse: find "items": [ ... ] and extract pairs.
auto items = extract_object(d.payloadJson, "items");
// items looks like [["a","b"],["c","d"]]
// Walk character by character.
std::size_t p = 0;
while (p < items.size()) {
if (items[p] == '[') {
// start of a pair
++p;
// first string
while (p < items.size() && items[p] != '"') ++p;
std::string name;
if (p < items.size() && items[p] == '"') {
++p;
while (p < items.size() && items[p] != '"') {
if (items[p] == '\\' && p + 1 < items.size()) { p += 2; continue; }
name.push_back(items[p++]);
}
if (p < items.size()) ++p; // skip closing "
}
// skip until next "
while (p < items.size() && items[p] != '"' && items[p] != ']') ++p;
std::string desc;
if (p < items.size() && items[p] == '"') {
++p;
while (p < items.size() && items[p] != '"') {
if (items[p] == '\\' && p + 1 < items.size()) { p += 2; continue; }
desc.push_back(items[p++]);
}
if (p < items.size()) ++p;
}
// record
if (!name.empty()) {
hits.push_back({cfg_.defaultIndex, std::move(name), std::move(desc)});
}
// advance past ]
while (p < items.size() && items[p] != ']') ++p;
if (p < items.size()) ++p;
} else {
++p;
}
}
}
return hits;
}
std::expected<std::vector<Fetcher::PackageInstall>, CallError>
Fetcher::plan_install(const std::vector<std::string>& targets) {
auto args = make_targets_args(targets);
auto r = call("plan_install", args);
if (!r) return std::unexpected(r.error());
std::vector<PackageInstall> plan;
// Look in data events for install_plan; payload has "steps":[{...}, ...]
for (auto& d : r->dataEvents) {
if (d.dataKind != "install_plan") continue;
auto stepsArr = extract_object(d.payloadJson, "steps");
// Walk objects within stepsArr (each {...}).
int depth = 0;
std::size_t start = 0;
for (std::size_t p = 0; p < stepsArr.size(); ++p) {
char c = stepsArr[p];
if (c == '{') {
if (depth == 0) start = p;
++depth;
} else if (c == '}') {
--depth;
if (depth == 0) {
auto obj = stepsArr.substr(start, p - start + 1);
PackageInstall pi;
pi.name = extract_string(obj, "name");
pi.version = extract_string(obj, "version");
pi.action = extract_string(obj, "action");
pi.url = extract_string(obj, "url");
pi.sha256 = extract_string(obj, "sha256");
if (!pi.name.empty()) plan.push_back(std::move(pi));
}
}
}
}
return plan;
}
std::expected<CallResult, CallError>
Fetcher::install(const std::vector<std::string>& targets, EventHandler* handler) {
auto args = make_targets_args(targets, /*yes=*/true);
return call("install_packages", args, handler);
}
std::expected<std::vector<Fetcher::RepoInfo>, CallError>
Fetcher::list_repos() {
auto r = call("list_repos", "{}");
if (!r) return std::unexpected(r.error());
std::vector<RepoInfo> repos;
for (auto& d : r->dataEvents) {
// payload format varies; styled_list with [name, url] pairs is common.
auto items = extract_object(d.payloadJson, "items");
// Walk pairs as in search().
std::size_t p = 0;
while (p < items.size()) {
if (items[p] == '[') {
++p;
while (p < items.size() && items[p] != '"') ++p;
std::string name;
if (p < items.size() && items[p] == '"') {
++p;
while (p < items.size() && items[p] != '"') {
if (items[p] == '\\' && p + 1 < items.size()) { p += 2; continue; }
name.push_back(items[p++]);
}
if (p < items.size()) ++p;
}
while (p < items.size() && items[p] != '"' && items[p] != ']') ++p;
std::string url;
if (p < items.size() && items[p] == '"') {
++p;
while (p < items.size() && items[p] != '"') {
if (items[p] == '\\' && p + 1 < items.size()) { p += 2; continue; }
url.push_back(items[p++]);
}
if (p < items.size()) ++p;
}
if (!name.empty()) {
repos.push_back({ std::move(name), std::move(url), false });
}
while (p < items.size() && items[p] != ']') ++p;
if (p < items.size()) ++p;
} else { ++p; }
}
}
return repos;
}
std::expected<void, CallError>
Fetcher::add_repo(std::string_view name, std::string_view url) {
auto args = std::format("{{\"name\":\"{}\",\"url\":\"{}\"}}", name, url);
auto r = call("add_repo", args);
if (!r) return std::unexpected(r.error());
if (r->exitCode != 0) {
std::string msg = "add_repo failed";
if (r->error) msg += ": " + r->error->message;
return std::unexpected(CallError{msg});
}
return {};
}
std::expected<void, CallError>
Fetcher::remove_repo(std::string_view name) {
auto args = std::format("{{\"name\":\"{}\"}}", name);
auto r = call("remove_repo", args);
if (!r) return std::unexpected(r.error());
if (r->exitCode != 0) {
std::string msg = "remove_repo failed";
if (r->error) msg += ": " + r->error->message;
return std::unexpected(CallError{msg});
}
return {};
}
// ─── Namespace-aware read_xpkg_lua (canonical, 0.0.10+) ─────────────
std::optional<std::string>
Fetcher::read_xpkg_lua(std::string_view ns, std::string_view shortName) const
{
if (shortName.empty()) return std::nullopt;
auto data = cfg_.xlingsHome() / "data";
if (!std::filesystem::exists(data)) return std::nullopt;
// Candidate filenames generated by compat module — canonical first,
// then fallback candidates (see compat.cppm for deprecation schedule).
auto filenames = mcpp::pm::compat::xpkg_lua_candidates(ns, shortName);
std::error_code ec;
for (auto& entry : std::filesystem::directory_iterator(data, ec)) {
if (!entry.is_directory()) continue;
auto pkgsDir = entry.path() / "pkgs";
if (!std::filesystem::exists(pkgsDir)) continue;
for (auto& fname : filenames) {
char first = static_cast<char>(std::tolower(
static_cast<unsigned char>(fname.front())));
auto candidate = pkgsDir / std::string(1, first) / fname;
if (std::filesystem::exists(candidate)) {
std::ifstream is(candidate);
std::stringstream ss; ss << is.rdbuf();
return ss.str();
}
}
}
return std::nullopt;
}
// ─── read_xpkg_lua from local path index ────────────────────────────
//
// For [indices] entries with `path = "/some/dir"`, read the xpkg .lua
// directly from the filesystem. The index layout follows the standard
// mcpp-index convention: <path>/pkgs/<first-letter>/<name>.lua
std::optional<std::string>
Fetcher::read_xpkg_lua_from_path(const std::filesystem::path& indexPath,
std::string_view shortName)
{
if (shortName.empty()) return std::nullopt;
auto pkgsDir = indexPath / "pkgs";
if (!std::filesystem::exists(pkgsDir)) return std::nullopt;
char first = static_cast<char>(std::tolower(
static_cast<unsigned char>(shortName.front())));
auto candidate = pkgsDir / std::string(1, first) / (std::string(shortName) + ".lua");
if (!std::filesystem::exists(candidate)) return std::nullopt;
std::ifstream is(candidate);
std::stringstream ss; ss << is.rdbuf();
return ss.str();
}
// ─── read_xpkg_lua from project-level data dir ─────────────────────
//
// For custom git indices cloned into .mcpp/data/, scan the data
// directory the same way the global read_xpkg_lua does.
std::optional<std::string>
Fetcher::read_xpkg_lua_from_project_data(const std::filesystem::path& projectDir,
std::string_view ns,
std::string_view shortName)
{
if (shortName.empty()) return std::nullopt;
auto data = projectDir / ".mcpp" / "data";
if (!std::filesystem::exists(data)) return std::nullopt;
auto filenames = mcpp::pm::compat::xpkg_lua_candidates(ns, shortName);
std::error_code ec;
for (auto& entry : std::filesystem::directory_iterator(data, ec)) {
if (!entry.is_directory()) continue;
auto pkgsDir = entry.path() / "pkgs";
if (!std::filesystem::exists(pkgsDir)) continue;
for (auto& fname : filenames) {
char first = static_cast<char>(std::tolower(
static_cast<unsigned char>(fname.front())));
auto candidate = pkgsDir / std::string(1, first) / fname;
if (std::filesystem::exists(candidate)) {
std::ifstream is(candidate);
std::stringstream ss; ss << is.rdbuf();
return ss.str();
}
}
}
return std::nullopt;
}
// ─── install_path from project-level data dir ──────────────────────
//
// For packages installed under .mcpp/data/xpkgs/ by custom git indices.
std::optional<std::filesystem::path>
Fetcher::install_path_from_project_data(const std::filesystem::path& projectDir,
std::string_view ns,
std::string_view shortName,
std::string_view version)
{
auto base = projectDir / ".mcpp" / "data" / "xpkgs";
if (!std::filesystem::exists(base)) return std::nullopt;
// Try canonical directory name: ns.shortName
auto qname = std::string(ns) + "." + std::string(shortName);
auto verdir = base / qname / std::string(version);
if (std::filesystem::exists(verdir)) return verdir;
// Try shortName alone.
verdir = base / std::string(shortName) / std::string(version);
if (std::filesystem::exists(verdir)) return verdir;
return std::nullopt;
}
// ─── Legacy read_xpkg_lua (COMPAT, remove in 1.0.0) ─────────────────
//
// Infers namespace from the raw package_name string and delegates to the
// namespace-aware overload.
std::optional<std::string>
Fetcher::read_xpkg_lua(std::string_view package_name) const
{
if (package_name.empty()) return std::nullopt;
auto resolved = mcpp::pm::compat::resolve_package_name(package_name, "");
return read_xpkg_lua(resolved.namespace_, resolved.shortName);
}
// --- resolve_xpkg_path ---
namespace {
struct ParsedTarget {
std::string indexName; // "xim", "mcpplibs", or "" (default)
std::string packageName;
std::string version;
};
ParsedTarget parse_target(std::string_view target, std::string_view defaultIndex) {
ParsedTarget r;
auto colon = target.find(':');
auto at = target.find('@');
if (at == std::string_view::npos) {
// No version → caller may need to default
if (colon != std::string_view::npos) {
r.indexName = std::string(target.substr(0, colon));
r.packageName = std::string(target.substr(colon + 1));
} else {
r.indexName = std::string(defaultIndex);
r.packageName = std::string(target);
}
return r;
}
r.version = std::string(target.substr(at + 1));
if (colon != std::string_view::npos && colon < at) {
r.indexName = std::string(target.substr(0, colon));
r.packageName = std::string(target.substr(colon + 1, at - colon - 1));
} else {
r.indexName = std::string(defaultIndex);
r.packageName = std::string(target.substr(0, at));
}
return r;
}
} // namespace
std::expected<Fetcher::XpkgPayload, CallError>
Fetcher::resolve_xpkg_path(std::string_view target,
bool autoInstall,
EventHandler* handler)
{
// Default to xim namespace for tools/toolchain. Modular libs use
// mcpplibs but consumers (cli) typically pass "<idx>:<name>@<ver>"
// explicitly anyway.
auto parsed = parse_target(target, "xim");
if (parsed.packageName.empty() || parsed.version.empty()) {
return std::unexpected(CallError{
std::format("invalid xpkg target '{}': expected `<name>@<version>`",
target)});
}
auto base = cfg_.xlingsHome() / "data" / "xpkgs";
std::filesystem::path verdir = base
/ std::format("{}-x-{}", parsed.indexName, parsed.packageName)
/ parsed.version;
auto fill_payload = [&](XpkgPayload& p) {
p.binDir = p.root / "bin";
p.libDir = p.root / "lib";
p.includeDir = p.root / "include";
p.hasBin = std::filesystem::exists(p.binDir);
p.hasLib = std::filesystem::exists(p.libDir);
p.hasInclude = std::filesystem::exists(p.includeDir);
// sourceDir: prefer single subdir (extracted tarball), else root.
std::error_code ec;
std::vector<std::filesystem::path> subs;
if (std::filesystem::is_directory(p.root)) {
for (auto& e : std::filesystem::directory_iterator(p.root, ec)) {
if (e.is_directory()) subs.push_back(e.path());
}
}
p.sourceDir = (subs.size() == 1) ? subs.front() : p.root;
};
auto resolve = [&]() -> std::expected<XpkgPayload, CallError> {
// Workaround: xlings may extract large packages (e.g. LLVM) into its
// global data dir instead of the mcpp sandbox, because the extraction
// subprocess doesn't always inherit XLINGS_HOME. Detect this and copy
// the payload into the sandbox so mcpp remains self-contained.
// Originally Windows-only; extended to all platforms for the same
// reason (xlings subprocess XLINGS_HOME propagation is unreliable).
if (!std::filesystem::exists(verdir)) {
const char* xhome = nullptr;
#if defined(_WIN32)
xhome = std::getenv("USERPROFILE");
#endif
if (!xhome) xhome = std::getenv("HOME");
if (xhome) {
// xlings stores xpkgs at <home>/.xlings/data/xpkgs/ or
// <home>/.xlings/subos/default/data/xpkgs/
auto pkgDir = verdir.parent_path().filename().string();
auto verName = verdir.filename().string();
std::filesystem::path candidates[] = {
std::filesystem::path(xhome) / ".xlings" / "data" / "xpkgs" / pkgDir / verName,
std::filesystem::path(xhome) / ".xlings" / "subos" / "default" / "data" / "xpkgs" / pkgDir / verName,
};
for (auto& src : candidates) {
std::error_code ec;
if (std::filesystem::exists(src, ec) && std::filesystem::is_directory(src, ec)) {
std::filesystem::create_directories(verdir.parent_path(), ec);
std::filesystem::copy(src, verdir,
std::filesystem::copy_options::recursive
| std::filesystem::copy_options::overwrite_existing, ec);
if (!ec) break;
}
}
}
}
if (!std::filesystem::exists(verdir)) {
return std::unexpected(CallError{
std::format("xpkg payload missing: {}", verdir.string())});
}
XpkgPayload payload;
// For xim packages (gcc, cmake, ...) the version dir IS the root.
// For mcpplibs packages the version dir contains an extracted
// tarball subdirectory; we treat the wrapper subdir as the root
// when its content includes bin/ or include/.
std::error_code ec;
std::vector<std::filesystem::path> subs;
for (auto& e : std::filesystem::directory_iterator(verdir, ec)) {
if (e.is_directory()) subs.push_back(e.path());
}
// If verdir directly contains bin/ or include/ → it's the root.
// Otherwise prefer the unique subdirectory.
bool verdir_is_root = std::filesystem::exists(verdir / "bin")
|| std::filesystem::exists(verdir / "include")
|| std::filesystem::exists(verdir / "lib");
payload.root = verdir_is_root ? verdir
: (subs.size() == 1) ? subs.front()
: verdir;
fill_payload(payload);
return payload;
};
auto p = resolve();
if (p) return *p;
if (!autoInstall) {
return std::unexpected(p.error());
}
// Trigger install via xlings.
std::vector<std::string> targets {
std::format("{}:{}@{}", parsed.indexName, parsed.packageName, parsed.version)
};
auto inst = install(targets, handler);
if (!inst) return std::unexpected(inst.error());
if (inst->exitCode != 0) {
std::string err = std::format(
"xlings install of '{}:{}@{}' failed (exit {})",
parsed.indexName, parsed.packageName, parsed.version, inst->exitCode);
if (inst->error) err += ": " + inst->error->message;
return std::unexpected(CallError{err});
}
return resolve();
}
// ─── Namespace-aware install_path (canonical, 0.0.10+) ──────────────
std::optional<std::filesystem::path>
Fetcher::install_path(std::string_view ns, std::string_view shortName,
std::string_view version) const
{
// M6.x: install_path returns the verdir (untouched extract root).
// Layout discrimination is done by the caller via the xpkg.lua's
// `mcpp = "<glob path>"` (Form A pointer) or `mcpp = { ... }` (Form B
// inline) field.
auto base = cfg_.xlingsHome() / "data" / "xpkgs";
if (!std::filesystem::exists(base)) return std::nullopt;
auto try_dir = [&](std::string_view dirName) -> std::optional<std::filesystem::path> {
auto verdir = base / std::string(dirName) / std::string(version);
return std::filesystem::exists(verdir)
? std::optional<std::filesystem::path>{verdir}
: std::nullopt;
};
// Candidate directory names generated by compat module — canonical first,
// then fallback candidates (see compat.cppm for deprecation schedule).
auto candidates = mcpp::pm::compat::install_dir_candidates(
ns, shortName, cfg_.defaultIndex);
for (auto& dirName : candidates) {
if (auto p = try_dir(dirName)) return *p;
}
// Last-resort fallback scan (COMPAT, remove in 1.0.0): walk xpkgs/ for
// any directory ending with -x-<qname> or -x-<shortName>.
auto qname = mcpp::pm::compat::qualified_name(ns, shortName);
std::error_code ec;
std::string suffix1 = std::format("-x-{}", qname);
std::string suffix2 = std::format("-x-{}", shortName);
for (auto& entry : std::filesystem::directory_iterator(base, ec)) {
if (!entry.is_directory()) continue;
auto dirname = entry.path().filename().string();
if (dirname.ends_with(suffix1)) {
if (auto p = try_dir(dirname)) return *p;
}
if (suffix2 != suffix1 && dirname.ends_with(suffix2)) {
if (auto p = try_dir(dirname)) return *p;
}
}
return std::nullopt;
}
// ─── Legacy install_path (COMPAT, remove in 1.0.0) ──────────────────
//
// Infers namespace from the raw name string and delegates to the
// namespace-aware overload.
std::optional<std::filesystem::path>
Fetcher::install_path(std::string_view name, std::string_view version) const
{
auto resolved = mcpp::pm::compat::resolve_package_name(name, "");
return install_path(resolved.namespace_, resolved.shortName, version);
}
} // namespace mcpp::pm