gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package issues
  4. import (
  5. "context"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. "code.gitea.io/gitea/models/db"
  10. "code.gitea.io/gitea/models/organization"
  11. repo_model "code.gitea.io/gitea/models/repo"
  12. "code.gitea.io/gitea/models/unit"
  13. user_model "code.gitea.io/gitea/models/user"
  14. "code.gitea.io/gitea/modules/container"
  15. "code.gitea.io/gitea/modules/optional"
  16. "xorm.io/builder"
  17. "xorm.io/xorm"
  18. )
  19. const ScopeSortPrefix = "scope-"
  20. // IssuesOptions represents options of an issue.
  21. type IssuesOptions struct { //nolint:revive // export stutter
  22. Paginator *db.ListOptions
  23. RepoIDs []int64 // overwrites RepoCond if the length is not 0
  24. AllPublic bool // include also all public repositories
  25. RepoCond builder.Cond
  26. AssigneeID string // "(none)" or "(any)" or a user ID
  27. PosterID string // "(none)" or "(any)" or a user ID
  28. MentionedID int64
  29. ReviewRequestedID int64
  30. ReviewedID int64
  31. SubscriberID int64
  32. MilestoneIDs []int64
  33. ProjectID int64
  34. ProjectColumnID int64
  35. IsClosed optional.Option[bool]
  36. IsPull optional.Option[bool]
  37. LabelIDs []int64
  38. IncludedLabelNames []string
  39. ExcludedLabelNames []string
  40. IncludeMilestones []string
  41. SortType string
  42. IssueIDs []int64
  43. UpdatedAfterUnix int64
  44. UpdatedBeforeUnix int64
  45. // prioritize issues from this repo
  46. PriorityRepoID int64
  47. IsArchived optional.Option[bool]
  48. Owner *user_model.User // issues permission scope, it could be an organization or a user
  49. Team *organization.Team // issues permission scope
  50. Doer *user_model.User // issues permission scope
  51. }
  52. // Copy returns a copy of the options.
  53. // Be careful, it's not a deep copy, so `IssuesOptions.RepoIDs = {...}` is OK while `IssuesOptions.RepoIDs[0] = ...` is not.
  54. func (o *IssuesOptions) Copy(edit ...func(options *IssuesOptions)) *IssuesOptions {
  55. if o == nil {
  56. return nil
  57. }
  58. v := *o
  59. for _, e := range edit {
  60. e(&v)
  61. }
  62. return &v
  63. }
  64. // applySorts sort an issues-related session based on the provided
  65. // sortType string
  66. func applySorts(sess *xorm.Session, sortType string, priorityRepoID int64) {
  67. // Since this sortType is dynamically created, it has to be treated specially.
  68. if after, ok := strings.CutPrefix(sortType, ScopeSortPrefix); ok {
  69. scope := after
  70. sess.Join("LEFT", "issue_label", "issue.id = issue_label.issue_id")
  71. // "exclusive_order=0" means "no order is set", so exclude it from the JOIN criteria and then "LEFT JOIN" result is also null
  72. sess.Join("LEFT", "label", "label.id = issue_label.label_id AND label.exclusive_order <> 0 AND label.name LIKE ?", scope+"/%")
  73. // Use COALESCE to make sure we sort NULL last regardless of backend DB (2147483647 == max int)
  74. sess.OrderBy("COALESCE(label.exclusive_order, 2147483647) ASC").Desc("issue.id")
  75. return
  76. }
  77. switch sortType {
  78. case "oldest":
  79. sess.Asc("issue.created_unix").Asc("issue.id")
  80. case "recentupdate":
  81. sess.Desc("issue.updated_unix").Desc("issue.created_unix").Desc("issue.id")
  82. case "recentclose":
  83. sess.Desc("issue.closed_unix").Desc("issue.created_unix").Desc("issue.id")
  84. case "leastupdate":
  85. sess.Asc("issue.updated_unix").Asc("issue.created_unix").Asc("issue.id")
  86. case "mostcomment":
  87. sess.Desc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id")
  88. case "leastcomment":
  89. sess.Asc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id")
  90. case "priority":
  91. sess.Desc("issue.priority").Desc("issue.created_unix").Desc("issue.id")
  92. case "nearduedate":
  93. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  94. sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id").
  95. OrderBy("CASE " +
  96. "WHEN issue.deadline_unix = 0 AND (milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL) THEN 253370764800 " +
  97. "WHEN milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL THEN issue.deadline_unix " +
  98. "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " +
  99. "ELSE issue.deadline_unix END ASC").
  100. Asc("issue.created_unix").
  101. Asc("issue.id")
  102. case "farduedate":
  103. sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id").
  104. OrderBy("CASE " +
  105. "WHEN milestone.deadline_unix IS NULL THEN issue.deadline_unix " +
  106. "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " +
  107. "ELSE issue.deadline_unix END DESC").
  108. Desc("issue.created_unix").
  109. Desc("issue.id")
  110. case "priorityrepo":
  111. sess.OrderBy("CASE "+
  112. "WHEN issue.repo_id = ? THEN 1 "+
  113. "ELSE 2 END ASC", priorityRepoID).
  114. Desc("issue.created_unix").
  115. Desc("issue.id")
  116. case "project-column-sorting":
  117. sess.Asc("project_issue.sorting").Desc("issue.created_unix").Desc("issue.id")
  118. default:
  119. sess.Desc("issue.created_unix").Desc("issue.id")
  120. }
  121. }
  122. func applyLimit(sess *xorm.Session, opts *IssuesOptions) {
  123. if opts.Paginator == nil || opts.Paginator.IsListAll() {
  124. return
  125. }
  126. start := 0
  127. if opts.Paginator.Page > 1 {
  128. start = (opts.Paginator.Page - 1) * opts.Paginator.PageSize
  129. }
  130. sess.Limit(opts.Paginator.PageSize, start)
  131. }
  132. func applyLabelsCondition(sess *xorm.Session, opts *IssuesOptions) {
  133. if len(opts.LabelIDs) > 0 {
  134. if opts.LabelIDs[0] == 0 {
  135. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label)")
  136. } else {
  137. // deduplicate the label IDs for inclusion and exclusion
  138. includedLabelIDs := make(container.Set[int64])
  139. excludedLabelIDs := make(container.Set[int64])
  140. for _, labelID := range opts.LabelIDs {
  141. if labelID > 0 {
  142. includedLabelIDs.Add(labelID)
  143. } else if labelID < 0 { // 0 is not supported here, so just ignore it
  144. excludedLabelIDs.Add(-labelID)
  145. }
  146. }
  147. // ... and use them in a subquery of the form :
  148. // where (select count(*) from issue_label where issue_id=issue.id and label_id in (2, 4, 6)) = 3
  149. // This equality is guaranteed thanks to unique index (issue_id,label_id) on table issue_label.
  150. if len(includedLabelIDs) > 0 {
  151. subQuery := builder.Select("count(*)").From("issue_label").Where(builder.Expr("issue_id = issue.id")).
  152. And(builder.In("label_id", includedLabelIDs.Values()))
  153. sess.Where(builder.Eq{strconv.Itoa(len(includedLabelIDs)): subQuery})
  154. }
  155. // or (select count(*)...) = 0 for excluded labels
  156. if len(excludedLabelIDs) > 0 {
  157. subQuery := builder.Select("count(*)").From("issue_label").Where(builder.Expr("issue_id = issue.id")).
  158. And(builder.In("label_id", excludedLabelIDs.Values()))
  159. sess.Where(builder.Eq{"0": subQuery})
  160. }
  161. }
  162. }
  163. if len(opts.IncludedLabelNames) > 0 {
  164. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  165. }
  166. if len(opts.ExcludedLabelNames) > 0 {
  167. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  168. }
  169. }
  170. func applyMilestoneCondition(sess *xorm.Session, opts *IssuesOptions) {
  171. if len(opts.MilestoneIDs) == 1 && opts.MilestoneIDs[0] == db.NoConditionID {
  172. sess.And("issue.milestone_id = 0")
  173. } else if len(opts.MilestoneIDs) > 0 {
  174. sess.In("issue.milestone_id", opts.MilestoneIDs)
  175. }
  176. if len(opts.IncludeMilestones) > 0 {
  177. sess.In("issue.milestone_id",
  178. builder.Select("id").
  179. From("milestone").
  180. Where(builder.In("name", opts.IncludeMilestones)))
  181. }
  182. }
  183. func applyProjectCondition(sess *xorm.Session, opts *IssuesOptions) {
  184. if opts.ProjectID > 0 { // specific project
  185. sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id").
  186. And("project_issue.project_id=?", opts.ProjectID)
  187. } else if opts.ProjectID == db.NoConditionID { // show those that are in no project
  188. sess.And(builder.NotIn("issue.id", builder.Select("issue_id").From("project_issue").And(builder.Neq{"project_id": 0})))
  189. }
  190. // opts.ProjectID == 0 means all projects,
  191. // do not need to apply any condition
  192. }
  193. func applyProjectColumnCondition(sess *xorm.Session, opts *IssuesOptions) {
  194. // opts.ProjectColumnID == 0 means all project columns,
  195. // do not need to apply any condition
  196. if opts.ProjectColumnID > 0 {
  197. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectColumnID}))
  198. } else if opts.ProjectColumnID == db.NoConditionID {
  199. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0}))
  200. }
  201. }
  202. func applyRepoConditions(sess *xorm.Session, opts *IssuesOptions) {
  203. if len(opts.RepoIDs) == 1 {
  204. opts.RepoCond = builder.Eq{"issue.repo_id": opts.RepoIDs[0]}
  205. } else if len(opts.RepoIDs) > 1 {
  206. opts.RepoCond = builder.In("issue.repo_id", opts.RepoIDs)
  207. }
  208. if opts.AllPublic {
  209. if opts.RepoCond == nil {
  210. opts.RepoCond = builder.NewCond()
  211. }
  212. opts.RepoCond = opts.RepoCond.Or(builder.In("issue.repo_id", builder.Select("id").From("repository").Where(builder.Eq{"is_private": false})))
  213. }
  214. if opts.RepoCond != nil {
  215. sess.And(opts.RepoCond)
  216. }
  217. }
  218. func applyConditions(sess *xorm.Session, opts *IssuesOptions) {
  219. if len(opts.IssueIDs) > 0 {
  220. sess.In("issue.id", opts.IssueIDs)
  221. }
  222. applyRepoConditions(sess, opts)
  223. if opts.IsClosed.Has() {
  224. sess.And("issue.is_closed=?", opts.IsClosed.Value())
  225. }
  226. applyAssigneeCondition(sess, opts.AssigneeID)
  227. applyPosterCondition(sess, opts.PosterID)
  228. if opts.MentionedID > 0 {
  229. applyMentionedCondition(sess, opts.MentionedID)
  230. }
  231. if opts.ReviewRequestedID > 0 {
  232. applyReviewRequestedCondition(sess, opts.ReviewRequestedID)
  233. }
  234. if opts.ReviewedID > 0 {
  235. applyReviewedCondition(sess, opts.ReviewedID)
  236. }
  237. if opts.SubscriberID > 0 {
  238. applySubscribedCondition(sess, opts.SubscriberID)
  239. }
  240. applyMilestoneCondition(sess, opts)
  241. if opts.UpdatedAfterUnix != 0 {
  242. sess.And(builder.Gte{"issue.updated_unix": opts.UpdatedAfterUnix})
  243. }
  244. if opts.UpdatedBeforeUnix != 0 {
  245. sess.And(builder.Lte{"issue.updated_unix": opts.UpdatedBeforeUnix})
  246. }
  247. applyProjectCondition(sess, opts)
  248. applyProjectColumnCondition(sess, opts)
  249. if opts.IsPull.Has() {
  250. sess.And("issue.is_pull=?", opts.IsPull.Value())
  251. }
  252. if opts.IsArchived.Has() {
  253. sess.And(builder.Eq{"repository.is_archived": opts.IsArchived.Value()})
  254. }
  255. applyLabelsCondition(sess, opts)
  256. if opts.Owner != nil {
  257. sess.And(repo_model.UserOwnedRepoCond(opts.Owner.ID))
  258. }
  259. if opts.Doer != nil && !opts.Doer.IsAdmin {
  260. sess.And(issuePullAccessibleRepoCond("issue.repo_id", opts.Doer.ID, opts.Owner, opts.Team, opts.IsPull.Value()))
  261. }
  262. }
  263. // teamUnitsRepoCond returns query condition for those repo id in the special org team with special units access
  264. func teamUnitsRepoCond(id string, userID, orgID, teamID int64, units ...unit.Type) builder.Cond {
  265. return builder.In(id,
  266. builder.Select("repo_id").From("team_repo").Where(
  267. builder.Eq{
  268. "team_id": teamID,
  269. }.And(
  270. builder.Or(
  271. // Check if the user is member of the team.
  272. builder.In(
  273. "team_id", builder.Select("team_id").From("team_user").Where(
  274. builder.Eq{
  275. "uid": userID,
  276. },
  277. ),
  278. ),
  279. // Check if the user is in the owner team of the organisation.
  280. builder.Exists(builder.Select("team_id").From("team_user").
  281. Where(builder.Eq{
  282. "org_id": orgID,
  283. "team_id": builder.Select("id").From("team").Where(
  284. builder.Eq{
  285. "org_id": orgID,
  286. "lower_name": strings.ToLower(organization.OwnerTeamName),
  287. }),
  288. "uid": userID,
  289. }),
  290. ),
  291. )).And(
  292. builder.In(
  293. "team_id", builder.Select("team_id").From("team_unit").Where(
  294. builder.Eq{
  295. "`team_unit`.org_id": orgID,
  296. }.And(
  297. builder.In("`team_unit`.type", units),
  298. ),
  299. ),
  300. ),
  301. ),
  302. ))
  303. }
  304. // issuePullAccessibleRepoCond userID must not be zero, this condition require join repository table
  305. func issuePullAccessibleRepoCond(repoIDstr string, userID int64, owner *user_model.User, team *organization.Team, isPull bool) builder.Cond {
  306. cond := builder.NewCond()
  307. unitType := unit.TypeIssues
  308. if isPull {
  309. unitType = unit.TypePullRequests
  310. }
  311. if owner != nil && owner.IsOrganization() {
  312. if team != nil {
  313. cond = cond.And(teamUnitsRepoCond(repoIDstr, userID, owner.ID, team.ID, unitType)) // special team member repos
  314. } else {
  315. cond = cond.And(
  316. builder.Or(
  317. repo_model.UserOrgUnitRepoCond(repoIDstr, userID, owner.ID, unitType), // team member repos
  318. repo_model.UserOrgPublicUnitRepoCond(userID, owner.ID), // user org public non-member repos, TODO: check repo has issues
  319. ),
  320. )
  321. }
  322. } else {
  323. cond = cond.And(
  324. builder.Or(
  325. repo_model.UserOwnedRepoCond(userID), // owned repos
  326. repo_model.UserAccessRepoCond(repoIDstr, userID), // user can access repo in a unit independent way
  327. repo_model.UserAssignedRepoCond(repoIDstr, userID), // user has been assigned accessible public repos
  328. repo_model.UserMentionedRepoCond(repoIDstr, userID), // user has been mentioned accessible public repos
  329. repo_model.UserCreateIssueRepoCond(repoIDstr, userID, isPull), // user has created issue/pr accessible public repos
  330. ),
  331. )
  332. }
  333. return cond
  334. }
  335. func applyAssigneeCondition(sess *xorm.Session, assigneeID string) {
  336. // old logic: 0 is also treated as "not filtering assignee", because the "assignee" was read as FormInt64
  337. if assigneeID == "(none)" {
  338. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_assignees)")
  339. } else if assigneeID == "(any)" {
  340. sess.Where("issue.id IN (SELECT issue_id FROM issue_assignees)")
  341. } else if assigneeIDInt64, _ := strconv.ParseInt(assigneeID, 10, 64); assigneeIDInt64 > 0 {
  342. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  343. And("issue_assignees.assignee_id = ?", assigneeIDInt64)
  344. }
  345. }
  346. func applyPosterCondition(sess *xorm.Session, posterID string) {
  347. // Actually every issue has a poster.
  348. // The "(none)" is for internal usage only: when doer tries to search non-existing user as poster, use "(none)" to return empty result.
  349. if posterID == "(none)" {
  350. sess.And("issue.poster_id=0")
  351. } else if posterIDInt64, _ := strconv.ParseInt(posterID, 10, 64); posterIDInt64 > 0 {
  352. sess.And("issue.poster_id=?", posterIDInt64)
  353. }
  354. }
  355. func applyMentionedCondition(sess *xorm.Session, mentionedID int64) {
  356. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  357. And("issue_user.is_mentioned = ?", true).
  358. And("issue_user.uid = ?", mentionedID)
  359. }
  360. func applyReviewRequestedCondition(sess *xorm.Session, reviewRequestedID int64) {
  361. existInTeamQuery := builder.Select("team_user.team_id").
  362. From("team_user").
  363. Where(builder.Eq{"team_user.uid": reviewRequestedID})
  364. // if the review is approved or rejected, it should not be shown in the review requested list
  365. maxReview := builder.Select("MAX(r.id)").
  366. From("review as r").
  367. Where(builder.In("r.type", []ReviewType{ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest})).
  368. GroupBy("r.issue_id, r.reviewer_id, r.reviewer_team_id")
  369. subQuery := builder.Select("review.issue_id").
  370. From("review").
  371. Where(builder.And(
  372. builder.Eq{"review.type": ReviewTypeRequest},
  373. builder.Or(
  374. builder.Eq{"review.reviewer_id": reviewRequestedID},
  375. builder.In("review.reviewer_team_id", existInTeamQuery),
  376. ),
  377. builder.In("review.id", maxReview),
  378. ))
  379. sess.Where("issue.poster_id <> ?", reviewRequestedID).
  380. And(builder.In("issue.id", subQuery))
  381. }
  382. func applyReviewedCondition(sess *xorm.Session, reviewedID int64) {
  383. // Query for pull requests where you are a reviewer or commenter, excluding
  384. // any pull requests already returned by the review requested filter.
  385. notPoster := builder.Neq{"issue.poster_id": reviewedID}
  386. reviewed := builder.In("issue.id", builder.
  387. Select("issue_id").
  388. From("review").
  389. Where(builder.And(
  390. builder.Neq{"type": ReviewTypeRequest},
  391. builder.Or(
  392. builder.Eq{"reviewer_id": reviewedID},
  393. builder.In("reviewer_team_id", builder.
  394. Select("team_id").
  395. From("team_user").
  396. Where(builder.Eq{"uid": reviewedID}),
  397. ),
  398. ),
  399. )),
  400. )
  401. commented := builder.In("issue.id", builder.
  402. Select("issue_id").
  403. From("comment").
  404. Where(builder.And(
  405. builder.Eq{"poster_id": reviewedID},
  406. builder.In("type", CommentTypeComment, CommentTypeCode, CommentTypeReview),
  407. )),
  408. )
  409. sess.And(notPoster, builder.Or(reviewed, commented))
  410. }
  411. func applySubscribedCondition(sess *xorm.Session, subscriberID int64) {
  412. sess.And(
  413. builder.
  414. NotIn("issue.id",
  415. builder.Select("issue_id").
  416. From("issue_watch").
  417. Where(builder.Eq{"is_watching": false, "user_id": subscriberID}),
  418. ),
  419. ).And(
  420. builder.Or(
  421. builder.In("issue.id", builder.
  422. Select("issue_id").
  423. From("issue_watch").
  424. Where(builder.Eq{"is_watching": true, "user_id": subscriberID}),
  425. ),
  426. builder.In("issue.id", builder.
  427. Select("issue_id").
  428. From("comment").
  429. Where(builder.Eq{"poster_id": subscriberID}),
  430. ),
  431. builder.Eq{"issue.poster_id": subscriberID},
  432. builder.In("issue.repo_id", builder.
  433. Select("id").
  434. From("watch").
  435. Where(builder.And(builder.Eq{"user_id": subscriberID},
  436. builder.In("mode", repo_model.WatchModeNormal, repo_model.WatchModeAuto))),
  437. ),
  438. ),
  439. )
  440. }
  441. // Issues returns a list of issues by given conditions.
  442. func Issues(ctx context.Context, opts *IssuesOptions) (IssueList, error) {
  443. sess := db.GetEngine(ctx).
  444. Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  445. applyLimit(sess, opts)
  446. applyConditions(sess, opts)
  447. applySorts(sess, opts.SortType, opts.PriorityRepoID)
  448. issues := IssueList{}
  449. if err := sess.Find(&issues); err != nil {
  450. return nil, fmt.Errorf("unable to query Issues: %w", err)
  451. }
  452. if err := issues.LoadAttributes(ctx); err != nil {
  453. return nil, fmt.Errorf("unable to LoadAttributes for Issues: %w", err)
  454. }
  455. return issues, nil
  456. }
  457. // IssueIDs returns a list of issue ids by given conditions.
  458. func IssueIDs(ctx context.Context, opts *IssuesOptions, otherConds ...builder.Cond) ([]int64, int64, error) {
  459. sess := db.GetEngine(ctx).
  460. Join("INNER", "repository", "`issue`.repo_id = `repository`.id")
  461. applyConditions(sess, opts)
  462. for _, cond := range otherConds {
  463. sess.And(cond)
  464. }
  465. applyLimit(sess, opts)
  466. applySorts(sess, opts.SortType, opts.PriorityRepoID)
  467. var res []int64
  468. total, err := sess.Select("`issue`.id").Table(&Issue{}).FindAndCount(&res)
  469. if err != nil {
  470. return nil, 0, err
  471. }
  472. return res, total, nil
  473. }