-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxpkg-lua-stdlib.cppm
More file actions
2435 lines (2203 loc) · 85.8 KB
/
Copy pathxpkg-lua-stdlib.cppm
File metadata and controls
2435 lines (2203 loc) · 85.8 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
// Auto-generated by xmake before_build — do not edit manually
module;
export module mcpplibs.xpkg.lua_stdlib;
import std;
export namespace mcpplibs::xpkg::detail {
inline constexpr std::string_view prelude_lua = R"__LUA__(
-- prelude.lua: xmake compatibility layer + import() for libxpkg runtime
-- Loaded by PackageExecutor before any package script.
-- _LIBXPKG_MODULES is populated by C++ before this file runs
_LIBXPKG_MODULES = _LIBXPKG_MODULES or {}
-- Save Lua's built-in package.config before xpkg scripts overwrite `package` global
local _PATH_SEP = package.config:sub(1,1)
-- import(): maps "xim.libxpkg.X" to preloaded modules
-- Also registers module as global variable (xmake compat: bare import() sets global)
function import(mod_path)
local name = mod_path:match("xim%.libxpkg%.(.+)")
if name and _LIBXPKG_MODULES[name] then
_G[name] = _LIBXPKG_MODULES[name]
return _LIBXPKG_MODULES[name]
end
-- pkgindex custom modules: import("xim.pkgindex.<name>")
-- Loads <pkgindex_dir>/libs/<name>.lua from the package index repository.
-- Modules are cached in _LIBXPKG_MODULES after first load.
local pkgindex_mod = mod_path:match("xim%.pkgindex%.(.+)")
if pkgindex_mod then
-- Check cache first
if _LIBXPKG_MODULES[pkgindex_mod] then
_G[pkgindex_mod] = _LIBXPKG_MODULES[pkgindex_mod]
return _LIBXPKG_MODULES[pkgindex_mod]
end
-- _PKGINDEX_DIR is set early (before L_dofile) so top-level imports work;
-- _RUNTIME.pkgindex_dir is set later by inject_context for hook calls.
local pkgindex_dir = _PKGINDEX_DIR
or (_RUNTIME and _RUNTIME.pkgindex_dir)
if pkgindex_dir and pkgindex_dir ~= "" then
local mod_file = pkgindex_dir .. "/libs/" .. pkgindex_mod .. ".lua"
local loader = loadfile(mod_file)
if loader then
local ok, mod = pcall(loader)
if ok and mod then
_LIBXPKG_MODULES[pkgindex_mod] = mod
_G[pkgindex_mod] = mod
return mod
end
end
end
end
-- Stub for unknown imports (platform, base.runtime, etc.)
local log = _LIBXPKG_MODULES and _LIBXPKG_MODULES["log"]
if log then log.debug("unknown module '%s', returning stub", mod_path) end
local short = mod_path:match("[^.]+$") or mod_path
local function make_proxy()
return setmetatable({}, {
__index = function(_, k) return make_proxy() end,
__call = function() return make_proxy() end,
__tostring = function() return '' end,
__concat = function(a, b) return tostring(a) .. tostring(b) end,
})
end
local stub = setmetatable({}, {
__index = function(_, k) return make_proxy() end,
})
_G[short] = stub
return stub
end
-- os.* extensions (xmake compat)
os.isfile = function(p)
-- io.open succeeds on directories on Linux (fopen quirk), so also check it's not a dir
local f = io.open(p, "r")
if not f then return false end
f:close()
-- Reject directories: try reading 0 bytes; directories fail with "Is a directory"
local f2 = io.open(p, "rb")
if not f2 then return false end
local ok, _ = f2:read(0)
f2:close()
-- read(0) returns "" on regular files, nil on directories
return ok ~= nil
end
os.isdir = function(p)
local sep = _PATH_SEP
if sep == "\\" then
local ret = os.execute('if exist "' .. p .. '\\" exit 0')
return ret == 0 or ret == true
else
local ret = os.execute('[ -d "' .. p .. '" ]')
return ret == 0 or ret == true
end
end
os.host = function()
return _RUNTIME and _RUNTIME.platform or "linux"
end
os.trymv = function(src, dst)
-- If dst is an existing directory, move src INTO it (unix mv semantics)
if os.isdir(dst) then
local fname = src:match("[^/\\]+$") or src
dst = dst:gsub("[/\\]+$", "") .. "/" .. fname
end
local ok = pcall(os.rename, src, dst)
if ok then return true end
-- Cross-device or directory: fallback to shell mv
local ret = os.execute('mv "' .. src .. '" "' .. dst .. '" 2>/dev/null')
if ret == 0 or ret == true then return true end
-- Last resort: file copy + remove (files only)
local inf = io.open(src, "rb")
if not inf then return false end
local content = inf:read("*a"); inf:close()
local outf = io.open(dst, "wb")
if not outf then return false end
outf:write(content); outf:close()
local rm_ok = pcall(os.remove, src)
return rm_ok
end
os.mv = function(src, dst) return os.trymv(src, dst) end
os.cp = function(src, dst, opts)
-- opts accepted for xmake compat but ignored (cp -a already preserves symlinks)
-- Try shell cp first (handles directories, symlinks, etc.)
local sep = _PATH_SEP
if sep ~= "\\" then
local ret = os.execute('cp -a "' .. src .. '" "' .. dst .. '" 2>/dev/null')
if ret == 0 or ret == true then return true end
end
-- Fallback: file copy
local inf = io.open(src, "rb")
if not inf then return false end
local content = inf:read("*a"); inf:close()
local outf = io.open(dst, "wb")
if not outf then return false end
outf:write(content); outf:close()
return true
end
-- POSIX: shell-escape a glob pattern, keeping glob meta-chars raw so the
-- shell still expands them. Quoting the whole pattern (e.g. "/tmp/x/v*")
-- suppresses globbing — `ls -d "/tmp/x/v*"` would only match a file
-- literally named `v*`. Instead we backslash-escape characters that need
-- shell quoting (whitespace, $, `, ', ", redirects, etc.) and leave glob
-- meta (* ? [ ] ~) untouched.
local _SHELL_META_NO_GLOB = " \t\r\n$`'\"<>|&;()!\\"
local function _shell_glob_escape(s)
local out = {}
for i = 1, #s do
local c = s:sub(i, i)
if _SHELL_META_NO_GLOB:find(c, 1, true) then
out[#out+1] = "\\"
end
out[#out+1] = c
end
return table.concat(out)
end
os.dirs = function(pattern)
local result = {}
local sep = _PATH_SEP
local cmd
if sep == "\\" then
-- cmd.exe `dir` does its own wildcard expansion on the pattern
-- argument, so quoting is safe and required for paths with spaces.
cmd = 'dir /B /AD "' .. pattern .. '" 2>nul'
else
-- POSIX `ls` does NOT expand globs itself; the shell does. Escape
-- shell metachars but leave glob meta raw so expansion still works.
cmd = 'ls -d ' .. _shell_glob_escape(pattern) .. ' 2>/dev/null'
end
local f = io.popen(cmd)
if f then
for line in f:lines() do
local clean = line:gsub("[\r\n]+$", "") -- strip CRLF
if clean ~= "" and os.isdir(clean) then
table.insert(result, clean)
end
end
f:close()
end
return result
end
os.sleep = function(ms) end -- stub
os.cd = function(dir)
if not dir then return false end
-- Fallback: pure Lua cannot chdir; C++ override replaces this after prelude
_CURRENT_DIR = dir
return true
end
os.iorun = function(cmd)
local f = io.popen(cmd .. " 2>/dev/null")
if not f then return "" end
local output = f:read("*a")
f:close()
return output or ""
end
os.setenv = function(k, v)
if _PATH_SEP == "\\" then
os.execute(string.format('setx %s "%s"', k, v))
else
_ENV_OVERRIDES = _ENV_OVERRIDES or {}
_ENV_OVERRIDES[k] = v
end
end
os.addenv = function(k, v)
if _PATH_SEP == "\\" then
local cur = os.getenv(k) or ""
os.execute(string.format('setx %s "%s"', k, cur ~= "" and (cur .. ";" .. v) or v))
else
_ENV_OVERRIDES = _ENV_OVERRIDES or {}
local cur = _ENV_OVERRIDES[k] or os.getenv(k) or ""
_ENV_OVERRIDES[k] = cur ~= "" and (cur .. ":" .. v) or v
end
end
os.exec = function(cmd)
if _ENV_OVERRIDES and _PATH_SEP ~= "\\" then
local prefix = ""
for k, v in pairs(_ENV_OVERRIDES) do
prefix = prefix .. string.format('%s="%s" ', k, v)
end
if prefix ~= "" then cmd = prefix .. cmd end
end
return os.execute(cmd)
end
os.tryrm = function(p)
if not p then return false end
local sep = _PATH_SEP
local cmd
if sep == "\\" then
cmd = 'rmdir /s /q "' .. p .. '" 2>nul'
else
cmd = 'rm -rf "' .. p .. '" 2>/dev/null'
end
os.execute(cmd)
return true
end
os.mkdir = function(p)
if not p then return false end
local sep = _PATH_SEP
local cmd
if sep == "\\" then
cmd = 'mkdir "' .. p .. '" 2>nul'
else
cmd = 'mkdir -p "' .. p .. '" 2>/dev/null'
end
os.execute(cmd)
return true
end
-- path module
path = {}
path.join = function(...)
local parts = {...}
local sep = "/"
local result = parts[1] or ""
for i = 2, #parts do
if parts[i] and parts[i] ~= "" then
result = result:gsub("[/\\]+$", "") .. sep .. parts[i]
end
end
return result
end
path.filename = function(p)
return (p or ""):match("[^/\\]+$") or ""
end
path.directory = function(p)
return (p or ""):match("^(.*)[/\\][^/\\]+$") or ""
end
path.is_absolute = function(p)
return (p or ""):sub(1,1) == "/" or (p or ""):match("^%a:[/\\]") ~= nil
end
-- io extensions
io.readfile = function(p)
local f = io.open(p, "r")
if not f then return nil end
local content = f:read("*a"); f:close()
return content
end
io.writefile = function(p, content)
local f = io.open(p, "w")
if not f then return false end
f:write(content); f:close()
return true
end
-- cprint: strip ${color} markers, fallback to print
cprint = function(fmt, ...)
if type(fmt) == "string" then
fmt = fmt:gsub("%${%w+}", "")
local ok, msg = pcall(string.format, fmt, ...)
print(ok and msg or fmt)
else
print(fmt)
end
end
-- string.split: split string by separator
if not string.split then
function string.split(s, sep, plain)
local result = {}
local i = 1
while true do
local j, k = s:find(sep, i, plain)
if not j then
table.insert(result, s:sub(i))
break
end
table.insert(result, s:sub(i, j-1))
i = k + 1
end
return result
end
end
-- string:trim(): remove leading/trailing whitespace
if not string.trim then
function string.trim(s)
return s:match("^%s*(.-)%s*$") or s
end
end
-- xmake compat globals
function is_host(name)
local host = _RUNTIME and _RUNTIME.platform or os.host()
return host == name
end
format = string.format
raise = function(msg) error(msg or "raise called", 2) end
-- string.replace: xmake compat (plain text replacement)
if not string.replace then
function string.replace(s, old, new, opts)
-- Plain text replacement (not pattern); opts accepted for xmake compat but ignored
local result = s
local i = 1
while true do
local pos = result:find(old, i, true)
if not pos then break end
result = result:sub(1, pos - 1) .. new .. result:sub(pos + #old)
i = pos + #new
end
return result
end
end
-- try/catch: simulates xmake's try { function, catch { function } } syntax
function try(block)
local fn = block[1]
local catch_block = block.catch
local ok, result = pcall(fn)
if not ok then
if catch_block and catch_block[1] then
catch_block[1](result)
end
return nil
end
return result
end
)__LUA__";
inline constexpr std::string_view log_lua = R"__LUA__(
-- xim.libxpkg.log: logging API for xpkg scripts
local M = {}
local PREFIX = "[xim:xpkg]: "
-- Log levels: 0=debug, 1=info, 2=warn, 3=error, 4=silent
local LEVEL_DEBUG = 0
local LEVEL_INFO = 1
local LEVEL_WARN = 2
local LEVEL_ERROR = 3
local _level = LEVEL_INFO -- default: show info and above
local function _log(text, ...)
if not text then return end
local ok, msg = pcall(string.format, text, ...)
msg = ok and msg or tostring(text)
msg = msg:gsub("%${%w+}", "")
io.write(PREFIX .. msg .. "\n")
io.flush()
end
function M.debug(text, ...)
if _level <= LEVEL_DEBUG then _log(text, ...) end
end
function M.info(text, ...)
if _level <= LEVEL_INFO then _log(text, ...) end
end
function M.warn(text, ...)
if _level <= LEVEL_WARN then _log("[WARN] " .. (text or ""), ...) end
end
function M.error(text, ...)
if _level <= LEVEL_ERROR then _log("[ERROR] " .. (text or ""), ...) end
end
-- Set log level: "debug", "info", "warn", "error", "silent"
function M.set_level(level)
if level == "debug" or level == 0 then _level = LEVEL_DEBUG
elseif level == "info" or level == 1 then _level = LEVEL_INFO
elseif level == "warn" or level == 2 then _level = LEVEL_WARN
elseif level == "error" or level == 3 then _level = LEVEL_ERROR
elseif level == "silent" or level == 4 then _level = 4
end
end
function M.get_level()
return _level
end
return M
)__LUA__";
inline constexpr std::string_view pkginfo_lua = R"__LUA__(
-- xim.libxpkg.pkginfo: package info API reading from _RUNTIME global
local M = {}
local function _get_log()
return _LIBXPKG_MODULES and _LIBXPKG_MODULES["log"]
end
function M.name() return _RUNTIME and _RUNTIME.pkg_name or nil end
function M.version() return _RUNTIME and _RUNTIME.version or nil end
function M.install_file() return _RUNTIME and _RUNTIME.install_file or nil end
function M.deps_list() return (_RUNTIME and _RUNTIME.deps_list) or {} end
local function _ends_with(s, suffix)
return suffix == "" or s:sub(-#suffix) == suffix
end
local function _parse_namespace(name)
local ns, bare = name:match("^([^:]+):(.+)$")
if ns then return ns, bare end
return nil, name
end
local function _match_store_name(dirname, ns, bare)
if ns then
-- namespace specified: exact match "ns-x-bare"
return dirname == ns .. "-x-" .. bare
else
-- no namespace: match "bare" or "*-x-bare"
return dirname == bare or _ends_with(dirname, "-x-" .. bare)
end
end
local function _scan_dir(base, ns, bare, dep_version)
if not base or not os.isdir(base) then return nil end
local dirs = os.dirs(path.join(base, "*")) or {}
for _, dep_root in ipairs(dirs) do
local dirname = path.filename(dep_root)
if _match_store_name(dirname, ns, bare) then
local ver = dep_version
if not ver then
local vers = os.dirs(path.join(dep_root, "*")) or {}
table.sort(vers)
if #vers > 0 then ver = path.filename(vers[#vers]) end
end
if ver then
local install_dir = path.join(dep_root, ver)
if os.isdir(install_dir) then return install_dir end
end
end
end
return nil
end
local function _resolve_dep_via_scan(dep_name, dep_version)
local log = _get_log()
local ns, bare = _parse_namespace(dep_name)
if log then log.debug("scan dep=%s ns=%s bare=%s ver=%s",
dep_name, tostring(ns), bare, tostring(dep_version)) end
-- 1. Search xpkg_dir (lua package files directory)
local xpkg_dir = _RUNTIME and _RUNTIME.xpkg_dir
if log then log.debug("step1 xpkg_dir=%s", tostring(xpkg_dir)) end
local result = _scan_dir(xpkg_dir, ns, bare, dep_version)
if result then if log then log.debug("found via step1") end; return result end
-- 2. Search xpkgs install root (install_dir's grandparent)
if _RUNTIME and _RUNTIME.install_dir then
local xpkgs_root = path.directory(path.directory(_RUNTIME.install_dir))
if log then log.debug("step2 xpkgs_root=%s", tostring(xpkgs_root)) end
result = _scan_dir(xpkgs_root, ns, bare, dep_version)
if result then if log then log.debug("found via step2") end; return result end
end
-- 3. Search project xpkgs (handles global-pkg depending on project-local pkg)
local proj_data = _RUNTIME and _RUNTIME.project_data_dir
if log then log.debug("step3 project_data_dir=%s", tostring(proj_data)) end
if proj_data and proj_data ~= "" then
local proj_xpkgs = path.join(proj_data, "xpkgs")
if log then log.debug("step3 proj_xpkgs=%s exists=%s",
proj_xpkgs, tostring(os.isdir(proj_xpkgs))) end
result = _scan_dir(proj_xpkgs, ns, bare, dep_version)
if result then if log then log.debug("found via step3") end; return result end
end
if log then log.debug("scan: not found") end
return nil
end
-- Try xvm registry: for "ns:name", try "ns-name" first, then bare "name"
local function _resolve_dep_via_xvm(dep_name, dep_version)
local log = _get_log()
local ok_xvm, xvm_mod = pcall(require, "xim.libxpkg.xvm")
if not ok_xvm or not xvm_mod then
xvm_mod = _LIBXPKG_MODULES and _LIBXPKG_MODULES["xvm"]
end
if not xvm_mod then
if log then log.debug("xvm: module not available") end
return nil
end
local ns, bare = _parse_namespace(dep_name)
local candidates = ns and {ns .. "-" .. bare, bare} or {bare}
if log then log.debug("xvm candidates: %s", table.concat(candidates, ", ")) end
for _, xvm_name in ipairs(candidates) do
local info = xvm_mod.info(xvm_name, dep_version)
if log then log.debug("xvm.info(%s) = %s",
xvm_name, info and ("SPath=" .. tostring(info["SPath"])) or "nil") end
if info and info["SPath"] and info["SPath"] ~= "" then
local spath = info["SPath"]
local pver = (info["Version"] or dep_version or ""):gsub("([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1")
if pver ~= "" then
local head = spath:match("^(.*)" .. pver)
if head then
return path.join(head:gsub("[/\\]+$", ""), info["Version"] or dep_version)
end
end
end
end
if log then log.debug("xvm: not found") end
return nil
end
function M.dep_install_dir(dep_name, dep_version)
local result = _resolve_dep_via_scan(dep_name, dep_version)
if result then return result end
return _resolve_dep_via_xvm(dep_name, dep_version)
end
function M.install_dir(pkgname, pkgversion)
if not pkgname then
return _RUNTIME and _RUNTIME.install_dir or nil
end
local dir = M.dep_install_dir(pkgname, pkgversion)
if dir then return dir end
local log = _get_log()
if log then log.error("cannot get install dir for %s@%s",
tostring(pkgname), tostring(pkgversion or "latest")) end
return nil
end
-- ─────────────────────────────────────────────────────────────────────
-- build_dep API
-- ─────────────────────────────────────────────────────────────────────
-- Returns metadata about a build-time dep available to the current
-- install hook. Build deps are payloads xlings ensured are present in
-- the xpkgs store but did NOT activate in subos workspace. Use this
-- API instead of relying on PATH / shims when the consumer needs an
-- ABSOLUTE PATH or wants explicit version selection independent of
-- the user's active workspace.
--
-- local gcc = pkginfo.build_dep("gcc")
-- -- gcc.path : install_dir of the chosen build dep version
-- -- gcc.bin : <install_dir>/bin
-- -- gcc.version : resolved version string
--
-- Resolution order:
-- 1. Env var XLINGS_BUILDDEP_<UPPER_NAME>_PATH (injected by the
-- xlings installer when the consumer's `build` deps were resolved
-- to a concrete version).
-- 2. Fallback: scan xpkgs the same way `dep_install_dir` does.
-- Returns highest available version when version is omitted.
--
-- Returns nil if the build dep is not available.
function M.build_dep(dep_name, dep_version)
local log = _get_log()
if not dep_name or dep_name == "" then return nil end
local function _upper(s) return (s:gsub("[^%w]", "_")):upper() end
local env_key = "XLINGS_BUILDDEP_" .. _upper(dep_name) .. "_PATH"
local env_path = os.getenv(env_key)
local install_dir
if env_path and env_path ~= "" and os.isdir(env_path) then
install_dir = env_path
if log then log.debug("build_dep %s -> %s (via %s)",
dep_name, env_path, env_key) end
else
install_dir = M.dep_install_dir(dep_name, dep_version)
if log then log.debug("build_dep %s -> %s (via scan)",
dep_name, tostring(install_dir)) end
end
if not install_dir then return nil end
local resolved_ver = dep_version
if not resolved_ver or resolved_ver == "" then
-- The install_dir's leaf is the version (xpkgs/<store>/<ver>).
resolved_ver = path.filename(install_dir)
end
return {
path = install_dir,
bin = path.join(install_dir, "bin"),
include = path.join(install_dir, "include"),
lib = path.join(install_dir, "lib"),
version = resolved_ver,
}
end
-- Convenience: prepend every build dep's `bin/` to PATH for the
-- duration of the callback, then restore. Lets install hooks call
-- bare `gcc` / `patchelf` etc and pick up the build-dep version
-- without the hook needing to splice paths manually. The xlings
-- installer also pre-injects PATH globally for the hook subprocess,
-- so most hooks won't need this — useful only when an install hook
-- spawns sub-processes that need a different PATH.
function M.with_build_deps_on_path(build_dep_names, fn)
local log = _get_log()
local original_path = os.getenv("PATH") or ""
local extra = {}
for _, n in ipairs(build_dep_names or {}) do
local d = M.build_dep(n)
if d and d.bin and os.isdir(d.bin) then
table.insert(extra, d.bin)
elseif log then
log.warn("with_build_deps_on_path: %s not available", n)
end
end
if #extra == 0 then return fn() end
local new_path = table.concat(extra, path.envsep()) .. path.envsep() .. original_path
os.setenv("PATH", new_path)
local ok, err = pcall(fn)
os.setenv("PATH", original_path)
if not ok then error(err) end
end
return M
)__LUA__";
inline constexpr std::string_view system_lua = R"__LUA__(
-- xim.libxpkg.system: system operations API
local M = {}
function M.exec(cmd, opt)
opt = opt or {}
local retries = opt.retry or 0
local attempts = retries + 1
for i = 1, attempts do
local ret = os.execute(cmd)
if ret == 0 or ret == true then return end
if i == attempts then
error("exec failed after " .. attempts .. " attempt(s): " .. tostring(cmd))
end
end
end
function M.rundir() return _RUNTIME and _RUNTIME.run_dir or nil end
function M.xpkgdir() return _RUNTIME and _RUNTIME.xpkg_dir or nil end
function M.bindir() return _RUNTIME and _RUNTIME.bin_dir or nil end
function M.xpkg_args() return (_RUNTIME and _RUNTIME.args) or {} end
function M.subos_sysrootdir() return _RUNTIME and _RUNTIME.subos_sysrootdir or nil end
function M.run_in_script(content, admin)
local tmpfile = os.tmpname()
-- write content to temp file
if not io.writefile(tmpfile, content) then
error("run_in_script: failed to write temp script")
end
local ok, err = pcall(function()
os.execute("chmod +x " .. tmpfile)
local prefix = (admin == true) and "sudo " or ""
local ret = os.execute(prefix .. tmpfile)
if ret ~= 0 and ret ~= true then
error("script failed with code: " .. tostring(ret))
end
end)
os.remove(tmpfile) -- always cleanup
if not ok then error(err) end
end
function M.unix_api()
return {
append_to_shell_profile = function(config)
if not config then return end
if type(config) == "string" then
config = { posix = config, fish = config }
end
local profile_dir = _RUNTIME.run_dir or "/tmp"
local posix = path.join(profile_dir, "xlings-profile.sh")
local fish = path.join(profile_dir, "xlings-profile.fish")
if config.posix and os.isfile(posix) then
local cur = io.readfile(posix) or ""
if not cur:find(config.posix, 1, true) then
io.writefile(posix, cur .. "\n" .. config.posix)
end
end
if config.fish and os.isfile(fish) then
local cur = io.readfile(fish) or ""
if not cur:find(config.fish, 1, true) then
io.writefile(fish, cur .. "\n" .. config.fish)
end
end
end
}
end
return M
)__LUA__";
inline constexpr std::string_view xvm_lua = R"__LUA__(
-- xim.libxpkg.xvm: version management integration (collects ops for C++ processing)
local M = {}
local function _get_log()
return _LIBXPKG_MODULES and _LIBXPKG_MODULES["log"]
end
_XVM_OPS = _XVM_OPS or {}
function M.add(name, opt)
opt = opt or {}
local entry = {
op = "add",
name = name,
version = opt.version or (_RUNTIME and _RUNTIME.version) or "",
bindir = opt.bindir or (_RUNTIME and _RUNTIME.install_dir) or "",
alias = opt.alias or "",
type = opt.type or "",
filename = opt.filename or "",
binding = opt.binding or "",
envs = opt.envs or nil,
}
local log = _get_log()
if log then log.debug("xvm add %s version=%s", name, entry.version) end
table.insert(_XVM_OPS, entry)
end
function M.remove(name, version)
local log = _get_log()
if log then log.debug("xvm remove %s %s", name, version or "") end
table.insert(_XVM_OPS, {op = "remove", name = name, version = version or ""})
end
function M.use(name, version)
-- stub: version switching handled by C++ side
end
-- Load VersionDB from config files (global + project)
local _versions_cache = nil
local function _load_versions()
if _versions_cache then return _versions_cache end
local ok_json, json_mod = pcall(require, "xim.libxpkg.json")
if not ok_json then
json_mod = _LIBXPKG_MODULES and _LIBXPKG_MODULES["json"]
end
if not json_mod then return nil end
local function load_file(config_path)
local f = io.open(config_path, "r")
if not f then return nil end
local content = f:read("*a"); f:close()
if not content or content == "" then return nil end
local ok, data = pcall(json_mod.decode, content)
if not ok or type(data) ~= "table" then return nil end
return data.versions or nil
end
local merged = {}
-- 1. Load global versions: prefer XLINGS_HOME, fallback to ~/.xlings
local xlings_home = os.getenv("XLINGS_HOME")
if not xlings_home or xlings_home == "" then
local home = os.getenv("HOME") or os.getenv("USERPROFILE") or ""
xlings_home = home .. "/.xlings"
end
local global_versions = load_file(xlings_home .. "/.xlings.json")
if global_versions then
for k, v in pairs(global_versions) do merged[k] = v end
end
-- 2. Load project versions (project_data_dir is 2 levels below project root)
if _RUNTIME and _RUNTIME.project_data_dir and _RUNTIME.project_data_dir ~= "" then
local project_dir = path.directory(path.directory(_RUNTIME.project_data_dir))
local project_versions = load_file(path.join(project_dir, ".xlings.json"))
if project_versions then
for k, v in pairs(project_versions) do merged[k] = v end
end
end
_versions_cache = merged
return _versions_cache
end
function M.has(name, version)
-- Check pending ops first (current session adds)
for _, entry in ipairs(_XVM_OPS) do
if entry.op == "add" and entry.name == name then return true end
end
-- Check persisted VersionDB
local versions = _load_versions()
if not versions then return false end
local vinfo = versions[name]
if not vinfo then return false end
if not version or version == "" then return true end
if vinfo.versions then
for ver_key, _ in pairs(vinfo.versions) do
if ver_key == version then return true end
end
end
return false
end
function M.info(name, version)
local versions = _load_versions()
if not versions then return nil end
local vinfo = versions[name]
if not vinfo or not vinfo.versions then return nil end
-- Find matching version
local vdata = nil
local matched_version = version or ""
if version and version ~= "" then
vdata = vinfo.versions[version]
end
if not vdata then
-- Try first available version
for ver_key, ver_val in pairs(vinfo.versions) do
vdata = ver_val
matched_version = ver_key
break
end
end
if not vdata then return nil end
local info_table = {
Name = name,
Version = matched_version,
Type = vinfo.type or "program",
Program = vinfo.filename or name,
SPath = vdata.path or "",
TPath = vdata.path or "",
Alias = vdata.alias or nil,
Envs = vdata.envs or nil,
}
return info_table
end
-- Deprecated: use log.set_level() instead. Kept for backward compat.
function M.log_tag(enable)
return enable
end
--- Unified registration of programs, libraries, and headers
-- @param name package name (root node in binding tree)
-- @param opt table with:
-- install_dir install root directory (default _RUNTIME.install_dir)
-- version version string (default _RUNTIME.version)
-- bindir programs directory (relative or absolute, default "bin")
-- libdir library directory (relative or absolute, optional)
-- includedir header directory (relative or absolute, optional)
-- programs list of program names (optional)
-- libs list of library filenames (optional)
function M.setup(name, opt)
opt = opt or {}
local install_dir = opt.install_dir or (_RUNTIME and _RUNTIME.install_dir) or ""
local version = opt.version or (_RUNTIME and _RUNTIME.version) or ""
local binding = name .. "@" .. version
local function resolve(dir)
if not dir then return nil end
if path.is_absolute(dir) then return dir end
return path.join(install_dir, dir)
end
-- 1. Register root node
M.add(name)
-- 2. Batch register programs
if opt.programs then
local bindir = resolve(opt.bindir or "bin")
for _, prog in ipairs(opt.programs) do
M.add(prog, { bindir = bindir, binding = binding })
end
end
-- 3. Batch register libraries
if opt.libs then
local libdir = resolve(opt.libdir or "lib")
for _, lib in ipairs(opt.libs) do
M.add(lib, {
type = "lib", bindir = libdir,
alias = lib, filename = lib,
binding = binding,
})
end
end
-- 4. Header directory -> C++ side creates symlinks to sysroot
if opt.includedir then
local includedir = resolve(opt.includedir)
table.insert(_XVM_OPS, { op = "headers", includedir = includedir })
end
end
--- Unified unregistration
function M.teardown(name, opt)
opt = opt or {}
M.remove(name)
if opt.programs then
for _, prog in ipairs(opt.programs) do M.remove(prog) end
end
if opt.libs then
for _, lib in ipairs(opt.libs) do M.remove(lib) end
end
if opt.includedir then
local install_dir = opt.install_dir or (_RUNTIME and _RUNTIME.install_dir) or ""
local includedir = opt.includedir
if not path.is_absolute(includedir) then
includedir = path.join(install_dir, includedir)
end
table.insert(_XVM_OPS, { op = "remove_headers", includedir = includedir })
end
end
return M
)__LUA__";
inline constexpr std::string_view utils_lua = R"__LUA__(
-- xim.libxpkg.utils: utility functions
local M = {}
local function _get_log()
return _LIBXPKG_MODULES and _LIBXPKG_MODULES["log"]
end
function M.filepath_to_absolute(filepath)
if path.is_absolute(filepath) then return filepath end
return path.join(os.getenv("PWD") or ".", filepath)
end
function M.try_download_and_check(url, dir, sha256)
local log = _get_log()
local filename = url:match("[^/]+$") or "download"
local dest = path.join(dir, filename)
local ret = os.execute(string.format('curl -fsSL -o "%s" "%s"', dest, url))
if ret ~= 0 and ret ~= true then
if log then log.error("download failed: %s", url) end
return false
end
if sha256 then
local f = io.popen("sha256sum " .. dest)
local out = f and f:read("*l") or ""
if f then f:close() end
local actual = out:match("^(%x+)")
if actual ~= sha256 then
if log then log.error("sha256 mismatch for %s", dest) end
return false
end
end
return true
end
function M.input_args_process(cmds_kv, args)
local result = {}
local i = 1
local arglist = args or {}
while i <= #arglist do
local arg = arglist[i]
-- --key=value format
local k, v = arg:match("^(%-%-[%w%-]+)=(.+)$")
if k and cmds_kv[k] ~= nil then
result[k] = v
i = i + 1
elseif arg:match("^%-%-") and cmds_kv[arg] ~= nil then
-- --key value format
if i < #arglist then
result[arg] = arglist[i + 1]
i = i + 2
else
result[arg] = true
i = i + 1
end
else
i = i + 1
end
end
return true, result
end
return M
)__LUA__";
inline constexpr std::string_view pkgmanager_lua = R"__LUA__(
local M = {}