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.

compare.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. "path"
  7. "strings"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/base"
  10. "code.gitea.io/gitea/modules/context"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. )
  15. const (
  16. tplCompare base.TplName = "repo/diff/compare"
  17. )
  18. // ParseCompareInfo parse compare info between two commit for preparing comparing references
  19. func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.CompareInfo, string, string) {
  20. baseRepo := ctx.Repo.Repository
  21. // Get compared branches information
  22. // format: <base branch>...[<head repo>:]<head branch>
  23. // base<-head: master...head:feature
  24. // same repo: master...feature
  25. var (
  26. headUser *models.User
  27. headBranch string
  28. isSameRepo bool
  29. infoPath string
  30. err error
  31. )
  32. infoPath = ctx.Params("*")
  33. infos := strings.Split(infoPath, "...")
  34. if len(infos) != 2 {
  35. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  36. ctx.NotFound("CompareAndPullRequest", nil)
  37. return nil, nil, nil, nil, "", ""
  38. }
  39. baseBranch := infos[0]
  40. ctx.Data["BaseBranch"] = baseBranch
  41. // If there is no head repository, it means compare between same repository.
  42. headInfos := strings.Split(infos[1], ":")
  43. if len(headInfos) == 1 {
  44. isSameRepo = true
  45. headUser = ctx.Repo.Owner
  46. headBranch = headInfos[0]
  47. } else if len(headInfos) == 2 {
  48. headUser, err = models.GetUserByName(headInfos[0])
  49. if err != nil {
  50. if models.IsErrUserNotExist(err) {
  51. ctx.NotFound("GetUserByName", nil)
  52. } else {
  53. ctx.ServerError("GetUserByName", err)
  54. }
  55. return nil, nil, nil, nil, "", ""
  56. }
  57. headBranch = headInfos[1]
  58. isSameRepo = headUser.ID == ctx.Repo.Owner.ID
  59. } else {
  60. ctx.NotFound("CompareAndPullRequest", nil)
  61. return nil, nil, nil, nil, "", ""
  62. }
  63. ctx.Data["HeadUser"] = headUser
  64. ctx.Data["HeadBranch"] = headBranch
  65. ctx.Repo.PullRequest.SameRepo = isSameRepo
  66. // Check if base branch is valid.
  67. baseIsCommit := ctx.Repo.GitRepo.IsCommitExist(baseBranch)
  68. baseIsBranch := ctx.Repo.GitRepo.IsBranchExist(baseBranch)
  69. baseIsTag := ctx.Repo.GitRepo.IsTagExist(baseBranch)
  70. if !baseIsCommit && !baseIsBranch && !baseIsTag {
  71. // Check if baseBranch is short sha commit hash
  72. if baseCommit, _ := ctx.Repo.GitRepo.GetCommit(baseBranch); baseCommit != nil {
  73. baseBranch = baseCommit.ID.String()
  74. ctx.Data["BaseBranch"] = baseBranch
  75. baseIsCommit = true
  76. } else {
  77. ctx.NotFound("IsRefExist", nil)
  78. return nil, nil, nil, nil, "", ""
  79. }
  80. }
  81. ctx.Data["BaseIsCommit"] = baseIsCommit
  82. ctx.Data["BaseIsBranch"] = baseIsBranch
  83. ctx.Data["BaseIsTag"] = baseIsTag
  84. // Check if current user has fork of repository or in the same repository.
  85. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  86. if !has && !isSameRepo {
  87. ctx.Data["PageIsComparePull"] = false
  88. }
  89. var headGitRepo *git.Repository
  90. if isSameRepo {
  91. headRepo = ctx.Repo.Repository
  92. headGitRepo = ctx.Repo.GitRepo
  93. ctx.Data["BaseName"] = headUser.Name
  94. } else {
  95. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  96. ctx.Data["BaseName"] = baseRepo.OwnerName
  97. if err != nil {
  98. ctx.ServerError("OpenRepository", err)
  99. return nil, nil, nil, nil, "", ""
  100. }
  101. }
  102. // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
  103. permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
  104. if err != nil {
  105. headGitRepo.Close()
  106. ctx.ServerError("GetUserRepoPermission", err)
  107. return nil, nil, nil, nil, "", ""
  108. }
  109. if !permBase.CanRead(models.UnitTypeCode) {
  110. if log.IsTrace() {
  111. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  112. ctx.User,
  113. baseRepo,
  114. permBase)
  115. }
  116. headGitRepo.Close()
  117. ctx.NotFound("ParseCompareInfo", nil)
  118. return nil, nil, nil, nil, "", ""
  119. }
  120. // user should have permission to read headrepo's codes
  121. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  122. if err != nil {
  123. headGitRepo.Close()
  124. ctx.ServerError("GetUserRepoPermission", err)
  125. return nil, nil, nil, nil, "", ""
  126. }
  127. if !permHead.CanRead(models.UnitTypeCode) {
  128. if log.IsTrace() {
  129. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  130. ctx.User,
  131. headRepo,
  132. permHead)
  133. }
  134. headGitRepo.Close()
  135. ctx.NotFound("ParseCompareInfo", nil)
  136. return nil, nil, nil, nil, "", ""
  137. }
  138. // Check if head branch is valid.
  139. headIsCommit := ctx.Repo.GitRepo.IsCommitExist(headBranch)
  140. headIsBranch := headGitRepo.IsBranchExist(headBranch)
  141. headIsTag := headGitRepo.IsTagExist(headBranch)
  142. if !headIsCommit && !headIsBranch && !headIsTag {
  143. // Check if headBranch is short sha commit hash
  144. if headCommit, _ := ctx.Repo.GitRepo.GetCommit(headBranch); headCommit != nil {
  145. headBranch = headCommit.ID.String()
  146. ctx.Data["HeadBranch"] = headBranch
  147. headIsCommit = true
  148. } else {
  149. headGitRepo.Close()
  150. ctx.NotFound("IsRefExist", nil)
  151. return nil, nil, nil, nil, "", ""
  152. }
  153. }
  154. ctx.Data["HeadIsCommit"] = headIsCommit
  155. ctx.Data["HeadIsBranch"] = headIsBranch
  156. ctx.Data["HeadIsTag"] = headIsTag
  157. // Treat as pull request if both references are branches
  158. if ctx.Data["PageIsComparePull"] == nil {
  159. ctx.Data["PageIsComparePull"] = headIsBranch && baseIsBranch
  160. }
  161. if ctx.Data["PageIsComparePull"] == true && !permBase.CanReadIssuesOrPulls(true) {
  162. if log.IsTrace() {
  163. log.Trace("Permission Denied: User: %-v cannot create/read pull requests in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  164. ctx.User,
  165. baseRepo,
  166. permBase)
  167. }
  168. headGitRepo.Close()
  169. ctx.NotFound("ParseCompareInfo", nil)
  170. return nil, nil, nil, nil, "", ""
  171. }
  172. compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  173. if err != nil {
  174. headGitRepo.Close()
  175. ctx.ServerError("GetCompareInfo", err)
  176. return nil, nil, nil, nil, "", ""
  177. }
  178. ctx.Data["BeforeCommitID"] = compareInfo.MergeBase
  179. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  180. }
  181. // PrepareCompareDiff renders compare diff page
  182. func PrepareCompareDiff(
  183. ctx *context.Context,
  184. headUser *models.User,
  185. headRepo *models.Repository,
  186. headGitRepo *git.Repository,
  187. compareInfo *git.CompareInfo,
  188. baseBranch, headBranch string) bool {
  189. var (
  190. repo = ctx.Repo.Repository
  191. err error
  192. title string
  193. )
  194. // Get diff information.
  195. ctx.Data["CommitRepoLink"] = headRepo.Link()
  196. headCommitID := headBranch
  197. if ctx.Data["HeadIsCommit"] == false {
  198. if ctx.Data["HeadIsTag"] == true {
  199. headCommitID, err = headGitRepo.GetTagCommitID(headBranch)
  200. } else {
  201. headCommitID, err = headGitRepo.GetBranchCommitID(headBranch)
  202. }
  203. if err != nil {
  204. ctx.ServerError("GetRefCommitID", err)
  205. return false
  206. }
  207. }
  208. ctx.Data["AfterCommitID"] = headCommitID
  209. if headCommitID == compareInfo.MergeBase {
  210. ctx.Data["IsNothingToCompare"] = true
  211. return true
  212. }
  213. diff, err := models.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  214. compareInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  215. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  216. if err != nil {
  217. ctx.ServerError("GetDiffRange", err)
  218. return false
  219. }
  220. ctx.Data["Diff"] = diff
  221. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  222. headCommit, err := headGitRepo.GetCommit(headCommitID)
  223. if err != nil {
  224. ctx.ServerError("GetCommit", err)
  225. return false
  226. }
  227. compareInfo.Commits = models.ValidateCommitsWithEmails(compareInfo.Commits)
  228. compareInfo.Commits = models.ParseCommitsWithSignature(compareInfo.Commits)
  229. compareInfo.Commits = models.ParseCommitsWithStatus(compareInfo.Commits, headRepo)
  230. ctx.Data["Commits"] = compareInfo.Commits
  231. ctx.Data["CommitCount"] = compareInfo.Commits.Len()
  232. if ctx.Data["CommitCount"] == 0 {
  233. ctx.Data["PageIsComparePull"] = false
  234. }
  235. if compareInfo.Commits.Len() == 1 {
  236. c := compareInfo.Commits.Front().Value.(models.SignCommitWithStatuses)
  237. title = strings.TrimSpace(c.UserCommit.Summary())
  238. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  239. if len(body) > 1 {
  240. ctx.Data["content"] = strings.Join(body[1:], "\n")
  241. }
  242. } else {
  243. title = headBranch
  244. }
  245. ctx.Data["title"] = title
  246. ctx.Data["Username"] = headUser.Name
  247. ctx.Data["Reponame"] = headRepo.Name
  248. ctx.Data["IsImageFile"] = headCommit.IsImageFile
  249. headTarget := path.Join(headUser.Name, repo.Name)
  250. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", headCommitID)
  251. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", compareInfo.MergeBase)
  252. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", headCommitID)
  253. return false
  254. }
  255. // CompareDiff show different from one commit to another commit
  256. func CompareDiff(ctx *context.Context) {
  257. headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  258. if ctx.Written() {
  259. return
  260. }
  261. defer headGitRepo.Close()
  262. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch)
  263. if ctx.Written() {
  264. return
  265. }
  266. if ctx.Data["PageIsComparePull"] == true {
  267. headBranches, err := headGitRepo.GetBranches()
  268. if err != nil {
  269. ctx.ServerError("GetBranches", err)
  270. return
  271. }
  272. ctx.Data["HeadBranches"] = headBranches
  273. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  274. if err != nil {
  275. if !models.IsErrPullRequestNotExist(err) {
  276. ctx.ServerError("GetUnmergedPullRequest", err)
  277. return
  278. }
  279. } else {
  280. ctx.Data["HasPullRequest"] = true
  281. ctx.Data["PullRequest"] = pr
  282. ctx.HTML(200, tplCompareDiff)
  283. return
  284. }
  285. if !nothingToCompare {
  286. // Setup information for new form.
  287. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  288. if ctx.Written() {
  289. return
  290. }
  291. }
  292. }
  293. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  294. afterCommitID := ctx.Data["AfterCommitID"].(string)
  295. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + "..." + base.ShortSha(afterCommitID)
  296. ctx.Data["IsRepoToolbarCommits"] = true
  297. ctx.Data["IsDiffCompare"] = true
  298. ctx.Data["RequireHighlightJS"] = true
  299. ctx.Data["RequireTribute"] = true
  300. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  301. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  302. renderAttachmentSettings(ctx)
  303. ctx.HTML(200, tplCompare)
  304. }