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.

issue_xref.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package issues
  4. import (
  5. "context"
  6. "fmt"
  7. "code.gitea.io/gitea/models/db"
  8. access_model "code.gitea.io/gitea/models/perm/access"
  9. repo_model "code.gitea.io/gitea/models/repo"
  10. user_model "code.gitea.io/gitea/models/user"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/references"
  13. )
  14. type crossReference struct {
  15. Issue *Issue
  16. Action references.XRefAction
  17. }
  18. // crossReferencesContext is context to pass along findCrossReference functions
  19. type crossReferencesContext struct {
  20. Type CommentType
  21. Doer *user_model.User
  22. OrigIssue *Issue
  23. OrigComment *Comment
  24. RemoveOld bool
  25. }
  26. func findOldCrossReferences(ctx context.Context, issueID, commentID int64) ([]*Comment, error) {
  27. active := make([]*Comment, 0, 10)
  28. return active, db.GetEngine(ctx).Where("`ref_action` IN (?, ?, ?)", references.XRefActionNone, references.XRefActionCloses, references.XRefActionReopens).
  29. And("`ref_issue_id` = ?", issueID).
  30. And("`ref_comment_id` = ?", commentID).
  31. Find(&active)
  32. }
  33. func neuterCrossReferences(ctx context.Context, issueID, commentID int64) error {
  34. active, err := findOldCrossReferences(ctx, issueID, commentID)
  35. if err != nil {
  36. return err
  37. }
  38. ids := make([]int64, len(active))
  39. for i, c := range active {
  40. ids[i] = c.ID
  41. }
  42. return neuterCrossReferencesIDs(ctx, ids)
  43. }
  44. func neuterCrossReferencesIDs(ctx context.Context, ids []int64) error {
  45. _, err := db.GetEngine(ctx).In("id", ids).Cols("`ref_action`").Update(&Comment{RefAction: references.XRefActionNeutered})
  46. return err
  47. }
  48. // AddCrossReferences add cross repositories references.
  49. func (issue *Issue) AddCrossReferences(stdCtx context.Context, doer *user_model.User, removeOld bool) error {
  50. var commentType CommentType
  51. if issue.IsPull {
  52. commentType = CommentTypePullRef
  53. } else {
  54. commentType = CommentTypeIssueRef
  55. }
  56. ctx := &crossReferencesContext{
  57. Type: commentType,
  58. Doer: doer,
  59. OrigIssue: issue,
  60. RemoveOld: removeOld,
  61. }
  62. return issue.createCrossReferences(stdCtx, ctx, issue.Title, issue.Content)
  63. }
  64. func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossReferencesContext, plaincontent, mdcontent string) error {
  65. xreflist, err := ctx.OrigIssue.getCrossReferences(stdCtx, ctx, plaincontent, mdcontent)
  66. if err != nil {
  67. return err
  68. }
  69. if ctx.RemoveOld {
  70. var commentID int64
  71. if ctx.OrigComment != nil {
  72. commentID = ctx.OrigComment.ID
  73. }
  74. active, err := findOldCrossReferences(stdCtx, ctx.OrigIssue.ID, commentID)
  75. if err != nil {
  76. return err
  77. }
  78. ids := make([]int64, 0, len(active))
  79. for _, c := range active {
  80. found := false
  81. for i, x := range xreflist {
  82. if x.Issue.ID == c.IssueID && x.Action == c.RefAction {
  83. found = true
  84. xreflist = append(xreflist[:i], xreflist[i+1:]...)
  85. break
  86. }
  87. }
  88. if !found {
  89. ids = append(ids, c.ID)
  90. }
  91. }
  92. if len(ids) > 0 {
  93. if err = neuterCrossReferencesIDs(stdCtx, ids); err != nil {
  94. return err
  95. }
  96. }
  97. }
  98. for _, xref := range xreflist {
  99. var refCommentID int64
  100. if ctx.OrigComment != nil {
  101. refCommentID = ctx.OrigComment.ID
  102. }
  103. opts := &CreateCommentOptions{
  104. Type: ctx.Type,
  105. Doer: ctx.Doer,
  106. Repo: xref.Issue.Repo,
  107. Issue: xref.Issue,
  108. RefRepoID: ctx.OrigIssue.RepoID,
  109. RefIssueID: ctx.OrigIssue.ID,
  110. RefCommentID: refCommentID,
  111. RefAction: xref.Action,
  112. RefIsPull: ctx.OrigIssue.IsPull,
  113. }
  114. _, err := CreateComment(stdCtx, opts)
  115. if err != nil {
  116. return err
  117. }
  118. }
  119. return nil
  120. }
  121. func (issue *Issue) getCrossReferences(stdCtx context.Context, ctx *crossReferencesContext, plaincontent, mdcontent string) ([]*crossReference, error) {
  122. xreflist := make([]*crossReference, 0, 5)
  123. var (
  124. refRepo *repo_model.Repository
  125. refIssue *Issue
  126. refAction references.XRefAction
  127. err error
  128. )
  129. allrefs := append(references.FindAllIssueReferences(plaincontent), references.FindAllIssueReferencesMarkdown(mdcontent)...)
  130. for _, ref := range allrefs {
  131. if ref.Owner == "" && ref.Name == "" {
  132. // Issues in the same repository
  133. if err := ctx.OrigIssue.LoadRepo(stdCtx); err != nil {
  134. return nil, err
  135. }
  136. refRepo = ctx.OrigIssue.Repo
  137. } else {
  138. // Issues in other repositories
  139. refRepo, err = repo_model.GetRepositoryByOwnerAndName(stdCtx, ref.Owner, ref.Name)
  140. if err != nil {
  141. if repo_model.IsErrRepoNotExist(err) {
  142. continue
  143. }
  144. return nil, err
  145. }
  146. }
  147. if refIssue, refAction, err = ctx.OrigIssue.verifyReferencedIssue(stdCtx, ctx, refRepo, ref); err != nil {
  148. return nil, err
  149. }
  150. if refIssue != nil {
  151. xreflist = ctx.OrigIssue.updateCrossReferenceList(xreflist, &crossReference{
  152. Issue: refIssue,
  153. Action: refAction,
  154. })
  155. }
  156. }
  157. return xreflist, nil
  158. }
  159. func (issue *Issue) updateCrossReferenceList(list []*crossReference, xref *crossReference) []*crossReference {
  160. if xref.Issue.ID == issue.ID {
  161. return list
  162. }
  163. for i, r := range list {
  164. if r.Issue.ID == xref.Issue.ID {
  165. if xref.Action != references.XRefActionNone {
  166. list[i].Action = xref.Action
  167. }
  168. return list
  169. }
  170. }
  171. return append(list, xref)
  172. }
  173. // verifyReferencedIssue will check if the referenced issue exists, and whether the doer has permission to do what
  174. func (issue *Issue) verifyReferencedIssue(stdCtx context.Context, ctx *crossReferencesContext, repo *repo_model.Repository,
  175. ref references.IssueReference,
  176. ) (*Issue, references.XRefAction, error) {
  177. refIssue := &Issue{RepoID: repo.ID, Index: ref.Index}
  178. refAction := ref.Action
  179. e := db.GetEngine(stdCtx)
  180. if has, _ := e.Get(refIssue); !has {
  181. return nil, references.XRefActionNone, nil
  182. }
  183. if err := refIssue.LoadRepo(stdCtx); err != nil {
  184. return nil, references.XRefActionNone, err
  185. }
  186. // Close/reopen actions can only be set from pull requests to issues
  187. if refIssue.IsPull || !issue.IsPull {
  188. refAction = references.XRefActionNone
  189. }
  190. // Check doer permissions; set action to None if the doer can't change the destination
  191. if refIssue.RepoID != ctx.OrigIssue.RepoID || ref.Action != references.XRefActionNone {
  192. perm, err := access_model.GetUserRepoPermission(stdCtx, refIssue.Repo, ctx.Doer)
  193. if err != nil {
  194. return nil, references.XRefActionNone, err
  195. }
  196. if !perm.CanReadIssuesOrPulls(refIssue.IsPull) {
  197. return nil, references.XRefActionNone, nil
  198. }
  199. // Accept close/reopening actions only if the poster is able to close the
  200. // referenced issue manually at this moment. The only exception is
  201. // the poster of a new PR referencing an issue on the same repo: then the merger
  202. // should be responsible for checking whether the reference should resolve.
  203. if ref.Action != references.XRefActionNone &&
  204. ctx.Doer.ID != refIssue.PosterID &&
  205. !perm.CanWriteIssuesOrPulls(refIssue.IsPull) &&
  206. (refIssue.RepoID != ctx.OrigIssue.RepoID || ctx.OrigComment != nil) {
  207. refAction = references.XRefActionNone
  208. }
  209. }
  210. return refIssue, refAction, nil
  211. }
  212. // AddCrossReferences add cross references
  213. func (c *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.User, removeOld bool) error {
  214. if c.Type != CommentTypeCode && c.Type != CommentTypeComment {
  215. return nil
  216. }
  217. if err := c.LoadIssue(stdCtx); err != nil {
  218. return err
  219. }
  220. ctx := &crossReferencesContext{
  221. Type: CommentTypeCommentRef,
  222. Doer: doer,
  223. OrigIssue: c.Issue,
  224. OrigComment: c,
  225. RemoveOld: removeOld,
  226. }
  227. return c.Issue.createCrossReferences(stdCtx, ctx, "", c.Content)
  228. }
  229. func (c *Comment) neuterCrossReferences(ctx context.Context) error {
  230. return neuterCrossReferences(ctx, c.IssueID, c.ID)
  231. }
  232. // LoadRefComment loads comment that created this reference from database
  233. func (c *Comment) LoadRefComment(ctx context.Context) (err error) {
  234. if c.RefComment != nil {
  235. return nil
  236. }
  237. c.RefComment, err = GetCommentByID(ctx, c.RefCommentID)
  238. return err
  239. }
  240. // LoadRefIssue loads comment that created this reference from database
  241. func (c *Comment) LoadRefIssue(ctx context.Context) (err error) {
  242. if c.RefIssue != nil {
  243. return nil
  244. }
  245. c.RefIssue, err = GetIssueByID(ctx, c.RefIssueID)
  246. if err == nil {
  247. err = c.RefIssue.LoadRepo(ctx)
  248. }
  249. return err
  250. }
  251. // CommentTypeIsRef returns true if CommentType is a reference from another issue
  252. func CommentTypeIsRef(t CommentType) bool {
  253. return t == CommentTypeCommentRef || t == CommentTypePullRef || t == CommentTypeIssueRef
  254. }
  255. // RefCommentLink returns the relative URL for the comment that created this reference
  256. func (c *Comment) RefCommentLink(ctx context.Context) string {
  257. // Edge case for when the reference is inside the title or the description of the referring issue
  258. if c.RefCommentID == 0 {
  259. return c.RefIssueLink(ctx)
  260. }
  261. if err := c.LoadRefComment(ctx); err != nil { // Silently dropping errors :unamused:
  262. log.Error("LoadRefComment(%d): %v", c.RefCommentID, err)
  263. return ""
  264. }
  265. return c.RefComment.Link(ctx)
  266. }
  267. // RefIssueLink returns the relative URL of the issue where this reference was created
  268. func (c *Comment) RefIssueLink(ctx context.Context) string {
  269. if err := c.LoadRefIssue(ctx); err != nil { // Silently dropping errors :unamused:
  270. log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
  271. return ""
  272. }
  273. return c.RefIssue.Link()
  274. }
  275. // RefIssueTitle returns the title of the issue where this reference was created
  276. func (c *Comment) RefIssueTitle(ctx context.Context) string {
  277. if err := c.LoadRefIssue(ctx); err != nil { // Silently dropping errors :unamused:
  278. log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
  279. return ""
  280. }
  281. return c.RefIssue.Title
  282. }
  283. // RefIssueIdent returns the user friendly identity (e.g. "#1234") of the issue where this reference was created
  284. func (c *Comment) RefIssueIdent(ctx context.Context) string {
  285. if err := c.LoadRefIssue(ctx); err != nil { // Silently dropping errors :unamused:
  286. log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
  287. return ""
  288. }
  289. // FIXME: check this name for cross-repository references (#7901 if it gets merged)
  290. return fmt.Sprintf("#%d", c.RefIssue.Index)
  291. }
  292. // __________ .__ .__ __________ __
  293. // \______ \__ __| | | |\______ \ ____ ________ __ ____ _______/ |_
  294. // | ___/ | \ | | | | _// __ \/ ____/ | \_/ __ \ / ___/\ __\
  295. // | | | | / |_| |_| | \ ___< <_| | | /\ ___/ \___ \ | |
  296. // |____| |____/|____/____/____|_ /\___ >__ |____/ \___ >____ > |__|
  297. // \/ \/ |__| \/ \/
  298. // ResolveCrossReferences will return the list of references to close/reopen by this PR
  299. func (pr *PullRequest) ResolveCrossReferences(ctx context.Context) ([]*Comment, error) {
  300. unfiltered := make([]*Comment, 0, 5)
  301. if err := db.GetEngine(ctx).
  302. Where("ref_repo_id = ? AND ref_issue_id = ?", pr.Issue.RepoID, pr.Issue.ID).
  303. In("ref_action", []references.XRefAction{references.XRefActionCloses, references.XRefActionReopens}).
  304. OrderBy("id").
  305. Find(&unfiltered); err != nil {
  306. return nil, fmt.Errorf("get reference: %w", err)
  307. }
  308. refs := make([]*Comment, 0, len(unfiltered))
  309. for _, ref := range unfiltered {
  310. found := false
  311. for i, r := range refs {
  312. if r.IssueID == ref.IssueID {
  313. // Keep only the latest
  314. refs[i] = ref
  315. found = true
  316. break
  317. }
  318. }
  319. if !found {
  320. refs = append(refs, ref)
  321. }
  322. }
  323. return refs, nil
  324. }