本站源代码
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

398 líneas
12KB

  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. // CompareDiff show different from one commit to another commit
  303. func CompareDiff(ctx *context.Context) {
  304. headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  305. if ctx.Written() {
  306. return
  307. }
  308. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch)
  309. if ctx.Written() {
  310. return
  311. }
  312. if ctx.Data["PageIsComparePull"] == true {
  313. headBranches, err := headGitRepo.GetBranches()
  314. if err != nil {
  315. ctx.ServerError("GetBranches", err)
  316. return
  317. }
  318. ctx.Data["HeadBranches"] = headBranches
  319. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  320. if err != nil {
  321. if !models.IsErrPullRequestNotExist(err) {
  322. ctx.ServerError("GetUnmergedPullRequest", err)
  323. return
  324. }
  325. } else {
  326. ctx.Data["HasPullRequest"] = true
  327. ctx.Data["PullRequest"] = pr
  328. ctx.HTML(200, tplCompareDiff)
  329. return
  330. }
  331. if !nothingToCompare {
  332. // Setup information for new form.
  333. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  334. if ctx.Written() {
  335. return
  336. }
  337. }
  338. }
  339. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  340. afterCommitID := ctx.Data["AfterCommitID"].(string)
  341. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + "..." + base.ShortSha(afterCommitID)
  342. ctx.Data["IsRepoToolbarCommits"] = true
  343. ctx.Data["IsDiffCompare"] = true
  344. ctx.Data["RequireHighlightJS"] = true
  345. ctx.Data["RequireTribute"] = true
  346. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  347. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  348. renderAttachmentSettings(ctx)
  349. ctx.HTML(200, tplCompare)
  350. }
上海开阖软件有限公司 沪ICP备12045867号-1