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
63
64
65
66
67
68
69
70
71
72
73
|
// Copyright 2019 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 repofiles
import (
"net/url"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
)
// GetFileContents gets the meta data on a file's contents
func GetFileContents(repo *models.Repository, treePath, ref string) (*api.FileContentResponse, error) {
if ref == "" {
ref = repo.DefaultBranch
}
// Check that the path given in opts.treePath is valid (not a git path)
treePath = CleanUploadFileName(treePath)
if treePath == "" {
return nil, models.ErrFilenameInvalid{
Path: treePath,
}
}
gitRepo, err := git.OpenRepository(repo.RepoPath())
if err != nil {
return nil, err
}
// Get the commit object for the ref
commit, err := gitRepo.GetCommit(ref)
if err != nil {
return nil, err
}
entry, err := commit.GetTreeEntryByPath(treePath)
if err != nil {
return nil, err
}
urlRef := ref
if _, err := gitRepo.GetBranchCommit(ref); err == nil {
urlRef = "branch/" + ref
}
selfURL, _ := url.Parse(repo.APIURL() + "/contents/" + treePath)
gitURL, _ := url.Parse(repo.APIURL() + "/git/blobs/" + entry.ID.String())
downloadURL, _ := url.Parse(repo.HTMLURL() + "/raw/" + urlRef + "/" + treePath)
htmlURL, _ := url.Parse(repo.HTMLURL() + "/blob/" + ref + "/" + treePath)
fileContent := &api.FileContentResponse{
Name: entry.Name(),
Path: treePath,
SHA: entry.ID.String(),
Size: entry.Size(),
URL: selfURL.String(),
HTMLURL: htmlURL.String(),
GitURL: gitURL.String(),
DownloadURL: downloadURL.String(),
Type: entry.Type(),
Links: &api.FileLinksResponse{
Self: selfURL.String(),
GitURL: gitURL.String(),
HTMLURL: htmlURL.String(),
},
}
return fileContent, nil
}
|