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 13KB

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