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

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