aboutsummaryrefslogtreecommitdiffstats
path: root/plumbing/format/commitgraph/memory.go
blob: b24ce36d929ebcb7cf3c4cc10b38ffb283faeac0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package commitgraph

import (
	"github.com/go-git/go-git/v5/plumbing"
)

// MemoryIndex provides a way to build the commit-graph in memory

// for later encoding to file.

type MemoryIndex struct {
	commitData []*CommitData
	indexMap   map[plumbing.Hash]int
}

// NewMemoryIndex creates in-memory commit graph representation

func NewMemoryIndex() *MemoryIndex {
	return &MemoryIndex{
		indexMap: make(map[plumbing.Hash]int),
	}
}

// GetIndexByHash gets the index in the commit graph from commit hash, if available

func (mi *MemoryIndex) GetIndexByHash(h plumbing.Hash) (int, error) {
	i, ok := mi.indexMap[h]
	if ok {
		return i, nil
	}

	return 0, plumbing.ErrObjectNotFound
}

// GetCommitDataByIndex gets the commit node from the commit graph using index

// obtained from child node, if available

func (mi *MemoryIndex) GetCommitDataByIndex(i int) (*CommitData, error) {
	if i >= len(mi.commitData) {
		return nil, plumbing.ErrObjectNotFound
	}

	commitData := mi.commitData[i]

	// Map parent hashes to parent indexes

	if commitData.ParentIndexes == nil {
		parentIndexes := make([]int, len(commitData.ParentHashes))
		for i, parentHash := range commitData.ParentHashes {
			var err error
			if parentIndexes[i], err = mi.GetIndexByHash(parentHash); err != nil {
				return nil, err
			}
		}
		commitData.ParentIndexes = parentIndexes
	}

	return commitData, nil
}

// Hashes returns all the hashes that are available in the index

func (mi *MemoryIndex) Hashes() []plumbing.Hash {
	hashes := make([]plumbing.Hash, 0, len(mi.indexMap))
	for k := range mi.indexMap {
		hashes = append(hashes, k)
	}
	return hashes
}

// Add adds new node to the memory index

func (mi *MemoryIndex) Add(hash plumbing.Hash, commitData *CommitData) {
	// The parent indexes are calculated lazily in GetNodeByIndex

	// which allows adding nodes out of order as long as all parents

	// are eventually resolved

	commitData.ParentIndexes = nil
	mi.indexMap[hash] = len(mi.commitData)
	mi.commitData = append(mi.commitData, commitData)
}