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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. headGitRepo.Close()
  144. ctx.ServerError("GetUserRepoPermission", err)
  145. return nil, nil, nil, nil, "", ""
  146. }
  147. if !permBase.CanRead(models.UnitTypeCode) {
  148. if log.IsTrace() {
  149. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  150. ctx.User,
  151. baseRepo,
  152. permBase)
  153. }
  154. headGitRepo.Close()
  155. ctx.NotFound("ParseCompareInfo", nil)
  156. return nil, nil, nil, nil, "", ""
  157. }
  158. // user should have permission to read headrepo's codes
  159. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  160. if err != nil {
  161. headGitRepo.Close()
  162. ctx.ServerError("GetUserRepoPermission", err)
  163. return nil, nil, nil, nil, "", ""
  164. }
  165. if !permHead.CanRead(models.UnitTypeCode) {
  166. if log.IsTrace() {
  167. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  168. ctx.User,
  169. headRepo,
  170. permHead)
  171. }
  172. headGitRepo.Close()
  173. ctx.NotFound("ParseCompareInfo", nil)
  174. return nil, nil, nil, nil, "", ""
  175. }
  176. // Check if head branch is valid.
  177. headIsCommit := ctx.Repo.GitRepo.IsCommitExist(headBranch)
  178. headIsBranch := headGitRepo.IsBranchExist(headBranch)
  179. headIsTag := headGitRepo.IsTagExist(headBranch)
  180. if !headIsCommit && !headIsBranch && !headIsTag {
  181. // Check if headBranch is short sha commit hash
  182. if headCommit, _ := ctx.Repo.GitRepo.GetCommit(headBranch); headCommit != nil {
  183. headBranch = headCommit.ID.String()
  184. ctx.Data["HeadBranch"] = headBranch
  185. headIsCommit = true
  186. } else {
  187. headGitRepo.Close()
  188. ctx.NotFound("IsRefExist", nil)
  189. return nil, nil, nil, nil, "", ""
  190. }
  191. }
  192. ctx.Data["HeadIsCommit"] = headIsCommit
  193. ctx.Data["HeadIsBranch"] = headIsBranch
  194. ctx.Data["HeadIsTag"] = headIsTag
  195. // Treat as pull request if both references are branches
  196. if ctx.Data["PageIsComparePull"] == nil {
  197. ctx.Data["PageIsComparePull"] = headIsBranch && baseIsBranch
  198. }
  199. if ctx.Data["PageIsComparePull"] == true && !permBase.CanReadIssuesOrPulls(true) {
  200. if log.IsTrace() {
  201. log.Trace("Permission Denied: User: %-v cannot create/read pull requests in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  202. ctx.User,
  203. baseRepo,
  204. permBase)
  205. }
  206. headGitRepo.Close()
  207. ctx.NotFound("ParseCompareInfo", nil)
  208. return nil, nil, nil, nil, "", ""
  209. }
  210. compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  211. if err != nil {
  212. headGitRepo.Close()
  213. ctx.ServerError("GetCompareInfo", err)
  214. return nil, nil, nil, nil, "", ""
  215. }
  216. ctx.Data["BeforeCommitID"] = compareInfo.MergeBase
  217. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  218. }
  219. // PrepareCompareDiff renders compare diff page
  220. func PrepareCompareDiff(
  221. ctx *context.Context,
  222. headUser *models.User,
  223. headRepo *models.Repository,
  224. headGitRepo *git.Repository,
  225. compareInfo *git.CompareInfo,
  226. baseBranch, headBranch string) bool {
  227. var (
  228. repo = ctx.Repo.Repository
  229. err error
  230. title string
  231. )
  232. // Get diff information.
  233. ctx.Data["CommitRepoLink"] = headRepo.Link()
  234. headCommitID := headBranch
  235. if ctx.Data["HeadIsCommit"] == false {
  236. if ctx.Data["HeadIsTag"] == true {
  237. headCommitID, err = headGitRepo.GetTagCommitID(headBranch)
  238. } else {
  239. headCommitID, err = headGitRepo.GetBranchCommitID(headBranch)
  240. }
  241. if err != nil {
  242. ctx.ServerError("GetRefCommitID", err)
  243. return false
  244. }
  245. }
  246. ctx.Data["AfterCommitID"] = headCommitID
  247. if headCommitID == compareInfo.MergeBase {
  248. ctx.Data["IsNothingToCompare"] = true
  249. return true
  250. }
  251. diff, err := gitdiff.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  252. compareInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  253. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  254. if err != nil {
  255. ctx.ServerError("GetDiffRange", err)
  256. return false
  257. }
  258. ctx.Data["Diff"] = diff
  259. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  260. headCommit, err := headGitRepo.GetCommit(headCommitID)
  261. if err != nil {
  262. ctx.ServerError("GetCommit", err)
  263. return false
  264. }
  265. baseGitRepo := ctx.Repo.GitRepo
  266. baseCommitID := baseBranch
  267. if ctx.Data["BaseIsCommit"] == false {
  268. if ctx.Data["BaseIsTag"] == true {
  269. baseCommitID, err = baseGitRepo.GetTagCommitID(baseBranch)
  270. } else {
  271. baseCommitID, err = baseGitRepo.GetBranchCommitID(baseBranch)
  272. }
  273. if err != nil {
  274. ctx.ServerError("GetRefCommitID", err)
  275. return false
  276. }
  277. }
  278. baseCommit, err := baseGitRepo.GetCommit(baseCommitID)
  279. if err != nil {
  280. ctx.ServerError("GetCommit", err)
  281. return false
  282. }
  283. compareInfo.Commits = models.ValidateCommitsWithEmails(compareInfo.Commits)
  284. compareInfo.Commits = models.ParseCommitsWithSignature(compareInfo.Commits)
  285. compareInfo.Commits = models.ParseCommitsWithStatus(compareInfo.Commits, headRepo)
  286. ctx.Data["Commits"] = compareInfo.Commits
  287. ctx.Data["CommitCount"] = compareInfo.Commits.Len()
  288. if ctx.Data["CommitCount"] == 0 {
  289. ctx.Data["PageIsComparePull"] = false
  290. }
  291. if compareInfo.Commits.Len() == 1 {
  292. c := compareInfo.Commits.Front().Value.(models.SignCommitWithStatuses)
  293. title = strings.TrimSpace(c.UserCommit.Summary())
  294. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  295. if len(body) > 1 {
  296. ctx.Data["content"] = strings.Join(body[1:], "\n")
  297. }
  298. } else {
  299. title = headBranch
  300. }
  301. ctx.Data["title"] = title
  302. ctx.Data["Username"] = headUser.Name
  303. ctx.Data["Reponame"] = headRepo.Name
  304. setImageCompareContext(ctx, baseCommit, headCommit)
  305. headTarget := path.Join(headUser.Name, repo.Name)
  306. setPathsCompareContext(ctx, baseCommit, headCommit, headTarget)
  307. return false
  308. }
  309. // parseBaseRepoInfo parse base repository if current repo is forked.
  310. // The "base" here means the repository where current repo forks from,
  311. // not the repository fetch from current URL.
  312. func parseBaseRepoInfo(ctx *context.Context, repo *models.Repository) error {
  313. if !repo.IsFork {
  314. return nil
  315. }
  316. if err := repo.GetBaseRepo(); err != nil {
  317. return err
  318. }
  319. if err := repo.BaseRepo.GetOwnerName(); err != nil {
  320. return err
  321. }
  322. baseGitRepo, err := git.OpenRepository(models.RepoPath(repo.BaseRepo.OwnerName, repo.BaseRepo.Name))
  323. if err != nil {
  324. return err
  325. }
  326. defer baseGitRepo.Close()
  327. ctx.Data["BaseRepoBranches"], err = baseGitRepo.GetBranches()
  328. if err != nil {
  329. return err
  330. }
  331. return nil
  332. }
  333. // CompareDiff show different from one commit to another commit
  334. func CompareDiff(ctx *context.Context) {
  335. headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  336. if ctx.Written() {
  337. return
  338. }
  339. defer headGitRepo.Close()
  340. if err := parseBaseRepoInfo(ctx, headRepo); err != nil {
  341. ctx.ServerError("parseBaseRepoInfo", err)
  342. return
  343. }
  344. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch)
  345. if ctx.Written() {
  346. return
  347. }
  348. if ctx.Data["PageIsComparePull"] == true {
  349. headBranches, err := headGitRepo.GetBranches()
  350. if err != nil {
  351. ctx.ServerError("GetBranches", err)
  352. return
  353. }
  354. ctx.Data["HeadBranches"] = headBranches
  355. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  356. if err != nil {
  357. if !models.IsErrPullRequestNotExist(err) {
  358. ctx.ServerError("GetUnmergedPullRequest", err)
  359. return
  360. }
  361. } else {
  362. ctx.Data["HasPullRequest"] = true
  363. ctx.Data["PullRequest"] = pr
  364. ctx.HTML(200, tplCompareDiff)
  365. return
  366. }
  367. if !nothingToCompare {
  368. // Setup information for new form.
  369. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  370. if ctx.Written() {
  371. return
  372. }
  373. }
  374. }
  375. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  376. afterCommitID := ctx.Data["AfterCommitID"].(string)
  377. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + "..." + base.ShortSha(afterCommitID)
  378. ctx.Data["IsRepoToolbarCommits"] = true
  379. ctx.Data["IsDiffCompare"] = true
  380. ctx.Data["RequireHighlightJS"] = true
  381. ctx.Data["RequireTribute"] = true
  382. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  383. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  384. renderAttachmentSettings(ctx)
  385. ctx.HTML(200, tplCompare)
  386. }