From 2f2114851ca1abf8400cd9473ba135817f119f82 Mon Sep 17 00:00:00 2001 From: Yehonatan Ezron <37303618+jonatan5524@users.noreply.github.com> Date: Sat, 25 Jun 2022 12:31:00 +0300 Subject: [PATCH] feat(repo_blob): add CatFileBlob (#79) Co-authored-by: Joe Chen --- repo_blob.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++ repo_blob_test.go | 31 ++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 repo_blob.go create mode 100644 repo_blob_test.go diff --git a/repo_blob.go b/repo_blob.go new file mode 100644 index 00000000..e9f04c0c --- /dev/null +++ b/repo_blob.go @@ -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 +} diff --git a/repo_blob_test.go b/repo_blob_test.go new file mode 100644 index 00000000..7def8039 --- /dev/null +++ b/repo_blob_test.go @@ -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()) + }) +}