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

blame.go 9.6 kB

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