aboutsummaryrefslogtreecommitdiffstats
path: root/plumbing/object/commitgraph/commitnode_walker_ctime.go
blob: f2ed66304eea19bea62f2684f475ac1a253fa66e (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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package commitgraph

import (
	"io"

	"github.com/emirpasic/gods/trees/binaryheap"

	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/storer"
)

type commitNodeIteratorByCTime struct {
	heap         *binaryheap.Heap
	seenExternal map[plumbing.Hash]bool
	seen         map[plumbing.Hash]bool
}

// NewCommitNodeIterCTime returns a CommitNodeIter that walks the commit history,

// starting at the given commit and visiting its parents while preserving Committer Time order.

// this appears to be the closest order to `git log`

// The given callback will be called for each visited commit. Each commit will

// be visited only once. If the callback returns an error, walking will stop

// and will return the error. Other errors might be returned if the history

// cannot be traversed (e.g. missing objects). Ignore allows to skip some

// commits from being iterated.

func NewCommitNodeIterCTime(
	c CommitNode,
	seenExternal map[plumbing.Hash]bool,
	ignore []plumbing.Hash,
) CommitNodeIter {
	seen := make(map[plumbing.Hash]bool)
	for _, h := range ignore {
		seen[h] = true
	}

	heap := binaryheap.NewWith(func(a, b interface{}) int {
		if a.(CommitNode).CommitTime().Before(b.(CommitNode).CommitTime()) {
			return 1
		}
		return -1
	})

	heap.Push(c)

	return &commitNodeIteratorByCTime{
		heap:         heap,
		seenExternal: seenExternal,
		seen:         seen,
	}
}

func (w *commitNodeIteratorByCTime) Next() (CommitNode, error) {
	var c CommitNode
	for {
		cIn, ok := w.heap.Pop()
		if !ok {
			return nil, io.EOF
		}
		c = cIn.(CommitNode)
		cID := c.ID()

		if w.seen[cID] || w.seenExternal[cID] {
			continue
		}

		w.seen[cID] = true

		for i, h := range c.ParentHashes() {
			if w.seen[h] || w.seenExternal[h] {
				continue
			}
			pc, err := c.ParentNode(i)
			if err != nil {
				return nil, err
			}
			w.heap.Push(pc)
		}

		return c, nil
	}
}

func (w *commitNodeIteratorByCTime) ForEach(cb func(CommitNode) error) error {
	for {
		c, err := w.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		err = cb(c)
		if err == storer.ErrStop {
			break
		}
		if err != nil {
			return err
		}
	}

	return nil
}

func (w *commitNodeIteratorByCTime) Close() {}