Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add API to serve blob or LFS file content #19689

Merged
merged 18 commits into from
Jun 4, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions integrations/api_repo_file_get_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2022 The Gitea 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 integrations

import (
"net/http"
"net/url"
"os"
"testing"

"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert"
)

func TestAPIGetRawFileOrLFS(t *testing.T) {
defer prepareTestEnv(t)()

// Test with raw file
req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/media/README.md")
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, "# repo1\n\nDescription for repo1", resp.Body.String())

// Test with LFS
httpContext := NewAPITestContext(t, "user2", "repo1")

onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = httpContext.GitPath()
dstPath, err := os.MkdirTemp("", httpContext.Reponame)
assert.NoError(t, err)
defer util.RemoveAll(dstPath)

u.Path = httpContext.GitPath()
u.User = url.UserPassword("user2", userPassword)

t.Run("Clone", doGitClone(dstPath, u))

dstPath2, err := os.MkdirTemp("", httpContext.Reponame)
assert.NoError(t, err)
defer util.RemoveAll(dstPath2)

t.Run("Partial Clone", doPartialGitClone(dstPath2, u))

lfs, _ := lfsCommitAndPushTest(t, dstPath)

reqLFS := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/media/"+lfs)
respLFS := MakeRequestNilResponseRecorder(t, reqLFS, http.StatusOK)
assert.Equal(t, littleSize, respLFS.Length)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure, but seems like we need to do some cleanup here in order to not conflict with other tests.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed it t create a new repo and delete it afterwards.

})
}
1 change: 1 addition & 0 deletions routers/api/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,7 @@ func Routes() *web.Route {
Delete(reqAdmin(), repo.DeleteTeam)
}, reqToken())
m.Get("/raw/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFile)
m.Get("/media/*", context.ReferencesGitRepo(), context.RepoRefForAPI, reqRepoReader(unit.TypeCode), repo.GetRawFileOrLFS)
m.Get("/archive/*", reqRepoReader(unit.TypeCode), repo.GetArchive)
m.Combo("/forks").Get(repo.ListForks).
Post(reqToken(), reqRepoReader(unit.TypeCode), bind(api.CreateForkOption{}), repo.CreateFork)
Expand Down
108 changes: 108 additions & 0 deletions routers/api/v1/repo/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ import (
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/httpcache"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/common"
Expand Down Expand Up @@ -75,6 +79,110 @@ func GetRawFile(ctx *context.APIContext) {
}
}

// GetRawFileOrLFS get a file by repo's path, redirecting to LFS if necessary.
func GetRawFileOrLFS(ctx *context.APIContext) {
// swagger:operation GET /repos/{owner}/{repo}/media/{filepath} repository repoGetRawFileOrLFS
// ---
// summary: Get a file or it's LFS object from a repository
// parameters:
// - name: owner
// in: path
// description: owner of the repo
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repo
// type: string
// required: true
// - name: filepath
// in: path
// description: filepath of the file to get
// type: string
// required: true
// - name: ref
// in: query
// description: "The name of the commit/branch/tag. Default the repository’s default branch (usually master)"
// type: string
// required: false
// responses:
// 200:
// description: Returns raw file content.
// "404":
// "$ref": "#/responses/notFound"

if ctx.Repo.Repository.IsEmpty {
ctx.NotFound()
return
}

blob, lastModified := getBlobForEntry(ctx)
if ctx.Written() {
return
}

if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
return
}

dataRc, err := blob.DataAsync()
if err != nil {
ctx.ServerError("DataAsync", err)
return
}
defer func() {
if err = dataRc.Close(); err != nil {
log.Error("Close: %v", err)
}
}()

pointer, _ := lfs.ReadPointer(dataRc)
zeripath marked this conversation as resolved.
Show resolved Hide resolved
if pointer.IsValid() {
meta, err := models.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid)
if err != nil {
if err == models.ErrLFSObjectNotExist {
if err := common.ServeBlob(ctx.Context, blob, lastModified); err != nil {
ctx.ServerError("ServeBlob", err)
}
} else {
ctx.ServerError("GetLFSMetaObjectByOid", err)
}
qwerty287 marked this conversation as resolved.
Show resolved Hide resolved
return
}
if httpcache.HandleGenericETagCache(ctx.Req, ctx.Resp, `"`+pointer.Oid+`"`) {
return
}

if setting.LFS.ServeDirect {
// If we have a signed url (S3, object storage), redirect to this directly.
u, err := storage.LFS.URL(pointer.RelativePath(), blob.Name())
if u != nil && err == nil {
ctx.Redirect(u.String())
return
}
}

lfsDataRc, err := lfs.ReadMetaObject(meta.Pointer)
if err != nil {
ctx.ServerError("ReadMetaObject", err)
return
}
defer func() {
if err = lfsDataRc.Close(); err != nil {
log.Error("Close: %v", err)
}
}()
if err := common.ServeData(ctx.Context, ctx.Repo.TreePath, meta.Size, lfsDataRc); err != nil {
ctx.ServerError("ServeData", err)
}
return
}

if err := common.ServeBlob(ctx.Context, blob, lastModified); err != nil {
ctx.ServerError("ServeBlob", err)
}
}

func getBlobForEntry(ctx *context.APIContext) (blob *git.Blob, lastModified time.Time) {
entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
if err != nil {
Expand Down
46 changes: 46 additions & 0 deletions templates/swagger/v1_json.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -7150,6 +7150,52 @@
}
}
},
"/repos/{owner}/{repo}/media/{filepath}": {
"get": {
"tags": [
"repository"
],
"summary": "Get a file or it's LFS object from a repository",
"operationId": "repoGetRawFileOrLFS",
"parameters": [
{
"type": "string",
"description": "owner of the repo",
"name": "owner",
"in": "path",
"required": true
},
{
"type": "string",
"description": "name of the repo",
"name": "repo",
"in": "path",
"required": true
},
{
"type": "string",
"description": "filepath of the file to get",
"name": "filepath",
"in": "path",
"required": true
},
{
"type": "string",
"description": "The name of the commit/branch/tag. Default the repository’s default branch (usually master)",
"name": "ref",
"in": "query"
}
],
"responses": {
"200": {
"description": "Returns raw file content."
},
"404": {
"$ref": "#/responses/notFound"
}
}
}
},
"/repos/{owner}/{repo}/milestones": {
"get": {
"produces": [
Expand Down