versions.gno
1.75 Kb · 77 lines
1package bouncer
2
3import (
4 "strconv"
5 "strings"
6
7 "gno.land/p/nt/avl/v0"
8)
9
10// Versions group the attested paths of one package: gno.land/r/x/vault/v1,
11// .../v2 and so on. Packages on Gno cannot be overwritten, so a fix ships
12// at a new /vN path, and the Passport shows every version side by side.
13
14var families = avl.NewTree() // base path -> *avl.Tree (zero-padded N -> pkgpath)
15
16// familyOf splits ".../name/vN" into its base and N.
17func familyOf(pkgpath string) (base string, n int, ok bool) {
18 i := strings.LastIndex(pkgpath, "/")
19 if i < 0 {
20 return "", 0, false
21 }
22 last := pkgpath[i+1:]
23 if len(last) < 2 || len(last) > 7 || last[0] != 'v' {
24 return "", 0, false
25 }
26 n, err := strconv.Atoi(last[1:])
27 if err != nil || n < 0 || last[1:] != strconv.Itoa(n) {
28 return "", 0, false
29 }
30 base = pkgpath[:i]
31 if strings.Count(base, "/") < 2 { // need gno.land/r/<ns>/...
32 return "", 0, false
33 }
34 return base, n, true
35}
36
37func versionKey(n int) string {
38 s := strconv.Itoa(n)
39 return strings.Repeat("0", 6-len(s)) + s
40}
41
42func addToFamily(pkgpath string) {
43 base, n, ok := familyOf(pkgpath)
44 if !ok {
45 return
46 }
47 var t *avl.Tree
48 if v := families.Get(base); v != nil {
49 t = v.(*avl.Tree)
50 } else {
51 t = avl.NewTree()
52 families.Set(base, t)
53 }
54 t.Set(versionKey(n), pkgpath)
55}
56
57// Versions returns every attested version of pkgpath's package, oldest
58// first. A path without a /vN suffix is its own only version.
59func Versions(pkgpath string) []string {
60 out := []string{}
61 base, _, ok := familyOf(pkgpath)
62 if !ok {
63 if getRecord(pkgpath) != nil {
64 out = append(out, pkgpath)
65 }
66 return out
67 }
68 v := families.Get(base)
69 if v == nil {
70 return out
71 }
72 v.(*avl.Tree).Iterate("", "", func(_ string, p any) bool {
73 out = append(out, p.(string))
74 return false
75 })
76 return out
77}