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.

263 lines
7.7 KiB

  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 repo
  5. import (
  6. "bytes"
  7. "container/list"
  8. "fmt"
  9. "html"
  10. gotemplate "html/template"
  11. "net/url"
  12. "strings"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/highlight"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/markup"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. )
  23. const (
  24. tplBlame base.TplName = "repo/home"
  25. )
  26. // RefBlame render blame page
  27. func RefBlame(ctx *context.Context) {
  28. fileName := ctx.Repo.TreePath
  29. if len(fileName) == 0 {
  30. ctx.NotFound("Blame FileName", nil)
  31. return
  32. }
  33. userName := ctx.Repo.Owner.Name
  34. repoName := ctx.Repo.Repository.Name
  35. commitID := ctx.Repo.CommitID
  36. commit, err := ctx.Repo.GitRepo.GetCommit(commitID)
  37. if err != nil {
  38. if git.IsErrNotExist(err) {
  39. ctx.NotFound("Repo.GitRepo.GetCommit", err)
  40. } else {
  41. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  42. }
  43. return
  44. }
  45. if len(commitID) != 40 {
  46. commitID = commit.ID.String()
  47. }
  48. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  49. treeLink := branchLink
  50. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  51. if len(ctx.Repo.TreePath) > 0 {
  52. treeLink += "/" + ctx.Repo.TreePath
  53. }
  54. var treeNames []string
  55. paths := make([]string, 0, 5)
  56. if len(ctx.Repo.TreePath) > 0 {
  57. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  58. for i := range treeNames {
  59. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  60. }
  61. ctx.Data["HasParentPath"] = true
  62. if len(paths)-2 >= 0 {
  63. ctx.Data["ParentPath"] = "/" + paths[len(paths)-1]
  64. }
  65. }
  66. // Show latest commit info of repository in table header,
  67. // or of directory if not in root directory.
  68. latestCommit := ctx.Repo.Commit
  69. if len(ctx.Repo.TreePath) > 0 {
  70. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  71. if err != nil {
  72. ctx.ServerError("GetCommitByPath", err)
  73. return
  74. }
  75. }
  76. ctx.Data["LatestCommit"] = latestCommit
  77. ctx.Data["LatestCommitVerification"] = models.ParseCommitWithSignature(latestCommit)
  78. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  79. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  80. if err != nil {
  81. log.Error("GetLatestCommitStatus: %v", err)
  82. }
  83. // Get current entry user currently looking at.
  84. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  85. if err != nil {
  86. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  87. return
  88. }
  89. blob := entry.Blob()
  90. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  91. ctx.Data["Paths"] = paths
  92. ctx.Data["TreeLink"] = treeLink
  93. ctx.Data["TreeNames"] = treeNames
  94. ctx.Data["BranchLink"] = branchLink
  95. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(entry.Name())
  96. if !markup.IsReadmeFile(blob.Name()) {
  97. ctx.Data["RequireHighlightJS"] = true
  98. }
  99. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  100. ctx.Data["PageIsViewCode"] = true
  101. ctx.Data["IsBlame"] = true
  102. if ctx.Repo.CanEnableEditor() {
  103. // Check LFS Lock
  104. lfsLock, err := ctx.Repo.Repository.GetTreePathLock(ctx.Repo.TreePath)
  105. if err != nil {
  106. ctx.ServerError("GetTreePathLock", err)
  107. return
  108. }
  109. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  110. ctx.Data["CanDeleteFile"] = false
  111. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  112. } else {
  113. ctx.Data["CanDeleteFile"] = true
  114. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  115. }
  116. } else if !ctx.Repo.IsViewBranch {
  117. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  118. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  119. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  120. }
  121. ctx.Data["FileSize"] = blob.Size()
  122. ctx.Data["FileName"] = blob.Name()
  123. blameReader, err := git.CreateBlameReader(models.RepoPath(userName, repoName), commitID, fileName)
  124. if err != nil {
  125. ctx.NotFound("CreateBlameReader", err)
  126. return
  127. }
  128. defer blameReader.Close()
  129. blameParts := make([]git.BlamePart, 0)
  130. for {
  131. blamePart, err := blameReader.NextPart()
  132. if err != nil {
  133. ctx.NotFound("NextPart", err)
  134. return
  135. }
  136. if blamePart == nil {
  137. break
  138. }
  139. blameParts = append(blameParts, *blamePart)
  140. }
  141. commitNames := make(map[string]models.UserCommit)
  142. commits := list.New()
  143. for _, part := range blameParts {
  144. sha := part.Sha
  145. if _, ok := commitNames[sha]; ok {
  146. continue
  147. }
  148. commit, err := ctx.Repo.GitRepo.GetCommit(sha)
  149. if err != nil {
  150. if git.IsErrNotExist(err) {
  151. ctx.NotFound("Repo.GitRepo.GetCommit", err)
  152. } else {
  153. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  154. }
  155. return
  156. }
  157. commits.PushBack(commit)
  158. commitNames[commit.ID.String()] = models.UserCommit{}
  159. }
  160. commits = models.ValidateCommitsWithEmails(commits)
  161. for e := commits.Front(); e != nil; e = e.Next() {
  162. c := e.Value.(models.UserCommit)
  163. commitNames[c.ID.String()] = c
  164. }
  165. renderBlame(ctx, blameParts, commitNames)
  166. ctx.HTML(200, tplBlame)
  167. }
  168. func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]models.UserCommit) {
  169. repoLink := ctx.Repo.RepoLink
  170. var lines = make([]string, 0)
  171. var commitInfo bytes.Buffer
  172. var lineNumbers bytes.Buffer
  173. var codeLines bytes.Buffer
  174. var i = 0
  175. for pi, part := range blameParts {
  176. for index, line := range part.Lines {
  177. i++
  178. lines = append(lines, line)
  179. var attr = ""
  180. if len(part.Lines)-1 == index && len(blameParts)-1 != pi {
  181. attr = " bottom-line"
  182. }
  183. commit := commitNames[part.Sha]
  184. if index == 0 {
  185. // User avatar image
  186. avatar := ""
  187. commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Data["Lang"].(string))
  188. if commit.User != nil {
  189. authorName := commit.Author.Name
  190. if len(commit.User.FullName) > 0 {
  191. authorName = commit.User.FullName
  192. }
  193. avatar = fmt.Sprintf(`<a href="%s/%s"><img class="ui avatar image" src="%s" title="%s" alt=""/></a>`, setting.AppSubURL, url.PathEscape(commit.User.Name), commit.User.RelAvatarLink(), html.EscapeString(authorName))
  194. } else {
  195. avatar = fmt.Sprintf(`<img class="ui avatar image" src="%s" title="%s"/>`, html.EscapeString(models.AvatarLink(commit.Author.Email)), html.EscapeString(commit.Author.Name))
  196. }
  197. commitInfo.WriteString(fmt.Sprintf(`<div class="blame-info%s"><div class="blame-data"><div class="blame-avatar">%s</div><div class="blame-message"><a href="%s/commit/%s" title="%[5]s">%[5]s</a></div><div class="blame-time">%s</div></div></div>`, attr, avatar, repoLink, part.Sha, html.EscapeString(commit.CommitMessage), commitSince))
  198. } else {
  199. commitInfo.WriteString(fmt.Sprintf(`<div class="blame-info%s">&#8203;</div>`, attr))
  200. }
  201. //Line number
  202. if len(part.Lines)-1 == index && len(blameParts)-1 != pi {
  203. lineNumbers.WriteString(fmt.Sprintf(`<span id="L%d" class="bottom-line">%d</span>`, i, i))
  204. } else {
  205. lineNumbers.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i, i))
  206. }
  207. //Code line
  208. line = gotemplate.HTMLEscapeString(line)
  209. if i != len(lines)-1 {
  210. line += "\n"
  211. }
  212. if len(part.Lines)-1 == index && len(blameParts)-1 != pi {
  213. codeLines.WriteString(fmt.Sprintf(`<li class="L%d bottom-line" rel="L%d">%s</li>`, i, i, line))
  214. } else {
  215. codeLines.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, i, i, line))
  216. }
  217. }
  218. }
  219. ctx.Data["BlameContent"] = gotemplate.HTML(codeLines.String())
  220. ctx.Data["BlameCommitInfo"] = gotemplate.HTML(commitInfo.String())
  221. ctx.Data["BlameLineNums"] = gotemplate.HTML(lineNumbers.String())
  222. }