aboutsummaryrefslogtreecommitdiffstats
path: root/storage/filesystem/reference.go
blob: ae78efb96a587c1b1e5e689993eee7291e87852e (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
package filesystem

import (
	"gopkg.in/src-d/go-git.v4/core"
	"gopkg.in/src-d/go-git.v4/storage/filesystem/internal/dotgit"
)

type ReferenceStorage struct {
	dir  *dotgit.DotGit
	refs map[core.ReferenceName]*core.Reference
}

func (r *ReferenceStorage) Set(ref *core.Reference) error {
	return r.dir.SetRef(ref)
}

func (r *ReferenceStorage) Get(n core.ReferenceName) (*core.Reference, error) {
	if err := r.load(); err != nil {
		return nil, err
	}

	ref, ok := r.refs[n]
	if !ok {
		return nil, core.ErrReferenceNotFound
	}

	return ref, nil
}

func (r *ReferenceStorage) Iter() (core.ReferenceIter, error) {
	if err := r.load(); err != nil {
		return nil, err
	}

	var refs []*core.Reference
	for _, ref := range r.refs {
		refs = append(refs, ref)
	}

	return core.NewReferenceSliceIter(refs), nil
}

func (r *ReferenceStorage) load() error {
	if len(r.refs) != 0 {
		return nil
	}

	refs, err := r.dir.Refs()
	if err != nil {
		return err
	}

	r.refs = make(map[core.ReferenceName]*core.Reference, 0)
	for _, ref := range refs {
		r.refs[ref.Name()] = ref
	}

	return nil
}