File: blob.go

package info (click to toggle)
gittuf 0.12.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,692 kB
  • sloc: python: 85; makefile: 58; sh: 1
file content (44 lines) | stat: -rw-r--r-- 1,278 bytes parent folder | download | duplicates (3)
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
// Copyright The gittuf Authors
// SPDX-License-Identifier: Apache-2.0

package gitinterface

import (
	"bytes"
	"fmt"
	"io"
)

// ReadBlob returns the contents of the blob referenced by blobID.
func (r *Repository) ReadBlob(blobID Hash) ([]byte, error) {
	objType, err := r.executor("cat-file", "-t", blobID.String()).executeString()
	if err != nil {
		return nil, fmt.Errorf("unable to inspect if object is blob: %w", err)
	} else if objType != "blob" {
		return nil, fmt.Errorf("requested Git ID '%s' is not a blob object", blobID.String())
	}

	stdOut, stdErr, err := r.executor("cat-file", "-p", blobID.String()).execute()
	if err != nil {
		return nil, fmt.Errorf("unable to read blob: %s", stdErr)
	}

	return io.ReadAll(stdOut)
}

// WriteBlob creates a blob object with the specified contents and returns the
// ID of the resultant blob.
func (r *Repository) WriteBlob(contents []byte) (Hash, error) {
	stdInBuf := bytes.NewBuffer(contents)
	objID, err := r.executor("hash-object", "-t", "blob", "-w", "--stdin").withStdIn(stdInBuf).executeString()
	if err != nil {
		return ZeroHash, fmt.Errorf("unable to write blob: %w", err)
	}

	hash, err := NewHash(objID)
	if err != nil {
		return ZeroHash, fmt.Errorf("invalid Git ID for blob: %w", err)
	}

	return hash, nil
}