Skip to content

Commit

Permalink
feat(repo_blob): add CatFileBlob (#79)
Browse files Browse the repository at this point in the history
Co-authored-by: Joe Chen <[email protected]>
  • Loading branch information
jonatan5524 and unknwon authored Jun 25, 2022
1 parent 1bcceef commit 2f21148
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
51 changes: 51 additions & 0 deletions repo_blob.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package git

import "time"

// CatFileBlobOptions contains optional arguments for verifying the objects.
//
// Docs: https://git-scm.com/docs/git-cat-file#Documentation/git-cat-file.txt
type CatFileBlobOptions struct {
// The timeout duration before giving up for each shell command execution.
// The default timeout duration will be used when not supplied.
Timeout time.Duration
// The additional options to be passed to the underlying git.
CommandOptions
}

// CatFileBlob returns the blob corresponding to the given revision of the repository.
func (r *Repository) CatFileBlob(rev string, opts ...CatFileBlobOptions) (*Blob, error) {
var opt CatFileBlobOptions
if len(opts) > 0 {
opt = opts[0]
}

rev, err := r.RevParse(rev, RevParseOptions{Timeout: opt.Timeout}) //nolint
if err != nil {
return nil, err
}

typ, err := r.CatFileType(rev)
if err != nil {
return nil, err
}

if typ != ObjectBlob {
return nil, ErrNotBlob
}

return &Blob{
TreeEntry: &TreeEntry{
mode: EntryBlob,
typ: ObjectBlob,
id: MustIDFromString(rev),
parent: &Tree{
repo: r,
},
},
}, nil
}
31 changes: 31 additions & 0 deletions repo_blob_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2022 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package git

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestRepository_CatFileBlob(t *testing.T) {
t.Run("not a blob", func(t *testing.T) {
_, err := testrepo.CatFileBlob("007cb92318c7bd3b56908ea8c2e54370245562f8")
assert.Equal(t, ErrNotBlob, err)
})

t.Run("get a blob, no full rev hash", func(t *testing.T) {
b, err := testrepo.CatFileBlob("021a")
require.NoError(t, err)
assert.True(t, b.IsBlob())
})

t.Run("get a blob", func(t *testing.T) {
b, err := testrepo.CatFileBlob("021a721a61a1de65865542c405796d1eb985f784")
require.NoError(t, err)
assert.True(t, b.IsBlob())
})
}

0 comments on commit 2f21148

Please sign in to comment.