aboutsummaryrefslogtreecommitdiffstats
path: root/bug/git_tree.go
blob: a5583bda4411affb342d83c84a915bae2c1f94eb (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
package bug

import (
	"fmt"
	"strings"

	"github.com/pkg/errors"

	"github.com/MichaelMure/git-bug/repository"
	"github.com/MichaelMure/git-bug/util/lamport"
)

type gitTree struct {
	opsEntry   repository.TreeEntry
	createTime lamport.Time
	editTime   lamport.Time
}

func readTree(repo repository.RepoData, hash repository.Hash) (*gitTree, error) {
	tree := &gitTree{}

	entries, err := repo.ReadTree(hash)
	if err != nil {
		return nil, errors.Wrap(err, "can't list git tree entries")
	}

	opsFound := false

	for _, entry := range entries {
		if entry.Name == opsEntryName {
			tree.opsEntry = entry
			opsFound = true
			continue
		}
		if strings.HasPrefix(entry.Name, createClockEntryPrefix) {
			n, err := fmt.Sscanf(entry.Name, createClockEntryPattern, &tree.createTime)
			if err != nil {
				return nil, errors.Wrap(err, "can't read create lamport time")
			}
			if n != 1 {
				return nil, fmt.Errorf("could not parse create time lamport value")
			}
		}
		if strings.HasPrefix(entry.Name, editClockEntryPrefix) {
			n, err := fmt.Sscanf(entry.Name, editClockEntryPattern, &tree.editTime)
			if err != nil {
				return nil, errors.Wrap(err, "can't read edit lamport time")
			}
			if n != 1 {
				return nil, fmt.Errorf("could not parse edit time lamport value")
			}
		}
	}

	if !opsFound {
		return nil, errors.New("invalid tree, missing the ops entry")
	}

	return tree, nil
}

func makeMediaTree(pack OperationPack) []repository.TreeEntry {
	var tree []repository.TreeEntry
	counter := 0
	added := make(map[repository.Hash]interface{})

	for _, ops := range pack.Operations {
		for _, file := range ops.GetFiles() {
			if _, has := added[file]; !has {
				tree = append(tree, repository.TreeEntry{
					ObjectType: repository.Blob,
					Hash:       file,
					// The name is not important here, we only need to
					// reference the blob.
					Name: fmt.Sprintf("file%d", counter),
				})
				counter++
				added[file] = struct{}{}
			}
		}
	}

	return tree
}