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.2KB

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