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

import (
	"fmt"
	"io"
	"os"

	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/format/objfile"
	"github.com/go-git/go-git/v5/utils/ioutil"
)

var _ (plumbing.EncodedObject) = &EncodedObject{}

type EncodedObject struct {
	dir *DotGit
	h   plumbing.Hash
	t   plumbing.ObjectType
	sz  int64
}

func (e *EncodedObject) Hash() plumbing.Hash {
	return e.h
}

func (e *EncodedObject) Reader() (io.ReadCloser, error) {
	f, err := e.dir.Object(e.h)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, plumbing.ErrObjectNotFound
		}

		return nil, err
	}
	r, err := objfile.NewReader(f)
	if err != nil {
		return nil, err
	}

	t, size, err := r.Header()
	if err != nil {
		_ = r.Close()
		return nil, err
	}
	if t != e.t {
		_ = r.Close()
		return nil, objfile.ErrHeader
	}
	if size != e.sz {
		_ = r.Close()
		return nil, objfile.ErrHeader
	}
	return ioutil.NewReadCloserWithCloser(r, f.Close), nil
}

func (e *EncodedObject) SetType(plumbing.ObjectType) {}

func (e *EncodedObject) Type() plumbing.ObjectType {
	return e.t
}

func (e *EncodedObject) Size() int64 {
	return e.sz
}

func (e *EncodedObject) SetSize(int64) {}

func (e *EncodedObject) Writer() (io.WriteCloser, error) {
	return nil, fmt.Errorf("Not supported")
}

func NewEncodedObject(dir *DotGit, h plumbing.Hash, t plumbing.ObjectType, size int64) *EncodedObject {
	return &EncodedObject{
		dir: dir,
		h:   h,
		t:   t,
		sz:  size,
	}
}