|
7 | 7 | "log"
|
8 | 8 | "os"
|
9 | 9 | "path/filepath"
|
| 10 | + "sort" |
10 | 11 | "strconv"
|
| 12 | + "strings" |
11 | 13 |
|
12 | 14 | cbor "github.com/fxamacker/cbor/v2"
|
13 | 15 | "github.com/multiformats/go-multibase"
|
@@ -357,3 +359,40 @@ func (dag *Dag) GetDataFromLeaf(leaf *DagLeaf) ([]byte, error) {
|
357 | 359 |
|
358 | 360 | return content, nil
|
359 | 361 | }
|
| 362 | + |
| 363 | +func (d *Dag) IterateDag(processLeaf func(leaf *DagLeaf, parent *DagLeaf)) error { |
| 364 | + var iterate func(leafHash string, parentHash *string) error |
| 365 | + iterate = func(leafHash string, parentHash *string) error { |
| 366 | + leaf, exists := d.Leafs[leafHash] |
| 367 | + if !exists { |
| 368 | + return fmt.Errorf("child is missing when iterating dag") |
| 369 | + } |
| 370 | + |
| 371 | + var parent *DagLeaf |
| 372 | + if parentHash != nil { |
| 373 | + parent = d.Leafs[*parentHash] |
| 374 | + } |
| 375 | + |
| 376 | + processLeaf(leaf, parent) |
| 377 | + |
| 378 | + childHashes := []string{} |
| 379 | + for _, childHash := range leaf.Links { |
| 380 | + childHashes = append(childHashes, childHash) |
| 381 | + } |
| 382 | + |
| 383 | + sort.Slice(childHashes, func(i, j int) bool { |
| 384 | + numI, _ := strconv.Atoi(strings.Split(childHashes[i], ":")[0]) |
| 385 | + numJ, _ := strconv.Atoi(strings.Split(childHashes[j], ":")[0]) |
| 386 | + |
| 387 | + return numI < numJ |
| 388 | + }) |
| 389 | + |
| 390 | + for _, childHash := range childHashes { |
| 391 | + return iterate(childHash, &leaf.Hash) |
| 392 | + } |
| 393 | + |
| 394 | + return nil |
| 395 | + } |
| 396 | + |
| 397 | + return iterate(d.Root, nil) |
| 398 | +} |
0 commit comments