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

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