File: object.go

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

package gitinterface

import (
	"errors"
	"fmt"
	"strconv"
)

type ObjectType uint

const (
	BlobObjectType ObjectType = iota + 1
	TreeObjectType
	CommitObjectType
	TagObjectType
)

var ErrInvalidObjectType = errors.New("unknown Git object type")

// HasObject returns true if an object with the specified Git ID exists in the
// repository.
func (r *Repository) HasObject(objectID Hash) bool {
	_, err := r.executor("cat-file", "-e", objectID.String()).executeString()
	return err == nil
}

func (r *Repository) GetObjectType(objectID Hash) (ObjectType, error) {
	objType, err := r.executor("cat-file", "-t", objectID.String()).executeString()
	if err != nil {
		return 0, fmt.Errorf("unable to inspect object type: %w", err)
	}

	switch objType {
	case "blob":
		return BlobObjectType, nil
	case "tree":
		return TreeObjectType, nil
	case "commit":
		return CommitObjectType, nil
	case "tag":
		return TagObjectType, nil
	default:
		return 0, ErrInvalidObjectType
	}
}

// GetObjectSize returns the size of the object with the specified Git ID.
func (r *Repository) GetObjectSize(objectID Hash) (uint64, error) {
	stdOut, err := r.executor("cat-file", "-s", objectID.String()).executeString()
	if err != nil {
		return 0, fmt.Errorf("unable to inspect object size: %w", err)
	}

	objSize, err := strconv.ParseUint(stdOut, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("unable to convert output to integer: %w", err)
	}
	return objSize, nil
}