AT Protocol IPLD-CAR Repository toolkit (CLI)
1package repo
2
3import (
4 "context"
5 "log"
6 "strings"
7
8 cid "github.com/ipfs/go-cid"
9)
10
11type RepoItem struct {
12 Cid cid.Cid
13 Path string
14 Body interface{}
15}
16
17type RepoSnapshot struct {
18 Root cid.Cid
19 File string
20 Size int
21 Items []RepoItem
22 Repo Repo
23}
24
25func (ss *RepoSnapshot) GetCollectionStats(root string) (map[string]int, error) {
26 rctx := context.TODO()
27
28 rr := ss.Repo
29 if root != "" && root != "b" {
30 cid, err := cid.Parse(root)
31 if err != nil {
32 log.Fatalf("cannot parse CID: %s", root)
33 }
34 cr, err := OpenRepo(rctx, rr.BlockStore(), cid, 0)
35 if err != nil {
36 log.Fatal("cannot open repo")
37 }
38 rr = *cr
39 }
40 stats := make(map[string]int)
41 if err := rr.ForEach(rctx, "", func(k string, v cid.Cid) error {
42 col := strings.Split(k, "/")[0]
43 _, ok := stats[col]
44 if !ok {
45 stats[col] = 0
46 }
47 stats[col]++
48 return nil
49 }); err != nil {
50 return nil, err
51 }
52 return stats, nil
53}
54
55func (ss *RepoSnapshot) LoadItems(root string) error {
56 rctx := context.TODO()
57
58 rr := ss.Repo
59 if root != "" && root != "b" {
60 cid, err := cid.Parse(root)
61 if err != nil {
62 log.Fatalf("cannot parse CID: %s", root)
63 }
64 cr, err := OpenRepo(rctx, rr.BlockStore(), cid, 0)
65 if err != nil {
66 log.Fatal("cannot open repo")
67 }
68 rr = *cr
69 }
70
71 var out []RepoItem
72 if err := rr.ForEach(rctx, "", func(k string, v cid.Cid) error {
73 _, rec, err := rr.GetRecord(rctx, k)
74 if err != nil {
75 log.Println("Cannot get record:", v.String())
76 }
77 out = append(out, RepoItem{Cid: v, Path: k, Body: rec})
78 ss.Items = out
79 return nil
80 }); err != nil {
81 return err
82 }
83 return nil
84}