|
| 1 | +// Package quickbuilder is designed as a replacement for the existing ipfs-files |
| 2 | +// constructor for a simple way to generate synthetic directory trees. |
| 3 | +package quickbuilder |
| 4 | + |
| 5 | +import ( |
| 6 | + "bytes" |
| 7 | + |
| 8 | + "github.com/ipfs/go-unixfsnode/data/builder" |
| 9 | + dagpb "github.com/ipld/go-codec-dagpb" |
| 10 | + "github.com/ipld/go-ipld-prime" |
| 11 | +) |
| 12 | + |
| 13 | +// A Node represents the most basic form of a file or directory |
| 14 | +type Node interface { |
| 15 | + Size() (int64, error) |
| 16 | + Link() ipld.Link |
| 17 | +} |
| 18 | + |
| 19 | +type lnkNode struct { |
| 20 | + link ipld.Link |
| 21 | + size int64 |
| 22 | + ls *ipld.LinkSystem |
| 23 | +} |
| 24 | + |
| 25 | +func (ln *lnkNode) Size() (int64, error) { |
| 26 | + return ln.size, nil |
| 27 | +} |
| 28 | + |
| 29 | +func (ln *lnkNode) Link() ipld.Link { |
| 30 | + return ln.link |
| 31 | +} |
| 32 | + |
| 33 | +// Builder provides the linksystem context for saving files & directories |
| 34 | +type Builder struct { |
| 35 | + ls *ipld.LinkSystem |
| 36 | +} |
| 37 | + |
| 38 | +// NewMapDirectory creates a unixfs directory from a list of named entries |
| 39 | +func (b *Builder) NewMapDirectory(entries map[string]Node) Node { |
| 40 | + lnks := make([]dagpb.PBLink, 0, len(entries)) |
| 41 | + for name, e := range entries { |
| 42 | + sz, _ := e.Size() |
| 43 | + entry, err := builder.BuildUnixFSDirectoryEntry(name, sz, e.Link()) |
| 44 | + if err != nil { |
| 45 | + return nil |
| 46 | + } |
| 47 | + lnks = append(lnks, entry) |
| 48 | + } |
| 49 | + n, size, err := builder.BuildUnixFSDirectory(lnks, b.ls) |
| 50 | + if err != nil { |
| 51 | + panic(err) |
| 52 | + } |
| 53 | + return &lnkNode{ |
| 54 | + n, |
| 55 | + int64(size), |
| 56 | + b.ls, |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +// NewBytesFile creates a unixfs file from byte contents |
| 61 | +func (b *Builder) NewBytesFile(data []byte) Node { |
| 62 | + n, size, err := builder.BuildUnixFSFile(bytes.NewReader(data), "", b.ls) |
| 63 | + if err != nil { |
| 64 | + panic(err) |
| 65 | + } |
| 66 | + return &lnkNode{ |
| 67 | + n, |
| 68 | + int64(size), |
| 69 | + b.ls, |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// Store provides a builder context for making unixfs files and directories |
| 74 | +func Store(ls *ipld.LinkSystem, cb func(b *Builder) error) error { |
| 75 | + b := Builder{ls} |
| 76 | + return cb(&b) |
| 77 | +} |
0 commit comments