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.

blame.go 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. ctx.Data["CanDeleteFile"] = true
  104. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  105. } else if !ctx.Repo.IsViewBranch {
  106. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  107. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  108. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  109. }
  110. ctx.Data["FileSize"] = blob.Size()
  111. ctx.Data["FileName"] = blob.Name()
  112. blameReader, err := git.CreateBlameReader(models.RepoPath(userName, repoName), commitID, fileName)
  113. if err != nil {
  114. ctx.NotFound("CreateBlameReader", err)
  115. return
  116. }
  117. defer blameReader.Close()
  118. blameParts := make([]git.BlamePart, 0)
  119. for {
  120. blamePart, err := blameReader.NextPart()
  121. if err != nil {
  122. ctx.NotFound("NextPart", err)
  123. return
  124. }
  125. if blamePart == nil {
  126. break
  127. }
  128. blameParts = append(blameParts, *blamePart)
  129. }
  130. commitNames := make(map[string]models.UserCommit)
  131. commits := list.New()
  132. for _, part := range blameParts {
  133. sha := part.Sha
  134. if _, ok := commitNames[sha]; ok {
  135. continue
  136. }
  137. commit, err := ctx.Repo.GitRepo.GetCommit(sha)
  138. if err != nil {
  139. if git.IsErrNotExist(err) {
  140. ctx.NotFound("Repo.GitRepo.GetCommit", err)
  141. } else {
  142. ctx.ServerError("Repo.GitRepo.GetCommit", err)
  143. }
  144. return
  145. }
  146. commits.PushBack(commit)
  147. commitNames[commit.ID.String()] = models.UserCommit{}
  148. }
  149. commits = models.ValidateCommitsWithEmails(commits)
  150. for e := commits.Front(); e != nil; e = e.Next() {
  151. c := e.Value.(models.UserCommit)
  152. commitNames[c.ID.String()] = c
  153. }
  154. renderBlame(ctx, blameParts, commitNames)
  155. ctx.HTML(200, tplBlame)
  156. }
  157. func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]models.UserCommit) {
  158. repoLink := ctx.Repo.RepoLink
  159. var lines = make([]string, 0)
  160. var commitInfo bytes.Buffer
  161. var lineNumbers bytes.Buffer
  162. var codeLines bytes.Buffer
  163. var i = 0
  164. for pi, part := range blameParts {
  165. for index, line := range part.Lines {
  166. i++
  167. lines = append(lines, line)
  168. var attr = ""
  169. if len(part.Lines)-1 == index && len(blameParts)-1 != pi {
  170. attr = " bottom-line"
  171. }
  172. commit := commitNames[part.Sha]
  173. if index == 0 {
  174. // User avatar image
  175. avatar := ""
  176. commitSince := timeutil.TimeSinceUnix(timeutil.TimeStamp(commit.Author.When.Unix()), ctx.Data["Lang"].(string))
  177. if commit.User != nil {
  178. authorName := commit.Author.Name
  179. if len(commit.User.FullName) > 0 {
  180. authorName = commit.User.FullName
  181. }
  182. 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))
  183. } else {
  184. avatar = fmt.Sprintf(`<img class="ui avatar image" src="%s" title="%s"/>`, html.EscapeString(base.AvatarLink(commit.Author.Email)), html.EscapeString(commit.Author.Name))
  185. }
  186. 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))
  187. } else {
  188. commitInfo.WriteString(fmt.Sprintf(`<div class="blame-info%s">&#8203;</div>`, attr))
  189. }
  190. //Line number
  191. if len(part.Lines)-1 == index && len(blameParts)-1 != pi {
  192. lineNumbers.WriteString(fmt.Sprintf(`<span id="L%d" class="bottom-line">%d</span>`, i, i))
  193. } else {
  194. lineNumbers.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i, i))
  195. }
  196. //Code line
  197. line = gotemplate.HTMLEscapeString(line)
  198. if i != len(lines)-1 {
  199. line += "\n"
  200. }
  201. if len(part.Lines)-1 == index && len(blameParts)-1 != pi {
  202. codeLines.WriteString(fmt.Sprintf(`<li class="L%d bottom-line" rel="L%d">%s</li>`, i, i, line))
  203. } else {
  204. codeLines.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, i, i, line))
  205. }
  206. }
  207. }
  208. ctx.Data["BlameContent"] = gotemplate.HTML(codeLines.String())
  209. ctx.Data["BlameCommitInfo"] = gotemplate.HTML(commitInfo.String())
  210. ctx.Data["BlameLineNums"] = gotemplate.HTML(lineNumbers.String())
  211. }