aboutsummaryrefslogtreecommitdiff
path: root/object/parse.go
blob: 6a60407c446dfb278ab843815837fa4da4c1dce0 (about) (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
package object

import (
	"errors"
	"fmt"

	"lindenii.org/go/furgit/object/blob"
	"lindenii.org/go/furgit/object/commit"
	"lindenii.org/go/furgit/object/header"
	"lindenii.org/go/furgit/object/id"
	"lindenii.org/go/furgit/object/typ"
)

// ErrSizeMismatch indicates a mismatch
// between the size declared in the object header
// and the size of the object body.
var ErrSizeMismatch = errors.New("object: size mismatch")

// ParseWithHeader parses a loose object
// in "type size\x00body" format.
//
//nolint:ireturn
func ParseWithHeader(raw []byte, objectFormat id.ObjectFormat) (Object, error) {
	ty, size, headerLen, err := header.Parse(raw)
	if err != nil {
		return nil, err //nolint:wrapcheck
	}

	body := raw[headerLen:]
	if uint64(len(body)) != size {
		return nil, fmt.Errorf("%w: header declares %d bytes, body has %d", ErrSizeMismatch, size, len(body))
	}

	return ParseWithoutHeader(ty, body, objectFormat)
}

// ParseWithoutHeader parses a typed object body.
//
//nolint:ireturn
func ParseWithoutHeader(ty typ.Type, body []byte, objectFormat id.ObjectFormat) (Object, error) {
	switch ty {
	case typ.TypeBlob:
		return blob.Parse(body) //nolint:wrapcheck
	case typ.TypeTree:
		panic("TODO")
	case typ.TypeCommit:
		return commit.Parse(body, objectFormat) //nolint:wrapcheck
	case typ.TypeTag:
		panic("TODO")
	case typ.TypeUnknown:
		return nil, typ.ErrInvalidType
	default:
		return nil, typ.ErrInvalidType
	}
}