| 1 |
package commitgraph |
| 2 |
|
| 3 |
import ( |
| 4 |
"github.com/go-git/go-git/v5/plumbing" |
| 5 |
) |
| 6 |
|
| 7 |
// MemoryIndex provides a way to build the commit-graph in memory |
| 8 |
// for later encoding to file. |
| 9 |
// |
| 10 |
// Deprecated: This package uses the wrong types for Generation and Index in CommitData. |
| 11 |
// Use the v2 package instead. |
| 12 |
type MemoryIndex struct { |
| 13 |
commitData []*CommitData |
| 14 |
indexMap map[plumbing.Hash]int |
| 15 |
} |
| 16 |
|
| 17 |
// NewMemoryIndex creates in-memory commit graph representation |
| 18 |
// |
| 19 |
// Deprecated: This package uses the wrong types for Generation and Index in CommitData. |
| 20 |
// Use the v2 package instead. |
| 21 |
func NewMemoryIndex() *MemoryIndex { |
| 22 |
return &MemoryIndex{ |
| 23 |
indexMap: make(map[plumbing.Hash]int), |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
// GetIndexByHash gets the index in the commit graph from commit hash, if available |
| 28 |
func (mi *MemoryIndex) GetIndexByHash(h plumbing.Hash) (int, error) { |
| 29 |
i, ok := mi.indexMap[h] |
| 30 |
if ok { |
| 31 |
return i, nil |
| 32 |
} |
| 33 |
|
| 34 |
return 0, plumbing.ErrObjectNotFound |
| 35 |
} |
| 36 |
|
| 37 |
// GetCommitDataByIndex gets the commit node from the commit graph using index |
| 38 |
// obtained from child node, if available |
| 39 |
func (mi *MemoryIndex) GetCommitDataByIndex(i int) (*CommitData, error) { |
| 40 |
if i >= len(mi.commitData) { |
| 41 |
return nil, plumbing.ErrObjectNotFound |
| 42 |
} |
| 43 |
|
| 44 |
commitData := mi.commitData[i] |
| 45 |
|
| 46 |
// Map parent hashes to parent indexes |
| 47 |
if commitData.ParentIndexes == nil { |
| 48 |
parentIndexes := make([]int, len(commitData.ParentHashes)) |
| 49 |
for i, parentHash := range commitData.ParentHashes { |
| 50 |
var err error |
| 51 |
if parentIndexes[i], err = mi.GetIndexByHash(parentHash); err != nil { |
| 52 |
return nil, err |
| 53 |
} |
| 54 |
} |
| 55 |
commitData.ParentIndexes = parentIndexes |
| 56 |
} |
| 57 |
|
| 58 |
return commitData, nil |
| 59 |
} |
| 60 |
|
| 61 |
// Hashes returns all the hashes that are available in the index |
| 62 |
func (mi *MemoryIndex) Hashes() []plumbing.Hash { |
| 63 |
hashes := make([]plumbing.Hash, 0, len(mi.indexMap)) |
| 64 |
for k := range mi.indexMap { |
| 65 |
hashes = append(hashes, k) |
| 66 |
} |
| 67 |
return hashes |
| 68 |
} |
| 69 |
|
| 70 |
// Add adds new node to the memory index |
| 71 |
func (mi *MemoryIndex) Add(hash plumbing.Hash, commitData *CommitData) { |
| 72 |
// The parent indexes are calculated lazily in GetNodeByIndex |
| 73 |
// which allows adding nodes out of order as long as all parents |
| 74 |
// are eventually resolved |
| 75 |
commitData.ParentIndexes = nil |
| 76 |
mi.indexMap[hash] = len(mi.commitData) |
| 77 |
mi.commitData = append(mi.commitData, commitData) |
| 78 |
} |