-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative.go
More file actions
875 lines (713 loc) · 26.7 KB
/
Copy pathnative.go
File metadata and controls
875 lines (713 loc) · 26.7 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
package client
import (
"archive/zip"
"context"
"errors"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
"strings"
rocks "github.com/tarantool/go-luarocks"
"github.com/tarantool/go-luarocks/build"
"github.com/tarantool/go-luarocks/deps"
"github.com/tarantool/go-luarocks/fetch"
"github.com/tarantool/go-luarocks/remote"
"github.com/tarantool/go-luarocks/rockspec"
"github.com/tarantool/go-luarocks/tree"
)
// nativeEngine is the pure-Go backend (BackendNative). It holds the same
// state the *Rocks methods used before the Engine extraction and retains
// EXACT behavioral compatibility with the pre-task client.Rocks: the
// five implemented method bodies and their private helpers are moved here
// verbatim, with only the receiver renamed from (r *Rocks) to (e *nativeEngine).
//
// The thirteen operations the native backend does not implement return
// rocks.ErrNotImplemented — never a silent no-op.
type nativeEngine struct {
cfg rocks.Config
store rocks.ManifestStore
index rocks.RemoteIndex
logger *slog.Logger
}
// unpackDirMode is the permission applied to directories created while
// extracting a .rock archive: owner rwx, group rx, no world access.
const unpackDirMode = 0o750
// luaInterpreter is the interpreter name baked into generated command
// wrappers, matching the tarantool/luarocks fork's hardcoded.LUA_INTERPRETER.
const luaInterpreter = "tarantool"
// defaultSysconfDir is upstream LuaRocks' cfg.sysconfdir fallback on Unix
// (luarocks/core/cfg.lua) when neither LUAROCKS_SYSCONFDIR nor a detected
// install prefix applies.
const defaultSysconfDir = "/etc/luarocks"
// sysconfDir mirrors upstream's cfg.sysconfdir resolution for the value
// exported as LUAROCKS_SYSCONFDIR in command wrappers: honor the
// LUAROCKS_SYSCONFDIR env override, else fall back to the Unix default.
func sysconfDir() string {
if v := os.Getenv("LUAROCKS_SYSCONFDIR"); v != "" {
return v
}
return defaultSysconfDir
}
// Install installs `name` (with optional version constraint in
// opts.Version) into e.cfg.Tree, including transitive deps per
// opts.Deps. The general algorithm:
//
// 1. Query the remote index for `name` candidates.
// 2. Pick the newest version satisfying opts.Version.
// 3. Resolve transitive deps (unless DepsNone).
// 4. For each step in topo order: fetch source, eval rockspec, merge
// platforms, validate, build, deploy, update tree manifest.
// 5. Install the requested rock itself.
//
// Returns ErrUnsupportedRockspecFeature for unrecognized build types
// (bubbled up from build.RunBackend). May also surface
// ErrMissingTarantoolHeaders when a C-extension rock is built.
func (e *nativeEngine) Install(ctx context.Context, name string, opts InstallOpts) error {
if name == "" {
return errors.New("rocks.Install: empty name")
}
idx := e.index
if len(opts.Servers) > 0 {
idx = &remote.HTTPRemoteIndex{
Servers: opts.Servers,
InsecureServers: e.cfg.InsecureServers,
}
}
cs, err := deps.ParseConstraints(opts.Version)
if err != nil {
return fmt.Errorf("rocks.Install: parse version %q: %w", opts.Version, err)
}
// A user-supplied "owner/rock" target selects the owner's namespace.
queryName, namespace := name, ""
if before, after, ok0 := strings.Cut(name, "/"); ok0 {
namespace, queryName = before, after
}
candidates, err := idx.Query(ctx, queryName, namespace)
if err != nil {
return fmt.Errorf("rocks.Install: query %q: %w", name, err)
}
root, ok := pickNewest(candidates, cs)
if !ok {
return fmt.Errorf("rocks.Install: no version of %q matches %q", name, opts.Version)
}
e.logger.Info("rocks.Install: selected", "name", name, "version", root.Version.Raw, "url", root.URL)
// Fetch + eval root rockspec so we can resolve transitive deps.
rootSpec, err := e.fetchAndEval(ctx, root.URL)
if err != nil {
return fmt.Errorf("rocks.Install: fetch/eval root: %w", err)
}
root.Spec = rootSpec
var plan []rocks.InstallStep
if opts.Deps != DepsNone {
plan, err = e.resolvePlan(ctx, rootSpec, idx)
if err != nil {
return fmt.Errorf("rocks.Install: resolve deps: %w", err)
}
}
for _, step := range plan {
err := e.installStep(ctx, step)
if err != nil {
return fmt.Errorf("rocks.Install: dep %s-%s: %w", step.Name, step.Version.Raw, err)
}
}
// Finally install the requested rock itself. Its source is fetched from
// the rockspec's source.url, exactly like every dependency step.
rootStep := rocks.InstallStep{
Name: rootSpec.Package,
Version: root.Version,
URL: root.URL,
Rockspec: rootSpec,
}
if err := e.installFromSource(ctx, rootStep); err != nil {
return fmt.Errorf("rocks.Install: install root: %w", err)
}
return nil
}
// resolvePlan walks the full transitive dependency closure of rootSpec via
// deps.Resolve. It hands Resolve a fetcher (the remote index returns bare
// name/version/URL rows with no preloaded rockspec, so each chosen rock is
// evaluated on demand), registers `tarantool` as a VM-provided rock at the
// configured version (mirroring util.get_rocks_provided in the
// tarantool/luarocks fork), and supplies the already-installed rocks so
// satisfied deps are skipped (glr-n88).
func (e *nativeEngine) resolvePlan(ctx context.Context, rootSpec *rocks.Rockspec, idx rocks.RemoteIndex) ([]rocks.InstallStep, error) {
fetchSpec := func(ctx context.Context, rock rocks.VersionedRock) (*rocks.Rockspec, error) {
return e.fetchAndEval(ctx, rock.URL)
}
resolveOpts := []deps.Option{deps.WithSpecFetcher(fetchSpec)}
if e.cfg.Tarantool.Version != "" {
if ttVer, verr := deps.ParseVersion(e.cfg.Tarantool.Version + "-1"); verr == nil {
resolveOpts = append(resolveOpts,
deps.WithProvided(map[string]rocks.Version{"tarantool": ttVer}))
}
}
// Tarantool is single-tree, so the deps_mode tree selection reduces to
// "consult this tree" for every mode except none (which never reaches here).
if lookup, lerr := e.installedLookup(); lerr == nil {
resolveOpts = append(resolveOpts, deps.WithInstalled(lookup))
}
return deps.Resolve(ctx, rootSpec, idx, resolveOpts...)
}
// Build evaluates the rockspec at specPath, fetches its declared source,
// runs the build backend, and deploys the result into e.cfg.Tree.
//
// Unlike Install, Build does not perform dependency resolution — it
// assumes prerequisites are already present (matching upstream
// `luarocks build`).
func (e *nativeEngine) Build(ctx context.Context, specPath string, opts BuildOpts) error {
spec, err := evalAndPrepare(specPath, e.cfg)
if err != nil {
return err
}
tmp, err := os.MkdirTemp(e.cfg.WorkingDir, "rocks-build-*")
if err != nil {
return fmt.Errorf("rocks.Build: mkdir tmp: %w", err)
}
if !opts.Keep {
defer func() { _ = os.RemoveAll(tmp) }()
}
srcDir, err := e.fetchSource(ctx, spec, tmp)
if err != nil {
return fmt.Errorf("rocks.Build: %w", err)
}
return e.deployFromSource(ctx, spec, srcDir)
}
// Make is "build the rockspec found in cwd against the source already
// present in cwd" — the upstream `luarocks make` flow. It is the
// developer-iteration form of Build.
func (e *nativeEngine) Make(ctx context.Context, opts MakeOpts) error {
specPath := opts.RockspecPath
if specPath == "" {
entries, err := os.ReadDir(e.cfg.WorkingDir)
if err != nil {
return fmt.Errorf("rocks.Make: read %s: %w", e.cfg.WorkingDir, err)
}
var found []string
for _, ent := range entries {
if !ent.IsDir() && strings.HasSuffix(ent.Name(), ".rockspec") {
found = append(found, filepath.Join(e.cfg.WorkingDir, ent.Name()))
}
}
if len(found) == 0 {
return fmt.Errorf("rocks.Make: no .rockspec found in %s", e.cfg.WorkingDir)
}
if len(found) > 1 {
return fmt.Errorf("rocks.Make: multiple .rockspec found in %s (%v); pass MakeOpts.RockspecPath", e.cfg.WorkingDir, found)
}
specPath = found[0]
}
spec, err := evalAndPrepare(specPath, e.cfg)
if err != nil {
return err
}
return e.deployFromSource(ctx, spec, e.cfg.WorkingDir)
}
// Pack produces a .rock or .src.rock archive for `target` (rock name) in
// e.cfg.WorkingDir and returns its path.
//
// - opts.SrcOnly == false: zip the installed tree at
// <tree>/share/tarantool/rocks/<name>/<version>/ into <name>-<ver>.rock.
// - opts.SrcOnly == true: zip the rockspec only into
// <name>-<ver>.src.rock. (Source download lives outside the rockspec;
// upstream pulls source per `source.url` and inlines it. We omit that
// until a real packaging need surfaces — fail loud over over-engineering.)
func (e *nativeEngine) Pack(ctx context.Context, target string, opts PackOpts) (string, error) {
_ = ctx
t, err := tree.Open(e.cfg)
if err != nil {
return "", err
}
m, err := e.store.ReadTree(t.RocksDir())
if err != nil {
return "", err
}
versions, ok := m.Repository[target]
if !ok {
return "", fmt.Errorf("rocks.Pack: %q not installed in %s", target, t.Tree)
}
var picked string
for v := range versions {
if picked == "" || v < picked {
picked = v
}
}
installDir := t.InstallDir(target, picked)
suffix := ".rock"
if opts.SrcOnly {
suffix = ".src.rock"
}
outPath := filepath.Join(e.cfg.WorkingDir, target+"-"+picked+suffix)
if opts.SrcOnly {
specPath := filepath.Join(installDir, target+"-"+picked+".rockspec")
err := zipSingleFile(outPath, specPath, target+"-"+picked+".rockspec")
if err != nil {
return "", fmt.Errorf("rocks.Pack: zip rockspec: %w", err)
}
} else {
err := zipDir(outPath, installDir)
if err != nil {
return "", fmt.Errorf("rocks.Pack: zip install dir: %w", err)
}
}
return outPath, nil
}
// Unpack extracts `archive` (a .rock or .src.rock zip) into destDir.
func (e *nativeEngine) Unpack(ctx context.Context, archive, destDir string) error {
_ = ctx
if err := os.MkdirAll(destDir, unpackDirMode); err != nil {
return fmt.Errorf("rocks.Unpack: mkdir: %w", err)
}
zr, err := zip.OpenReader(archive)
if err != nil {
return fmt.Errorf("rocks.Unpack: open %s: %w", archive, err)
}
defer func() { _ = zr.Close() }()
cleanDest := filepath.Clean(destDir)
for _, f := range zr.File {
target := filepath.Join(destDir, f.Name)
if !strings.HasPrefix(target, cleanDest+string(os.PathSeparator)) && target != cleanDest {
return fmt.Errorf("rocks.Unpack: entry %q escapes destDir", f.Name)
}
if f.FileInfo().IsDir() {
err := os.MkdirAll(target, unpackDirMode)
if err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(target), unpackDirMode); err != nil {
return err
}
rc, err := f.Open()
if err != nil {
return err
}
out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
_ = rc.Close()
return err
}
if _, err := io.Copy(out, rc); err != nil {
_ = rc.Close()
_ = out.Close()
return err
}
_ = rc.Close()
if err := out.Close(); err != nil {
return err
}
}
return nil
}
// --- internal helpers (used only by the five native write operations) ---
func (e *nativeEngine) installStep(ctx context.Context, step rocks.InstallStep) error {
// deps.Resolve populates step.Rockspec via the spec fetcher; reuse it rather
// than fetching and evaluating the same version-pinned artifact a second
// time. It is nil only if a caller resolved without the fetcher.
if step.Rockspec == nil {
spec, err := e.fetchAndEval(ctx, step.URL)
if err != nil {
return err
}
step.Rockspec = spec
}
return e.installFromSource(ctx, step)
}
// fetchAndEval fetches the resolver-produced rock/rockspec URL into a
// throwaway directory, locates the `.rockspec` it contains (a bare
// .rockspec, or one bundled inside a .src.rock), and evaluates it. Only the
// parsed *Rockspec is returned — the fetched directory is the registry
// artifact, NOT the rock's source tree, so it is removed before returning.
// The actual source is fetched separately from spec.Source.URL at build
// time (see installFromSource / Build), mirroring upstream luarocks which
// never builds against the rockspec download directory.
func (e *nativeEngine) fetchAndEval(ctx context.Context, urlStr string) (*rocks.Rockspec, error) {
tmp, err := os.MkdirTemp(e.cfg.WorkingDir, "rocks-fetch-*")
if err != nil {
return nil, fmt.Errorf("mkdir tmp: %w", err)
}
defer func() { _ = os.RemoveAll(tmp) }()
srcDir, err := fetch.FetchWith(ctx, urlStr, tmp, fetch.Options{
InsecureServers: e.cfg.InsecureServers,
})
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", urlStr, err)
}
specPath, err := findRockspecIn(srcDir)
if err != nil {
return nil, err
}
return evalAndPrepare(specPath, e.cfg)
}
// installFromSource fetches the rockspec's declared source (spec.Source.URL)
// into a fresh build directory and builds+deploys against THAT — never
// against the rockspec download directory, which holds only the registry
// artifact. This mirrors nativeEngine.Build and upstream luarocks'
// fetch_sources → build flow.
func (e *nativeEngine) installFromSource(ctx context.Context, step rocks.InstallStep) error {
spec := step.Rockspec
tmp, err := os.MkdirTemp(e.cfg.WorkingDir, "rocks-src-*")
if err != nil {
return fmt.Errorf("mkdir tmp: %w", err)
}
defer func() { _ = os.RemoveAll(tmp) }()
srcDir, err := e.fetchSource(ctx, spec, tmp)
if err != nil {
return err
}
return e.deployFromSource(ctx, spec, srcDir)
}
// fetchSource downloads spec.Source.URL into tmp and returns the source
// root to build against. After unpacking an archive the real source usually
// lives in a single top-level subdirectory (e.g. inspect.lua-3.1.3/), and
// build.modules paths are relative to that root — so descend into it,
// mirroring upstream luarocks' fetch.find_base_dir.
func (e *nativeEngine) fetchSource(ctx context.Context, spec *rocks.Rockspec, tmp string) (string, error) {
unpacked, err := fetch.FetchWith(ctx, spec.Source.URL, tmp, fetch.Options{
InsecureServers: e.cfg.InsecureServers,
Tag: spec.Source.Tag,
Branch: spec.Source.Branch,
File: spec.Source.File,
MD5: spec.Source.MD5,
Version: spec.Version,
IdentifierOut: &spec.Source.Identifier,
})
if err != nil {
return "", fmt.Errorf("fetch %s: %w", spec.Source.URL, err)
}
return findSourceBaseDir(unpacked, spec)
}
// findSourceBaseDir mirrors upstream luarocks fetch.find_base_dir: pick the
// directory the rock's source actually lives in after unpacking.
//
// - If source.dir is set and names an existing subdirectory, use it
// (explicit override from the rockspec).
// - Else, if dir contains exactly one entry and it is a directory, descend
// into it (the common single-versioned-subdir tarball layout).
// - Else, use dir as-is (flat layout: a bare module file, or a git/file
// checkout whose files already sit at the top level).
func findSourceBaseDir(dir string, spec *rocks.Rockspec) (string, error) {
// (1) explicit source.dir wins when it names an existing subdir.
if spec.Source.Dir != "" {
cand := filepath.Join(dir, spec.Source.Dir)
if fi, err := os.Stat(cand); err == nil && fi.IsDir() {
return cand, nil
}
}
// (2) the dir inferred from the archive name (deduce_base_dir), when it
// exists — this is what upstream fetch.find_base_dir prefers, so a tarball
// unpacking to foo-1.0/ plus stray top-level files still descends into
// foo-1.0 (glr-qht).
if src := spec.Source.File; src != "" || spec.Source.URL != "" {
if src == "" {
src = spec.Source.URL
}
if inferred := deduceBaseDir(src); inferred != "" {
cand := filepath.Join(dir, inferred)
if fi, err := os.Stat(cand); err == nil && fi.IsDir() {
return cand, nil
}
}
}
entries, err := os.ReadDir(dir)
if err != nil {
return "", fmt.Errorf("read source dir %s: %w", dir, err)
}
// (3) the common single-versioned-subdir tarball layout: descend into the
// lone directory. We deliberately do NOT fall back to the first-sorted
// subdir for multi-entry roots — the native pipeline also unpacks .src.rock
// sources flat (files plus .github/, src/, … at the root), where the root
// itself is the base dir and descending would resolve modules wrongly.
if len(entries) == 1 && entries[0].IsDir() {
return filepath.Join(dir, entries[0].Name()), nil
}
// (4) flat layout: files already at the top level.
return dir, nil
}
// deduceBaseDir infers the directory an archive unpacks into from its name,
// mirroring upstream dir.deduce_base_dir (dir.lua:38-46): strip a trailing
// known archive extension ({zip,git,tgz,tar,gz,bz2}) then any ".tar".
func deduceBaseDir(url string) string {
base := filepath.Base(url)
known := map[string]bool{"zip": true, "git": true, "tgz": true, "tar": true, "gz": true, "bz2": true}
if i := strings.LastIndex(base, "."); i >= 0 && known[base[i+1:]] {
base = base[:i]
}
return strings.ReplaceAll(base, ".tar", "")
}
// checkSupportedPlatforms mirrors upstream deps.check_supported_platforms
// (deps.lua:247-273): a rockspec's supported_platforms list constrains where it
// may install. A "!plat" entry that matches the current platform set rejects
// the install; if there are any positive entries and none matches, it is also
// rejected. An empty list imposes no constraint.
func checkSupportedPlatforms(spec *rocks.Rockspec, plats []string) error {
if len(spec.SupportedPlatforms) == 0 {
return nil
}
isPlatform := func(name string) bool {
return slices.Contains(plats, name)
}
allNegative := true
supported := false
for _, entry := range spec.SupportedPlatforms {
if name, ok := strings.CutPrefix(entry, "!"); ok {
if isPlatform(name) {
return fmt.Errorf("%w: rockspec for %s does not support %s platforms",
rocks.ErrUnsupportedRockspecFeature, spec.Package, name)
}
continue
}
allNegative = false
if isPlatform(entry) {
supported = true
break
}
}
if !supported && !allNegative {
return fmt.Errorf("%w: rockspec for %s does not support the current platform",
rocks.ErrUnsupportedRockspecFeature, spec.Package)
}
return nil
}
// wrapBinScripts mirrors repos.should_wrap_bin_scripts: wrap command scripts
// unless the rockspec explicitly sets deploy.wrap_bin_scripts = false.
func wrapBinScripts(spec *rocks.Rockspec) bool {
if spec.Deploy.WrapBinScripts != nil {
return *spec.Deploy.WrapBinScripts
}
return true
}
// installedLookup returns a deps.InstalledLookup over the current tree
// manifest's repository — the installed versions of a rock name — so the
// resolver can skip dependencies already satisfied by an installed rock.
func (e *nativeEngine) installedLookup() (deps.InstalledLookup, error) {
t, err := tree.Open(e.cfg)
if err != nil {
return nil, err
}
m, err := e.readTreeManifest(t)
if err != nil {
return nil, err
}
return func(name string) []rocks.Version {
var out []rocks.Version
for verStr := range m.Repository[name] {
if v, verr := deps.ParseVersion(verStr); verr == nil {
out = append(out, v)
}
}
return out
}, nil
}
// readTreeManifest loads the tree-level manifest, returning a fresh (empty)
// one with initialized maps when none exists yet.
func (e *nativeEngine) readTreeManifest(t *tree.Tree) (*rocks.Manifest, error) {
m, err := e.store.ReadTree(t.RocksDir())
if err != nil {
if !os.IsNotExist(unwrapPathErr(err)) {
return nil, fmt.Errorf("read tree manifest: %w", err)
}
m = &rocks.Manifest{}
}
if m.Repository == nil {
m.Repository = map[string]map[string]rocks.RepoEntry{}
}
if m.Modules == nil {
m.Modules = map[string][]string{}
}
if m.Commands == nil {
m.Commands = map[string][]string{}
}
if m.Dependencies == nil {
m.Dependencies = map[string]map[string][]rocks.Dep{}
}
return m, nil
}
func (e *nativeEngine) deployFromSource(ctx context.Context, spec *rocks.Rockspec, srcDir string) error {
// Abort before build/deploy when the rockspec excludes the current platform
// (upstream deps.check_supported_platforms, deps.lua:247-273).
if err := checkSupportedPlatforms(spec, rockspec.RuntimePlatforms()); err != nil {
return err
}
t, err := tree.Open(e.cfg)
if err != nil {
return err
}
// Read the current tree manifest BEFORE deploying so Deploy can consult the
// active provider of each module/command (check_spot_if_available) — this
// drives version promotion on reinstall/upgrade (glr-5e9).
m, err := e.readTreeManifest(t)
if err != nil {
return err
}
t.Provider = manifestProvider(m)
// Match upstream's command-wrapper deploy (repos.deploy_files →
// fs.wrap_script): the interpreter path is LUA_BINDIR/lua_interpreter
// (prefix/bin/tarantool), and LUAROCKS_SYSCONFDIR mirrors cfg.sysconfdir.
// repos.should_wrap_bin_scripts wraps unless the rockspec sets
// deploy.wrap_bin_scripts = false; when it does, leave BinWrap nil so
// Deploy copies scripts verbatim. (Upstream also honors a cfg-level
// wrap_bin_scripts override, which the hardcoded Tarantool cfg lacks.)
if wrapBinScripts(spec) {
t.BinWrap = &tree.BinWrap{
Interpreter: filepath.Join(e.cfg.Tarantool.Prefix, "bin", luaInterpreter),
Sysconfdir: sysconfDir(),
}
}
destDir := filepath.Join(t.InstallDir(spec.Package, spec.Version), "build")
if err := os.MkdirAll(destDir, unpackDirMode); err != nil {
return fmt.Errorf("mkdir destDir: %w", err)
}
if err := build.RunBackend(ctx, spec, srcDir, destDir, e.cfg); err != nil {
return err
}
// srcDir holds original .lua / install / copy_dirs files; destDir holds
// compiled .so artifacts from the build phase. Deploy reads from both.
rm, err := t.Deploy(spec, srcDir, destDir)
if err != nil {
return fmt.Errorf("deploy: %w", err)
}
rockManifestPath := filepath.Join(t.InstallDir(spec.Package, spec.Version), "rock_manifest")
if err := e.store.WriteRock(rockManifestPath, rm); err != nil {
return fmt.Errorf("write rock_manifest: %w", err)
}
if m.Repository[spec.Package] == nil {
m.Repository[spec.Package] = map[string]rocks.RepoEntry{}
}
// Build the per-arch entry's modules/commands index from what tree.Deploy
// actually wrote (rm.Lua, rm.Lib, rm.Bin). Module names in the rockspec
// are dotted; on-disk paths are slashed — invert by reading rm directly.
entry := rocks.RepoEntry{Arch: "installed"}
pkgVer := spec.Package + "/" + spec.Version
if len(rm.Lua) > 0 || len(rm.Lib) > 0 {
entry.Modules = map[string]string{}
for modName := range spec.Build.Modules {
// Derive on-disk path from the deployed RockManifest: prefer
// rm.Lib (compiled .so) over rm.Lua (the .lua source). A plain-path
// key means this install won the active (plain) spot, so it becomes
// the current provider (index 0); a munged key means it deployed
// inactive and is appended after the active provider.
slashed := strings.ReplaceAll(modName, ".", "/")
if p, ok := matchModulePath(rm.Lib, slashed+".so"); ok {
entry.Modules[modName] = p
m.Modules[modName] = upsertProvider(m.Modules[modName], pkgVer, true)
continue
}
if p, ok := matchModulePath(rm.Lua, slashed+".lua"); ok {
entry.Modules[modName] = p
m.Modules[modName] = upsertProvider(m.Modules[modName], pkgVer, true)
continue
}
}
}
if len(rm.Bin) > 0 {
entry.Commands = map[string]string{}
for binName, srcRel := range spec.Build.Install.Bin {
entry.Commands[binName] = srcRel
m.Commands[binName] = upsertProvider(m.Commands[binName], pkgVer, true)
}
}
// Dependencies (glr-6y6): upstream update_dependencies records both the
// rock's own declared dependency list (top-level manifest.dependencies) and
// the resolved name→version map of its installed deps (per-entry
// repo.dependencies). Both are always present — {} for a dep-less rock.
if m.Dependencies[spec.Package] == nil {
m.Dependencies[spec.Package] = map[string][]rocks.Dep{}
}
m.Dependencies[spec.Package][spec.Version] = spec.Dependencies
entry.Dependencies = resolveInstalledDeps(spec, m)
m.Repository[spec.Package][spec.Version] = entry
if err := e.store.WriteTree(t.RocksDir(), m); err != nil {
return fmt.Errorf("write tree manifest: %w", err)
}
return nil
}
// Remove deletes the requested version (or every installed version when
// opts.Version is empty) from the on-disk tree, drops its module/command
// providers from the manifest, and rewrites the tree manifest.
func (e *nativeEngine) Remove(_ context.Context, name string, opts RemoveOpts) error {
t, err := tree.Open(e.cfg)
if err != nil {
return err
}
m, err := e.readTreeManifest(t)
if err != nil {
return err
}
versions := m.Repository[name]
if len(versions) == 0 {
return fmt.Errorf("rocks.Remove: %s is not installed", name)
}
// Determine which versions to remove: a specific one, or all.
var toRemove []string
if opts.Version != "" {
if _, ok := versions[opts.Version]; !ok {
return fmt.Errorf("rocks.Remove: %s %s is not installed", name, opts.Version)
}
toRemove = []string{opts.Version}
} else {
for v := range versions {
toRemove = append(toRemove, v)
}
}
for _, v := range toRemove {
if err := t.DeleteVersion(name, v); err != nil {
return fmt.Errorf("rocks.Remove: %s %s: %w", name, v, err)
}
pkgVer := name + "/" + v
delete(m.Repository[name], v)
removeProvider(m.Modules, pkgVer)
removeProvider(m.Commands, pkgVer)
if vers, ok := m.Dependencies[name]; ok {
delete(vers, v)
}
}
if len(m.Repository[name]) == 0 {
delete(m.Repository, name)
delete(m.Dependencies, name)
}
if err := e.store.WriteTree(t.RocksDir(), m); err != nil {
return fmt.Errorf("rocks.Remove: write tree manifest: %w", err)
}
return nil
}
// --- unimplemented operations: loud ErrNotImplemented ---
func (e *nativeEngine) Purge(ctx context.Context, opts PurgeOpts) error {
return rocks.ErrNotImplemented
}
func (e *nativeEngine) Search(ctx context.Context, pattern string, opts SearchOpts) ([]SearchResult, error) {
return nil, rocks.ErrNotImplemented
}
func (e *nativeEngine) Download(ctx context.Context, name string, opts DownloadOpts) (string, error) {
return "", rocks.ErrNotImplemented
}
func (e *nativeEngine) Lint(ctx context.Context, specPath string, opts LintOpts) error {
return rocks.ErrNotImplemented
}
func (e *nativeEngine) NewVersion(ctx context.Context, specPath string, opts NewVersionOpts) (string, error) {
return "", rocks.ErrNotImplemented
}
func (e *nativeEngine) WriteRockspec(ctx context.Context, url string, opts WriteRockspecOpts) (string, error) {
return "", rocks.ErrNotImplemented
}
func (e *nativeEngine) Doc(ctx context.Context, name string, opts DocOpts) error {
return rocks.ErrNotImplemented
}
func (e *nativeEngine) Test(ctx context.Context, specPath string, opts TestOpts) error {
return rocks.ErrNotImplemented
}
func (e *nativeEngine) Config(ctx context.Context, opts ConfigOpts) (string, error) {
return "", rocks.ErrNotImplemented
}
func (e *nativeEngine) Upload(ctx context.Context, specPath string, opts UploadOpts) error {
return rocks.ErrNotImplemented
}
func (e *nativeEngine) InitProject(ctx context.Context, opts InitProjectOpts) error {
return rocks.ErrNotImplemented
}
func (e *nativeEngine) Admin(ctx context.Context, subCmd string, args []string, opts AdminOpts) error {
return rocks.ErrNotImplemented
}