You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

content.go 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repofiles
  5. import (
  6. "net/url"
  7. "code.gitea.io/gitea/models"
  8. "code.gitea.io/gitea/modules/git"
  9. api "code.gitea.io/sdk/gitea"
  10. )
  11. // GetFileContents gets the meta data on a file's contents
  12. func GetFileContents(repo *models.Repository, treePath, ref string) (*api.FileContentResponse, error) {
  13. if ref == "" {
  14. ref = repo.DefaultBranch
  15. }
  16. // Check that the path given in opts.treePath is valid (not a git path)
  17. treePath = CleanUploadFileName(treePath)
  18. if treePath == "" {
  19. return nil, models.ErrFilenameInvalid{
  20. Path: treePath,
  21. }
  22. }
  23. gitRepo, err := git.OpenRepository(repo.RepoPath())
  24. if err != nil {
  25. return nil, err
  26. }
  27. // Get the commit object for the ref
  28. commit, err := gitRepo.GetCommit(ref)
  29. if err != nil {
  30. return nil, err
  31. }
  32. entry, err := commit.GetTreeEntryByPath(treePath)
  33. if err != nil {
  34. return nil, err
  35. }
  36. urlRef := ref
  37. if _, err := gitRepo.GetBranchCommit(ref); err == nil {
  38. urlRef = "branch/" + ref
  39. }
  40. selfURL, _ := url.Parse(repo.APIURL() + "/contents/" + treePath)
  41. gitURL, _ := url.Parse(repo.APIURL() + "/git/blobs/" + entry.ID.String())
  42. downloadURL, _ := url.Parse(repo.HTMLURL() + "/raw/" + urlRef + "/" + treePath)
  43. htmlURL, _ := url.Parse(repo.HTMLURL() + "/blob/" + ref + "/" + treePath)
  44. fileContent := &api.FileContentResponse{
  45. Name: entry.Name(),
  46. Path: treePath,
  47. SHA: entry.ID.String(),
  48. Size: entry.Size(),
  49. URL: selfURL.String(),
  50. HTMLURL: htmlURL.String(),
  51. GitURL: gitURL.String(),
  52. DownloadURL: downloadURL.String(),
  53. Type: string(entry.Type),
  54. Links: &api.FileLinksResponse{
  55. Self: selfURL.String(),
  56. GitURL: gitURL.String(),
  57. HTMLURL: htmlURL.String(),
  58. },
  59. }
  60. return fileContent, nil
  61. }