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.go 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "path"
  9. "regexp"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/structs"
  17. api "code.gitea.io/gitea/modules/structs"
  18. "code.gitea.io/gitea/modules/timeutil"
  19. "code.gitea.io/gitea/modules/util"
  20. "github.com/unknwon/com"
  21. "xorm.io/builder"
  22. "xorm.io/xorm"
  23. )
  24. // Issue represents an issue or pull request of repository.
  25. type Issue struct {
  26. ID int64 `xorm:"pk autoincr"`
  27. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  28. Repo *Repository `xorm:"-"`
  29. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  30. PosterID int64 `xorm:"INDEX"`
  31. Poster *User `xorm:"-"`
  32. OriginalAuthor string
  33. OriginalAuthorID int64 `xorm:"index"`
  34. Title string `xorm:"name"`
  35. Content string `xorm:"TEXT"`
  36. RenderedContent string `xorm:"-"`
  37. Labels []*Label `xorm:"-"`
  38. MilestoneID int64 `xorm:"INDEX"`
  39. Milestone *Milestone `xorm:"-"`
  40. Priority int
  41. AssigneeID int64 `xorm:"-"`
  42. Assignee *User `xorm:"-"`
  43. IsClosed bool `xorm:"INDEX"`
  44. IsRead bool `xorm:"-"`
  45. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  46. PullRequest *PullRequest `xorm:"-"`
  47. NumComments int
  48. Ref string
  49. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  50. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  51. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  52. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  53. Attachments []*Attachment `xorm:"-"`
  54. Comments []*Comment `xorm:"-"`
  55. Reactions ReactionList `xorm:"-"`
  56. TotalTrackedTime int64 `xorm:"-"`
  57. Assignees []*User `xorm:"-"`
  58. // IsLocked limits commenting abilities to users on an issue
  59. // with write access
  60. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  61. }
  62. var (
  63. issueTasksPat *regexp.Regexp
  64. issueTasksDonePat *regexp.Regexp
  65. )
  66. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sxX]\]\s.)|(\n\s*[-*]\s\[[\sxX]\]\s.)`
  67. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[xX]\]\s.)|(\n\s*[-*]\s\[[xX]\]\s.)`
  68. const issueMaxDupIndexAttempts = 3
  69. func init() {
  70. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  71. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  72. }
  73. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  74. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  75. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  76. if err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. // IsOverdue checks if the issue is overdue
  82. func (issue *Issue) IsOverdue() bool {
  83. return timeutil.TimeStampNow() >= issue.DeadlineUnix
  84. }
  85. // LoadRepo loads issue's repository
  86. func (issue *Issue) LoadRepo() error {
  87. return issue.loadRepo(x)
  88. }
  89. func (issue *Issue) loadRepo(e Engine) (err error) {
  90. if issue.Repo == nil {
  91. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  92. if err != nil {
  93. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  94. }
  95. }
  96. return nil
  97. }
  98. // IsTimetrackerEnabled returns true if the repo enables timetracking
  99. func (issue *Issue) IsTimetrackerEnabled() bool {
  100. return issue.isTimetrackerEnabled(x)
  101. }
  102. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  103. if err := issue.loadRepo(e); err != nil {
  104. log.Error(fmt.Sprintf("loadRepo: %v", err))
  105. return false
  106. }
  107. return issue.Repo.IsTimetrackerEnabled()
  108. }
  109. // GetPullRequest returns the issue pull request
  110. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  111. if !issue.IsPull {
  112. return nil, fmt.Errorf("Issue is not a pull request")
  113. }
  114. pr, err = getPullRequestByIssueID(x, issue.ID)
  115. if err != nil {
  116. return nil, err
  117. }
  118. pr.Issue = issue
  119. return
  120. }
  121. func (issue *Issue) loadLabels(e Engine) (err error) {
  122. if issue.Labels == nil {
  123. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  124. if err != nil {
  125. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  126. }
  127. }
  128. return nil
  129. }
  130. // LoadPoster loads poster
  131. func (issue *Issue) LoadPoster() error {
  132. return issue.loadPoster(x)
  133. }
  134. func (issue *Issue) loadPoster(e Engine) (err error) {
  135. if issue.Poster == nil {
  136. issue.Poster, err = getUserByID(e, issue.PosterID)
  137. if err != nil {
  138. issue.PosterID = -1
  139. issue.Poster = NewGhostUser()
  140. if !IsErrUserNotExist(err) {
  141. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  142. }
  143. err = nil
  144. return
  145. }
  146. }
  147. return
  148. }
  149. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  150. if issue.IsPull && issue.PullRequest == nil {
  151. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  152. if err != nil {
  153. if IsErrPullRequestNotExist(err) {
  154. return err
  155. }
  156. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  157. }
  158. issue.PullRequest.Issue = issue
  159. }
  160. return nil
  161. }
  162. // LoadPullRequest loads pull request info
  163. func (issue *Issue) LoadPullRequest() error {
  164. return issue.loadPullRequest(x)
  165. }
  166. func (issue *Issue) loadComments(e Engine) (err error) {
  167. return issue.loadCommentsByType(e, CommentTypeUnknown)
  168. }
  169. // LoadDiscussComments loads discuss comments
  170. func (issue *Issue) LoadDiscussComments() error {
  171. return issue.loadCommentsByType(x, CommentTypeComment)
  172. }
  173. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  174. if issue.Comments != nil {
  175. return nil
  176. }
  177. issue.Comments, err = findComments(e, FindCommentsOptions{
  178. IssueID: issue.ID,
  179. Type: tp,
  180. })
  181. return err
  182. }
  183. func (issue *Issue) loadReactions(e Engine) (err error) {
  184. if issue.Reactions != nil {
  185. return nil
  186. }
  187. reactions, err := findReactions(e, FindReactionsOptions{
  188. IssueID: issue.ID,
  189. })
  190. if err != nil {
  191. return err
  192. }
  193. // Load reaction user data
  194. if _, err := ReactionList(reactions).loadUsers(e); err != nil {
  195. return err
  196. }
  197. // Cache comments to map
  198. comments := make(map[int64]*Comment)
  199. for _, comment := range issue.Comments {
  200. comments[comment.ID] = comment
  201. }
  202. // Add reactions either to issue or comment
  203. for _, react := range reactions {
  204. if react.CommentID == 0 {
  205. issue.Reactions = append(issue.Reactions, react)
  206. } else if comment, ok := comments[react.CommentID]; ok {
  207. comment.Reactions = append(comment.Reactions, react)
  208. }
  209. }
  210. return nil
  211. }
  212. func (issue *Issue) loadMilestone(e Engine) (err error) {
  213. if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 {
  214. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  215. if err != nil && !IsErrMilestoneNotExist(err) {
  216. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  217. }
  218. }
  219. return nil
  220. }
  221. func (issue *Issue) loadAttributes(e Engine) (err error) {
  222. if err = issue.loadRepo(e); err != nil {
  223. return
  224. }
  225. if err = issue.loadPoster(e); err != nil {
  226. return
  227. }
  228. if err = issue.loadLabels(e); err != nil {
  229. return
  230. }
  231. if err = issue.loadMilestone(e); err != nil {
  232. return
  233. }
  234. if err = issue.loadAssignees(e); err != nil {
  235. return
  236. }
  237. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  238. // It is possible pull request is not yet created.
  239. return err
  240. }
  241. if issue.Attachments == nil {
  242. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  243. if err != nil {
  244. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  245. }
  246. }
  247. if err = issue.loadComments(e); err != nil {
  248. return err
  249. }
  250. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  251. return err
  252. }
  253. if issue.isTimetrackerEnabled(e) {
  254. if err = issue.loadTotalTimes(e); err != nil {
  255. return err
  256. }
  257. }
  258. return issue.loadReactions(e)
  259. }
  260. // LoadAttributes loads the attribute of this issue.
  261. func (issue *Issue) LoadAttributes() error {
  262. return issue.loadAttributes(x)
  263. }
  264. // LoadMilestone load milestone of this issue.
  265. func (issue *Issue) LoadMilestone() error {
  266. return issue.loadMilestone(x)
  267. }
  268. // GetIsRead load the `IsRead` field of the issue
  269. func (issue *Issue) GetIsRead(userID int64) error {
  270. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  271. if has, err := x.Get(issueUser); err != nil {
  272. return err
  273. } else if !has {
  274. issue.IsRead = false
  275. return nil
  276. }
  277. issue.IsRead = issueUser.IsRead
  278. return nil
  279. }
  280. // APIURL returns the absolute APIURL to this issue.
  281. func (issue *Issue) APIURL() string {
  282. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  283. }
  284. // HTMLURL returns the absolute URL to this issue.
  285. func (issue *Issue) HTMLURL() string {
  286. var path string
  287. if issue.IsPull {
  288. path = "pulls"
  289. } else {
  290. path = "issues"
  291. }
  292. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  293. }
  294. // DiffURL returns the absolute URL to this diff
  295. func (issue *Issue) DiffURL() string {
  296. if issue.IsPull {
  297. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  298. }
  299. return ""
  300. }
  301. // PatchURL returns the absolute URL to this patch
  302. func (issue *Issue) PatchURL() string {
  303. if issue.IsPull {
  304. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  305. }
  306. return ""
  307. }
  308. // State returns string representation of issue status.
  309. func (issue *Issue) State() api.StateType {
  310. if issue.IsClosed {
  311. return api.StateClosed
  312. }
  313. return api.StateOpen
  314. }
  315. // APIFormat assumes some fields assigned with values:
  316. // Required - Poster, Labels,
  317. // Optional - Milestone, Assignee, PullRequest
  318. func (issue *Issue) APIFormat() *api.Issue {
  319. return issue.apiFormat(x)
  320. }
  321. func (issue *Issue) apiFormat(e Engine) *api.Issue {
  322. issue.loadLabels(e)
  323. apiLabels := make([]*api.Label, len(issue.Labels))
  324. for i := range issue.Labels {
  325. apiLabels[i] = issue.Labels[i].APIFormat()
  326. }
  327. issue.loadPoster(e)
  328. issue.loadRepo(e)
  329. apiIssue := &api.Issue{
  330. ID: issue.ID,
  331. URL: issue.APIURL(),
  332. HTMLURL: issue.HTMLURL(),
  333. Index: issue.Index,
  334. Poster: issue.Poster.APIFormat(),
  335. Title: issue.Title,
  336. Body: issue.Content,
  337. Labels: apiLabels,
  338. State: issue.State(),
  339. Comments: issue.NumComments,
  340. Created: issue.CreatedUnix.AsTime(),
  341. Updated: issue.UpdatedUnix.AsTime(),
  342. }
  343. apiIssue.Repo = &api.RepositoryMeta{
  344. ID: issue.Repo.ID,
  345. Name: issue.Repo.Name,
  346. FullName: issue.Repo.FullName(),
  347. }
  348. if issue.ClosedUnix != 0 {
  349. apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
  350. }
  351. issue.loadMilestone(e)
  352. if issue.Milestone != nil {
  353. apiIssue.Milestone = issue.Milestone.APIFormat()
  354. }
  355. issue.loadAssignees(e)
  356. if len(issue.Assignees) > 0 {
  357. for _, assignee := range issue.Assignees {
  358. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  359. }
  360. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  361. }
  362. if issue.IsPull {
  363. issue.loadPullRequest(e)
  364. apiIssue.PullRequest = &api.PullRequestMeta{
  365. HasMerged: issue.PullRequest.HasMerged,
  366. }
  367. if issue.PullRequest.HasMerged {
  368. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  369. }
  370. }
  371. if issue.DeadlineUnix != 0 {
  372. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  373. }
  374. return apiIssue
  375. }
  376. // HashTag returns unique hash tag for issue.
  377. func (issue *Issue) HashTag() string {
  378. return "issue-" + com.ToStr(issue.ID)
  379. }
  380. // IsPoster returns true if given user by ID is the poster.
  381. func (issue *Issue) IsPoster(uid int64) bool {
  382. return issue.OriginalAuthorID == 0 && issue.PosterID == uid
  383. }
  384. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  385. return hasIssueLabel(e, issue.ID, labelID)
  386. }
  387. // HasLabel returns true if issue has been labeled by given ID.
  388. func (issue *Issue) HasLabel(labelID int64) bool {
  389. return issue.hasLabel(x, labelID)
  390. }
  391. // ReplyReference returns tokenized address to use for email reply headers
  392. func (issue *Issue) ReplyReference() string {
  393. var path string
  394. if issue.IsPull {
  395. path = "pulls"
  396. } else {
  397. path = "issues"
  398. }
  399. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  400. }
  401. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  402. return newIssueLabel(e, issue, label, doer)
  403. }
  404. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  405. return newIssueLabels(e, issue, labels, doer)
  406. }
  407. func (issue *Issue) getLabels(e Engine) (err error) {
  408. if len(issue.Labels) > 0 {
  409. return nil
  410. }
  411. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  412. if err != nil {
  413. return fmt.Errorf("getLabelsByIssueID: %v", err)
  414. }
  415. return nil
  416. }
  417. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  418. return deleteIssueLabel(e, issue, label, doer)
  419. }
  420. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  421. if err = issue.getLabels(e); err != nil {
  422. return fmt.Errorf("getLabels: %v", err)
  423. }
  424. for i := range issue.Labels {
  425. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  426. return fmt.Errorf("removeLabel: %v", err)
  427. }
  428. }
  429. return nil
  430. }
  431. // ClearLabels removes all issue labels as the given user.
  432. // Triggers appropriate WebHooks, if any.
  433. func (issue *Issue) ClearLabels(doer *User) (err error) {
  434. sess := x.NewSession()
  435. defer sess.Close()
  436. if err = sess.Begin(); err != nil {
  437. return err
  438. }
  439. if err := issue.loadRepo(sess); err != nil {
  440. return err
  441. } else if err = issue.loadPullRequest(sess); err != nil {
  442. return err
  443. }
  444. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  445. if err != nil {
  446. return err
  447. }
  448. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  449. return ErrLabelNotExist{}
  450. }
  451. if err = issue.clearLabels(sess, doer); err != nil {
  452. return err
  453. }
  454. if err = sess.Commit(); err != nil {
  455. return fmt.Errorf("Commit: %v", err)
  456. }
  457. return nil
  458. }
  459. type labelSorter []*Label
  460. func (ts labelSorter) Len() int {
  461. return len([]*Label(ts))
  462. }
  463. func (ts labelSorter) Less(i, j int) bool {
  464. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  465. }
  466. func (ts labelSorter) Swap(i, j int) {
  467. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  468. }
  469. // ReplaceLabels removes all current labels and add new labels to the issue.
  470. // Triggers appropriate WebHooks, if any.
  471. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  472. sess := x.NewSession()
  473. defer sess.Close()
  474. if err = sess.Begin(); err != nil {
  475. return err
  476. }
  477. if err = issue.loadLabels(sess); err != nil {
  478. return err
  479. }
  480. sort.Sort(labelSorter(labels))
  481. sort.Sort(labelSorter(issue.Labels))
  482. var toAdd, toRemove []*Label
  483. addIndex, removeIndex := 0, 0
  484. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  485. addLabel := labels[addIndex]
  486. removeLabel := issue.Labels[removeIndex]
  487. if addLabel.ID == removeLabel.ID {
  488. addIndex++
  489. removeIndex++
  490. } else if addLabel.ID < removeLabel.ID {
  491. toAdd = append(toAdd, addLabel)
  492. addIndex++
  493. } else {
  494. toRemove = append(toRemove, removeLabel)
  495. removeIndex++
  496. }
  497. }
  498. toAdd = append(toAdd, labels[addIndex:]...)
  499. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  500. if len(toAdd) > 0 {
  501. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  502. return fmt.Errorf("addLabels: %v", err)
  503. }
  504. }
  505. for _, l := range toRemove {
  506. if err = issue.removeLabel(sess, doer, l); err != nil {
  507. return fmt.Errorf("removeLabel: %v", err)
  508. }
  509. }
  510. return sess.Commit()
  511. }
  512. // ReadBy sets issue to be read by given user.
  513. func (issue *Issue) ReadBy(userID int64) error {
  514. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  515. return err
  516. }
  517. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  518. }
  519. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  520. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  521. return err
  522. }
  523. return nil
  524. }
  525. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (*Comment, error) {
  526. // Reload the issue
  527. currentIssue, err := getIssueByID(e, issue.ID)
  528. if err != nil {
  529. return nil, err
  530. }
  531. // Nothing should be performed if current status is same as target status
  532. if currentIssue.IsClosed == isClosed {
  533. if !issue.IsPull {
  534. return nil, ErrIssueWasClosed{
  535. ID: issue.ID,
  536. }
  537. }
  538. return nil, ErrPullWasClosed{
  539. ID: issue.ID,
  540. }
  541. }
  542. // Check for open dependencies
  543. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  544. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  545. noDeps, err := issueNoDependenciesLeft(e, issue)
  546. if err != nil {
  547. return nil, err
  548. }
  549. if !noDeps {
  550. return nil, ErrDependenciesLeft{issue.ID}
  551. }
  552. }
  553. issue.IsClosed = isClosed
  554. if isClosed {
  555. issue.ClosedUnix = timeutil.TimeStampNow()
  556. } else {
  557. issue.ClosedUnix = 0
  558. }
  559. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  560. return nil, err
  561. }
  562. // Update issue count of labels
  563. if err = issue.getLabels(e); err != nil {
  564. return nil, err
  565. }
  566. for idx := range issue.Labels {
  567. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  568. return nil, err
  569. }
  570. }
  571. // Update issue count of milestone
  572. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  573. return nil, err
  574. }
  575. if err := issue.updateClosedNum(e); err != nil {
  576. return nil, err
  577. }
  578. // New action comment
  579. cmtType := CommentTypeClose
  580. if !issue.IsClosed {
  581. cmtType = CommentTypeReopen
  582. }
  583. return createComment(e, &CreateCommentOptions{
  584. Type: cmtType,
  585. Doer: doer,
  586. Repo: issue.Repo,
  587. Issue: issue,
  588. })
  589. }
  590. // ChangeStatus changes issue status to open or closed.
  591. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
  592. sess := x.NewSession()
  593. defer sess.Close()
  594. if err := sess.Begin(); err != nil {
  595. return nil, err
  596. }
  597. if err := issue.loadRepo(sess); err != nil {
  598. return nil, err
  599. }
  600. if err := issue.loadPoster(sess); err != nil {
  601. return nil, err
  602. }
  603. comment, err := issue.changeStatus(sess, doer, isClosed)
  604. if err != nil {
  605. return nil, err
  606. }
  607. if err = sess.Commit(); err != nil {
  608. return nil, fmt.Errorf("Commit: %v", err)
  609. }
  610. return comment, nil
  611. }
  612. // ChangeTitle changes the title of this issue, as the given user.
  613. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  614. sess := x.NewSession()
  615. defer sess.Close()
  616. if err = sess.Begin(); err != nil {
  617. return err
  618. }
  619. if err = updateIssueCols(sess, issue, "name"); err != nil {
  620. return fmt.Errorf("updateIssueCols: %v", err)
  621. }
  622. if err = issue.loadRepo(sess); err != nil {
  623. return fmt.Errorf("loadRepo: %v", err)
  624. }
  625. var opts = &CreateCommentOptions{
  626. Type: CommentTypeChangeTitle,
  627. Doer: doer,
  628. Repo: issue.Repo,
  629. Issue: issue,
  630. OldTitle: oldTitle,
  631. NewTitle: issue.Title,
  632. }
  633. if _, err = createComment(sess, opts); err != nil {
  634. return fmt.Errorf("createComment: %v", err)
  635. }
  636. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  637. return err
  638. }
  639. return sess.Commit()
  640. }
  641. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  642. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  643. issue, err := getIssueByID(x, issueID)
  644. if err != nil {
  645. return err
  646. }
  647. sess := x.NewSession()
  648. defer sess.Close()
  649. if err := sess.Begin(); err != nil {
  650. return err
  651. }
  652. var opts = &CreateCommentOptions{
  653. Type: CommentTypeDeleteBranch,
  654. Doer: doer,
  655. Repo: repo,
  656. Issue: issue,
  657. CommitSHA: branchName,
  658. }
  659. if _, err = createComment(sess, opts); err != nil {
  660. return err
  661. }
  662. return sess.Commit()
  663. }
  664. // UpdateAttachments update attachments by UUIDs for the issue
  665. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  666. sess := x.NewSession()
  667. defer sess.Close()
  668. if err = sess.Begin(); err != nil {
  669. return err
  670. }
  671. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  672. if err != nil {
  673. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  674. }
  675. for i := 0; i < len(attachments); i++ {
  676. attachments[i].IssueID = issue.ID
  677. if err := updateAttachment(sess, attachments[i]); err != nil {
  678. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  679. }
  680. }
  681. return sess.Commit()
  682. }
  683. // ChangeContent changes issue content, as the given user.
  684. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  685. issue.Content = content
  686. sess := x.NewSession()
  687. defer sess.Close()
  688. if err = sess.Begin(); err != nil {
  689. return err
  690. }
  691. if err = updateIssueCols(sess, issue, "content"); err != nil {
  692. return fmt.Errorf("UpdateIssueCols: %v", err)
  693. }
  694. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  695. return err
  696. }
  697. return sess.Commit()
  698. }
  699. // GetTasks returns the amount of tasks in the issues content
  700. func (issue *Issue) GetTasks() int {
  701. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  702. }
  703. // GetTasksDone returns the amount of completed tasks in the issues content
  704. func (issue *Issue) GetTasksDone() int {
  705. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  706. }
  707. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  708. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  709. if issue.IsClosed {
  710. return issue.ClosedUnix
  711. }
  712. return issue.CreatedUnix
  713. }
  714. // GetLastEventLabel returns the localization label for the current issue.
  715. func (issue *Issue) GetLastEventLabel() string {
  716. if issue.IsClosed {
  717. if issue.IsPull && issue.PullRequest.HasMerged {
  718. return "repo.pulls.merged_by"
  719. }
  720. return "repo.issues.closed_by"
  721. }
  722. return "repo.issues.opened_by"
  723. }
  724. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  725. func (issue *Issue) GetLastEventLabelFake() string {
  726. if issue.IsClosed {
  727. if issue.IsPull && issue.PullRequest.HasMerged {
  728. return "repo.pulls.merged_by_fake"
  729. }
  730. return "repo.issues.closed_by_fake"
  731. }
  732. return "repo.issues.opened_by_fake"
  733. }
  734. // NewIssueOptions represents the options of a new issue.
  735. type NewIssueOptions struct {
  736. Repo *Repository
  737. Issue *Issue
  738. LabelIDs []int64
  739. Attachments []string // In UUID format.
  740. IsPull bool
  741. }
  742. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  743. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  744. if opts.Issue.MilestoneID > 0 {
  745. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  746. if err != nil && !IsErrMilestoneNotExist(err) {
  747. return fmt.Errorf("getMilestoneByID: %v", err)
  748. }
  749. // Assume milestone is invalid and drop silently.
  750. opts.Issue.MilestoneID = 0
  751. if milestone != nil {
  752. opts.Issue.MilestoneID = milestone.ID
  753. opts.Issue.Milestone = milestone
  754. }
  755. }
  756. // Milestone validation should happen before insert actual object.
  757. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  758. Where("repo_id=?", opts.Issue.RepoID).
  759. Insert(opts.Issue); err != nil {
  760. return ErrNewIssueInsert{err}
  761. }
  762. inserted, err := getIssueByID(e, opts.Issue.ID)
  763. if err != nil {
  764. return err
  765. }
  766. // Patch Index with the value calculated by the database
  767. opts.Issue.Index = inserted.Index
  768. if opts.Issue.MilestoneID > 0 {
  769. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  770. return err
  771. }
  772. var opts = &CreateCommentOptions{
  773. Type: CommentTypeMilestone,
  774. Doer: doer,
  775. Repo: opts.Repo,
  776. Issue: opts.Issue,
  777. OldMilestoneID: 0,
  778. MilestoneID: opts.Issue.MilestoneID,
  779. }
  780. if _, err = createComment(e, opts); err != nil {
  781. return err
  782. }
  783. }
  784. if opts.IsPull {
  785. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  786. } else {
  787. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  788. }
  789. if err != nil {
  790. return err
  791. }
  792. if len(opts.LabelIDs) > 0 {
  793. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  794. // So we have to get all needed labels first.
  795. labels := make([]*Label, 0, len(opts.LabelIDs))
  796. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  797. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  798. }
  799. if err = opts.Issue.loadPoster(e); err != nil {
  800. return err
  801. }
  802. for _, label := range labels {
  803. // Silently drop invalid labels.
  804. if label.RepoID != opts.Repo.ID {
  805. continue
  806. }
  807. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  808. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  809. }
  810. }
  811. }
  812. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  813. return err
  814. }
  815. if len(opts.Attachments) > 0 {
  816. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  817. if err != nil {
  818. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  819. }
  820. for i := 0; i < len(attachments); i++ {
  821. attachments[i].IssueID = opts.Issue.ID
  822. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  823. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  824. }
  825. }
  826. }
  827. if err = opts.Issue.loadAttributes(e); err != nil {
  828. return err
  829. }
  830. return opts.Issue.addCrossReferences(e, doer, false)
  831. }
  832. // NewIssue creates new issue with labels for repository.
  833. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  834. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  835. i := 0
  836. for {
  837. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  838. return nil
  839. }
  840. if !IsErrNewIssueInsert(err) {
  841. return err
  842. }
  843. if i++; i == issueMaxDupIndexAttempts {
  844. break
  845. }
  846. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  847. }
  848. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  849. }
  850. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  851. sess := x.NewSession()
  852. defer sess.Close()
  853. if err = sess.Begin(); err != nil {
  854. return err
  855. }
  856. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  857. Repo: repo,
  858. Issue: issue,
  859. LabelIDs: labelIDs,
  860. Attachments: uuids,
  861. }); err != nil {
  862. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  863. return err
  864. }
  865. return fmt.Errorf("newIssue: %v", err)
  866. }
  867. if err = sess.Commit(); err != nil {
  868. return fmt.Errorf("Commit: %v", err)
  869. }
  870. return nil
  871. }
  872. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  873. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  874. issue := &Issue{
  875. RepoID: repoID,
  876. Index: index,
  877. }
  878. has, err := x.Get(issue)
  879. if err != nil {
  880. return nil, err
  881. } else if !has {
  882. return nil, ErrIssueNotExist{0, repoID, index}
  883. }
  884. return issue, nil
  885. }
  886. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  887. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  888. issue, err := GetIssueByIndex(repoID, index)
  889. if err != nil {
  890. return nil, err
  891. }
  892. return issue, issue.LoadAttributes()
  893. }
  894. func getIssueByID(e Engine, id int64) (*Issue, error) {
  895. issue := new(Issue)
  896. has, err := e.ID(id).Get(issue)
  897. if err != nil {
  898. return nil, err
  899. } else if !has {
  900. return nil, ErrIssueNotExist{id, 0, 0}
  901. }
  902. return issue, nil
  903. }
  904. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  905. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  906. issue, err := getIssueByID(x, id)
  907. if err != nil {
  908. return nil, err
  909. }
  910. return issue, issue.loadAttributes(x)
  911. }
  912. // GetIssueByID returns an issue by given ID.
  913. func GetIssueByID(id int64) (*Issue, error) {
  914. return getIssueByID(x, id)
  915. }
  916. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  917. issues := make([]*Issue, 0, 10)
  918. return issues, e.In("id", issueIDs).Find(&issues)
  919. }
  920. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  921. var ids = make([]int64, 0, 10)
  922. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  923. return ids, err
  924. }
  925. // GetIssueIDsByRepoID returns all issue ids by repo id
  926. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  927. return getIssueIDsByRepoID(x, repoID)
  928. }
  929. // GetIssuesByIDs return issues with the given IDs.
  930. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  931. return getIssuesByIDs(x, issueIDs)
  932. }
  933. // IssuesOptions represents options of an issue.
  934. type IssuesOptions struct {
  935. RepoIDs []int64 // include all repos if empty
  936. AssigneeID int64
  937. PosterID int64
  938. MentionedID int64
  939. MilestoneID int64
  940. Page int
  941. PageSize int
  942. IsClosed util.OptionalBool
  943. IsPull util.OptionalBool
  944. LabelIDs []int64
  945. SortType string
  946. IssueIDs []int64
  947. // prioritize issues from this repo
  948. PriorityRepoID int64
  949. }
  950. // sortIssuesSession sort an issues-related session based on the provided
  951. // sortType string
  952. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  953. switch sortType {
  954. case "oldest":
  955. sess.Asc("issue.created_unix")
  956. case "recentupdate":
  957. sess.Desc("issue.updated_unix")
  958. case "leastupdate":
  959. sess.Asc("issue.updated_unix")
  960. case "mostcomment":
  961. sess.Desc("issue.num_comments")
  962. case "leastcomment":
  963. sess.Asc("issue.num_comments")
  964. case "priority":
  965. sess.Desc("issue.priority")
  966. case "nearduedate":
  967. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  968. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  969. case "farduedate":
  970. sess.Desc("issue.deadline_unix")
  971. case "priorityrepo":
  972. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  973. default:
  974. sess.Desc("issue.created_unix")
  975. }
  976. }
  977. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  978. if opts.Page >= 0 && opts.PageSize > 0 {
  979. var start int
  980. if opts.Page == 0 {
  981. start = 0
  982. } else {
  983. start = (opts.Page - 1) * opts.PageSize
  984. }
  985. sess.Limit(opts.PageSize, start)
  986. }
  987. if len(opts.IssueIDs) > 0 {
  988. sess.In("issue.id", opts.IssueIDs)
  989. }
  990. if len(opts.RepoIDs) > 0 {
  991. // In case repository IDs are provided but actually no repository has issue.
  992. sess.In("issue.repo_id", opts.RepoIDs)
  993. }
  994. switch opts.IsClosed {
  995. case util.OptionalBoolTrue:
  996. sess.And("issue.is_closed=?", true)
  997. case util.OptionalBoolFalse:
  998. sess.And("issue.is_closed=?", false)
  999. }
  1000. if opts.AssigneeID > 0 {
  1001. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1002. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1003. }
  1004. if opts.PosterID > 0 {
  1005. sess.And("issue.poster_id=?", opts.PosterID)
  1006. }
  1007. if opts.MentionedID > 0 {
  1008. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1009. And("issue_user.is_mentioned = ?", true).
  1010. And("issue_user.uid = ?", opts.MentionedID)
  1011. }
  1012. if opts.MilestoneID > 0 {
  1013. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1014. }
  1015. switch opts.IsPull {
  1016. case util.OptionalBoolTrue:
  1017. sess.And("issue.is_pull=?", true)
  1018. case util.OptionalBoolFalse:
  1019. sess.And("issue.is_pull=?", false)
  1020. }
  1021. if opts.LabelIDs != nil {
  1022. for i, labelID := range opts.LabelIDs {
  1023. if labelID > 0 {
  1024. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1025. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1026. } else {
  1027. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1028. }
  1029. }
  1030. }
  1031. }
  1032. // CountIssuesByRepo map from repoID to number of issues matching the options
  1033. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1034. sess := x.NewSession()
  1035. defer sess.Close()
  1036. opts.setupSession(sess)
  1037. countsSlice := make([]*struct {
  1038. RepoID int64
  1039. Count int64
  1040. }, 0, 10)
  1041. if err := sess.GroupBy("issue.repo_id").
  1042. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1043. Table("issue").
  1044. Find(&countsSlice); err != nil {
  1045. return nil, err
  1046. }
  1047. countMap := make(map[int64]int64, len(countsSlice))
  1048. for _, c := range countsSlice {
  1049. countMap[c.RepoID] = c.Count
  1050. }
  1051. return countMap, nil
  1052. }
  1053. // Issues returns a list of issues by given conditions.
  1054. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1055. sess := x.NewSession()
  1056. defer sess.Close()
  1057. opts.setupSession(sess)
  1058. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1059. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1060. if err := sess.Find(&issues); err != nil {
  1061. return nil, fmt.Errorf("Find: %v", err)
  1062. }
  1063. sess.Close()
  1064. if err := IssueList(issues).LoadAttributes(); err != nil {
  1065. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1066. }
  1067. return issues, nil
  1068. }
  1069. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1070. // but skips joining with `user` for performance reasons.
  1071. // User permissions must be verified elsewhere if required.
  1072. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1073. userIDs := make([]int64, 0, 5)
  1074. return userIDs, x.Table("comment").
  1075. Cols("poster_id").
  1076. Where("issue_id = ?", issueID).
  1077. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1078. Distinct("poster_id").
  1079. Find(&userIDs)
  1080. }
  1081. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1082. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1083. return getParticipantsByIssueID(x, issueID)
  1084. }
  1085. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1086. userIDs := make([]int64, 0, 5)
  1087. if err := e.Table("comment").Cols("poster_id").
  1088. Where("`comment`.issue_id = ?", issueID).
  1089. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1090. And("`user`.is_active = ?", true).
  1091. And("`user`.prohibit_login = ?", false).
  1092. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1093. Distinct("poster_id").
  1094. Find(&userIDs); err != nil {
  1095. return nil, fmt.Errorf("get poster IDs: %v", err)
  1096. }
  1097. if len(userIDs) == 0 {
  1098. return nil, nil
  1099. }
  1100. users := make([]*User, 0, len(userIDs))
  1101. return users, e.In("id", userIDs).Find(&users)
  1102. }
  1103. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1104. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1105. if len(mentions) == 0 {
  1106. return nil
  1107. }
  1108. ids := make([]int64, len(mentions))
  1109. for i, u := range mentions {
  1110. ids[i] = u.ID
  1111. }
  1112. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1113. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1114. }
  1115. return nil
  1116. }
  1117. // IssueStats represents issue statistic information.
  1118. type IssueStats struct {
  1119. OpenCount, ClosedCount int64
  1120. YourRepositoriesCount int64
  1121. AssignCount int64
  1122. CreateCount int64
  1123. MentionCount int64
  1124. }
  1125. // Filter modes.
  1126. const (
  1127. FilterModeAll = iota
  1128. FilterModeAssign
  1129. FilterModeCreate
  1130. FilterModeMention
  1131. )
  1132. func parseCountResult(results []map[string][]byte) int64 {
  1133. if len(results) == 0 {
  1134. return 0
  1135. }
  1136. for _, result := range results[0] {
  1137. return com.StrTo(string(result)).MustInt64()
  1138. }
  1139. return 0
  1140. }
  1141. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1142. type IssueStatsOptions struct {
  1143. RepoID int64
  1144. Labels string
  1145. MilestoneID int64
  1146. AssigneeID int64
  1147. MentionedID int64
  1148. PosterID int64
  1149. IsPull util.OptionalBool
  1150. IssueIDs []int64
  1151. }
  1152. // GetIssueStats returns issue statistic information by given conditions.
  1153. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1154. if len(opts.IssueIDs) <= maxQueryParameters {
  1155. return getIssueStatsChunk(opts, opts.IssueIDs)
  1156. }
  1157. // If too long a list of IDs is provided, we get the statistics in
  1158. // smaller chunks and get accumulates. Note: this could potentially
  1159. // get us invalid results. The alternative is to insert the list of
  1160. // ids in a temporary table and join from them.
  1161. accum := &IssueStats{}
  1162. for i := 0; i < len(opts.IssueIDs); {
  1163. chunk := i + maxQueryParameters
  1164. if chunk > len(opts.IssueIDs) {
  1165. chunk = len(opts.IssueIDs)
  1166. }
  1167. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1168. if err != nil {
  1169. return nil, err
  1170. }
  1171. accum.OpenCount += stats.OpenCount
  1172. accum.ClosedCount += stats.ClosedCount
  1173. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1174. accum.AssignCount += stats.AssignCount
  1175. accum.CreateCount += stats.CreateCount
  1176. accum.OpenCount += stats.MentionCount
  1177. i = chunk
  1178. }
  1179. return accum, nil
  1180. }
  1181. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1182. stats := &IssueStats{}
  1183. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1184. sess := x.
  1185. Where("issue.repo_id = ?", opts.RepoID)
  1186. if len(opts.IssueIDs) > 0 {
  1187. sess.In("issue.id", opts.IssueIDs)
  1188. }
  1189. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1190. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1191. if err != nil {
  1192. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1193. } else {
  1194. for i, labelID := range labelIDs {
  1195. if labelID > 0 {
  1196. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1197. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1198. } else {
  1199. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1200. }
  1201. }
  1202. }
  1203. }
  1204. if opts.MilestoneID > 0 {
  1205. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1206. }
  1207. if opts.AssigneeID > 0 {
  1208. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1209. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1210. }
  1211. if opts.PosterID > 0 {
  1212. sess.And("issue.poster_id = ?", opts.PosterID)
  1213. }
  1214. if opts.MentionedID > 0 {
  1215. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1216. And("issue_user.uid = ?", opts.MentionedID).
  1217. And("issue_user.is_mentioned = ?", true)
  1218. }
  1219. switch opts.IsPull {
  1220. case util.OptionalBoolTrue:
  1221. sess.And("issue.is_pull=?", true)
  1222. case util.OptionalBoolFalse:
  1223. sess.And("issue.is_pull=?", false)
  1224. }
  1225. return sess
  1226. }
  1227. var err error
  1228. stats.OpenCount, err = countSession(opts).
  1229. And("issue.is_closed = ?", false).
  1230. Count(new(Issue))
  1231. if err != nil {
  1232. return stats, err
  1233. }
  1234. stats.ClosedCount, err = countSession(opts).
  1235. And("issue.is_closed = ?", true).
  1236. Count(new(Issue))
  1237. return stats, err
  1238. }
  1239. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1240. type UserIssueStatsOptions struct {
  1241. UserID int64
  1242. RepoIDs []int64
  1243. UserRepoIDs []int64
  1244. FilterMode int
  1245. IsPull bool
  1246. IsClosed bool
  1247. }
  1248. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1249. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1250. var err error
  1251. stats := &IssueStats{}
  1252. cond := builder.NewCond()
  1253. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1254. if len(opts.RepoIDs) > 0 {
  1255. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1256. }
  1257. switch opts.FilterMode {
  1258. case FilterModeAll:
  1259. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1260. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1261. Count(new(Issue))
  1262. if err != nil {
  1263. return nil, err
  1264. }
  1265. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1266. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1267. Count(new(Issue))
  1268. if err != nil {
  1269. return nil, err
  1270. }
  1271. case FilterModeAssign:
  1272. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1273. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1274. And("issue_assignees.assignee_id = ?", opts.UserID).
  1275. Count(new(Issue))
  1276. if err != nil {
  1277. return nil, err
  1278. }
  1279. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1280. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1281. And("issue_assignees.assignee_id = ?", opts.UserID).
  1282. Count(new(Issue))
  1283. if err != nil {
  1284. return nil, err
  1285. }
  1286. case FilterModeCreate:
  1287. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1288. And("issue.poster_id = ?", opts.UserID).
  1289. Count(new(Issue))
  1290. if err != nil {
  1291. return nil, err
  1292. }
  1293. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1294. And("issue.poster_id = ?", opts.UserID).
  1295. Count(new(Issue))
  1296. if err != nil {
  1297. return nil, err
  1298. }
  1299. case FilterModeMention:
  1300. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1301. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1302. And("issue_user.uid = ?", opts.UserID).
  1303. Count(new(Issue))
  1304. if err != nil {
  1305. return nil, err
  1306. }
  1307. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1308. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1309. And("issue_user.uid = ?", opts.UserID).
  1310. Count(new(Issue))
  1311. if err != nil {
  1312. return nil, err
  1313. }
  1314. }
  1315. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1316. stats.AssignCount, err = x.Where(cond).
  1317. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1318. And("issue_assignees.assignee_id = ?", opts.UserID).
  1319. Count(new(Issue))
  1320. if err != nil {
  1321. return nil, err
  1322. }
  1323. stats.CreateCount, err = x.Where(cond).
  1324. And("poster_id = ?", opts.UserID).
  1325. Count(new(Issue))
  1326. if err != nil {
  1327. return nil, err
  1328. }
  1329. stats.MentionCount, err = x.Where(cond).
  1330. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1331. And("issue_user.uid = ?", opts.UserID).
  1332. Count(new(Issue))
  1333. if err != nil {
  1334. return nil, err
  1335. }
  1336. stats.YourRepositoriesCount, err = x.Where(cond).
  1337. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1338. Count(new(Issue))
  1339. if err != nil {
  1340. return nil, err
  1341. }
  1342. return stats, nil
  1343. }
  1344. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1345. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1346. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1347. sess := x.
  1348. Where("is_closed = ?", isClosed).
  1349. And("is_pull = ?", isPull).
  1350. And("repo_id = ?", repoID)
  1351. return sess
  1352. }
  1353. openCountSession := countSession(false, isPull, repoID)
  1354. closedCountSession := countSession(true, isPull, repoID)
  1355. switch filterMode {
  1356. case FilterModeAssign:
  1357. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1358. And("issue_assignees.assignee_id = ?", uid)
  1359. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1360. And("issue_assignees.assignee_id = ?", uid)
  1361. case FilterModeCreate:
  1362. openCountSession.And("poster_id = ?", uid)
  1363. closedCountSession.And("poster_id = ?", uid)
  1364. }
  1365. openResult, _ := openCountSession.Count(new(Issue))
  1366. closedResult, _ := closedCountSession.Count(new(Issue))
  1367. return openResult, closedResult
  1368. }
  1369. // SearchIssueIDsByKeyword search issues on database
  1370. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1371. var repoCond = builder.In("repo_id", repoIDs)
  1372. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1373. var cond = builder.And(
  1374. repoCond,
  1375. builder.Or(
  1376. builder.Like{"name", kw},
  1377. builder.Like{"content", kw},
  1378. builder.In("id", builder.Select("issue_id").
  1379. From("comment").
  1380. Where(builder.And(
  1381. builder.Eq{"type": CommentTypeComment},
  1382. builder.In("issue_id", subQuery),
  1383. builder.Like{"content", kw},
  1384. )),
  1385. ),
  1386. ),
  1387. )
  1388. var ids = make([]int64, 0, limit)
  1389. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1390. if err != nil {
  1391. return 0, nil, err
  1392. }
  1393. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1394. if err != nil {
  1395. return 0, nil, err
  1396. }
  1397. return total, ids, nil
  1398. }
  1399. // UpdateIssueByAPI updates all allowed fields of given issue.
  1400. func UpdateIssueByAPI(issue *Issue) error {
  1401. sess := x.NewSession()
  1402. defer sess.Close()
  1403. if err := sess.Begin(); err != nil {
  1404. return err
  1405. }
  1406. if _, err := sess.ID(issue.ID).Cols(
  1407. "name", "is_closed", "content", "milestone_id", "priority",
  1408. "deadline_unix", "updated_unix", "closed_unix", "is_locked").
  1409. Update(issue); err != nil {
  1410. return err
  1411. }
  1412. if err := issue.loadPoster(sess); err != nil {
  1413. return err
  1414. }
  1415. if err := issue.addCrossReferences(sess, issue.Poster, true); err != nil {
  1416. return err
  1417. }
  1418. return sess.Commit()
  1419. }
  1420. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1421. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1422. // if the deadline hasn't changed do nothing
  1423. if issue.DeadlineUnix == deadlineUnix {
  1424. return nil
  1425. }
  1426. sess := x.NewSession()
  1427. defer sess.Close()
  1428. if err := sess.Begin(); err != nil {
  1429. return err
  1430. }
  1431. // Update the deadline
  1432. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1433. return err
  1434. }
  1435. // Make the comment
  1436. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1437. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1438. }
  1439. return sess.Commit()
  1440. }
  1441. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1442. type DependencyInfo struct {
  1443. Issue `xorm:"extends"`
  1444. Repository `xorm:"extends"`
  1445. }
  1446. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1447. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1448. return issueDeps, e.
  1449. Table("issue").
  1450. Join("INNER", "repository", "repository.id = issue.repo_id").
  1451. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1452. Where("issue_id = ?", issue.ID).
  1453. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1454. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1455. Find(&issueDeps)
  1456. }
  1457. // Get Blocking Dependencies, aka all issues this issue blocks.
  1458. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1459. return issueDeps, e.
  1460. Table("issue").
  1461. Join("INNER", "repository", "repository.id = issue.repo_id").
  1462. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1463. Where("dependency_id = ?", issue.ID).
  1464. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1465. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1466. Find(&issueDeps)
  1467. }
  1468. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1469. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1470. return issue.getBlockedByDependencies(x)
  1471. }
  1472. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1473. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1474. return issue.getBlockingDependencies(x)
  1475. }
  1476. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1477. if issue.IsPull {
  1478. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1479. issue.RepoID,
  1480. true,
  1481. true,
  1482. issue.RepoID,
  1483. )
  1484. } else {
  1485. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1486. issue.RepoID,
  1487. false,
  1488. true,
  1489. issue.RepoID,
  1490. )
  1491. }
  1492. return
  1493. }
  1494. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1495. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1496. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1497. if len(mentions) == 0 {
  1498. return
  1499. }
  1500. if err = issue.loadRepo(ctx.e); err != nil {
  1501. return
  1502. }
  1503. resolved := make(map[string]bool, 20)
  1504. names := make([]string, 0, 20)
  1505. resolved[doer.LowerName] = true
  1506. for _, name := range mentions {
  1507. name := strings.ToLower(name)
  1508. if _, ok := resolved[name]; ok {
  1509. continue
  1510. }
  1511. resolved[name] = false
  1512. names = append(names, name)
  1513. }
  1514. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1515. return nil, err
  1516. }
  1517. if issue.Repo.Owner.IsOrganization() {
  1518. // Since there can be users with names that match the name of a team,
  1519. // if the team exists and can read the issue, the team takes precedence.
  1520. teams := make([]*Team, 0, len(names))
  1521. if err := ctx.e.
  1522. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1523. Where("team_repo.repo_id=?", issue.Repo.ID).
  1524. In("team.lower_name", names).
  1525. Find(&teams); err != nil {
  1526. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1527. }
  1528. if len(teams) != 0 {
  1529. checked := make([]int64, 0, len(teams))
  1530. unittype := UnitTypeIssues
  1531. if issue.IsPull {
  1532. unittype = UnitTypePullRequests
  1533. }
  1534. for _, team := range teams {
  1535. if team.Authorize >= AccessModeOwner {
  1536. checked = append(checked, team.ID)
  1537. resolved[team.LowerName] = true
  1538. continue
  1539. }
  1540. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1541. if err != nil {
  1542. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1543. }
  1544. if has {
  1545. checked = append(checked, team.ID)
  1546. resolved[team.LowerName] = true
  1547. }
  1548. }
  1549. if len(checked) != 0 {
  1550. teamusers := make([]*User, 0, 20)
  1551. if err := ctx.e.
  1552. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1553. In("`team_user`.team_id", checked).
  1554. And("`user`.is_active = ?", true).
  1555. And("`user`.prohibit_login = ?", false).
  1556. Find(&teamusers); err != nil {
  1557. return nil, fmt.Errorf("get teams users: %v", err)
  1558. }
  1559. if len(teamusers) > 0 {
  1560. users = make([]*User, 0, len(teamusers))
  1561. for _, user := range teamusers {
  1562. if already, ok := resolved[user.LowerName]; !ok || !already {
  1563. users = append(users, user)
  1564. resolved[user.LowerName] = true
  1565. }
  1566. }
  1567. }
  1568. }
  1569. }
  1570. // Remove names already in the list to avoid querying the database if pending names remain
  1571. names = make([]string, 0, len(resolved))
  1572. for name, already := range resolved {
  1573. if !already {
  1574. names = append(names, name)
  1575. }
  1576. }
  1577. if len(names) == 0 {
  1578. return
  1579. }
  1580. }
  1581. unchecked := make([]*User, 0, len(names))
  1582. if err := ctx.e.
  1583. Where("`user`.is_active = ?", true).
  1584. And("`user`.prohibit_login = ?", false).
  1585. In("`user`.lower_name", names).
  1586. Find(&unchecked); err != nil {
  1587. return nil, fmt.Errorf("find mentioned users: %v", err)
  1588. }
  1589. for _, user := range unchecked {
  1590. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1591. continue
  1592. }
  1593. // Normal users must have read access to the referencing issue
  1594. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1595. if err != nil {
  1596. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1597. }
  1598. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1599. continue
  1600. }
  1601. users = append(users, user)
  1602. }
  1603. return
  1604. }
  1605. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1606. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1607. _, err := x.Table("issue").
  1608. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1609. And("original_author_id = ?", originalAuthorID).
  1610. Update(map[string]interface{}{
  1611. "poster_id": posterID,
  1612. "original_author": "",
  1613. "original_author_id": 0,
  1614. })
  1615. return err
  1616. }