aboutsummaryrefslogtreecommitdiff
path: root/internal/testgit/object.go
blob: cbdfce76e99e4cd1f355ae951072d679d5328e3f (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
package testgit

import (
	"fmt"
	"io"
	"strings"
	"testing"

	"lindenii.org/go/furgit/object/id"
	"lindenii.org/go/furgit/object/typ"
)

// HashObject hashes and writes an object,
// and returns its object ID.
func (repo *Repo) HashObject(tb testing.TB, ty typ.Type, body io.Reader) (id.ObjectID, error) {
	tb.Helper()

	stdout, err := repo.Run(tb, body, "git", "hash-object", "-t", ty.Name(), "-w", "--stdin", "--literally")
	if err != nil {
		return id.ObjectID{}, fmt.Errorf("hash-object: %w", err)
	}

	objectID, err := repo.objectFormat.FromString(strings.TrimSuffix(string(stdout), "\n"))
	if err != nil {
		return id.ObjectID{}, fmt.Errorf("parse git hash-object output %q: %w", string(stdout), err)
	}

	return objectID, nil
}

// CatFile returns the raw content of an object
// (without the "type size\x00" header).
func (repo *Repo) CatFile(tb testing.TB, ty typ.Type, oid id.ObjectID) ([]byte, error) {
	tb.Helper()

	stdout, err := repo.Run(tb, nil, "git", "cat-file", ty.Name(), oid.String())
	if err != nil {
		return nil, fmt.Errorf("cat-file: %w", err)
	}

	return stdout, nil
}