BlueGit

timfa bluegit

Files

bluegit / internal / store / issues.go

issues.go

feat: lees .bluegit-sjablonen en klikbare takenlijsten
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
79722e46 History
issues.go 21.3 KiB Download Raw
1package store
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "regexp"
8 "sort"
9 "strconv"
10 "strings"
11 "time"
12 "unicode"
13
14 "gitlab.com/Timfa/bluegit/internal/i18n"
15)
16
17// Label is een label binnen één repository.
18type Label struct {
19 ID int64
20 RepoID int64
21 Name string
22 Color string
23}
24
25// Milestone is een mijlpaal binnen één repository.
26type Milestone struct {
27 ID int64
28 RepoID int64
29 Title string
30 DueOn string
31 State string
32}
33
34// Issue is één issue, genummerd per repository.
35type Issue struct {
36 ID int64
37 RepoID int64
38 Number int64
39 Title string
40 Description string
41 AuthorID int64
42 Author string
43 Status string
44 Confidential bool
45 MilestoneID int64
46 Milestone string
47 DueOn string
48 CreatedAt time.Time
49 UpdatedAt time.Time
50 ClosedAt time.Time
51 Labels []Label
52 AssigneeIDs []int64
53 Assignees []string
54}
55
56// IssueNote is een reactie op een issue.
57type IssueNote struct {
58 ID int64
59 RepoID int64
60 IssueID int64
61 AuthorID int64
62 Author string
63 Body string
64 CreatedAt time.Time
65}
66
67// IssueFilter beperkt de lijst. State is open, closed of all.
68type IssueFilter struct {
69 State string
70 Query string
71 Label string
72 Assignee string
73 ViewerID int64
74 Triage bool
75}
76
77// NewIssue is de invoer voor een nieuw issue.
78type NewIssue struct {
79 Title string
80 Description string
81 Confidential bool
82 MilestoneID int64
83 DueOn string
84 LabelIDs []int64
85 AssigneeIDs []int64
86}
87
88var labelColor = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
89
90// ValidDue eist leeg of YYYY-MM-DD.
91func ValidDue(s string) error {
92 s = strings.TrimSpace(s)
93 if s == "" {
94 return nil
95 }
96 if _, err := time.Parse("2006-01-02", s); err != nil {
97 return i18n.E("err.issueDue")
98 }
99 return nil
100}
101
102// ValidLabelName eist letters, cijfers, spaties, streepjes of underscores.
103func ValidLabelName(s string) error {
104 s = strings.TrimSpace(s)
105 if s == "" || len([]rune(s)) > 50 {
106 return i18n.E("err.labelName")
107 }
108 for _, r := range s {
109 if r == ' ' || r == '-' || r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) {
110 continue
111 }
112 return i18n.E("err.labelName")
113 }
114 return nil
115}
116
117// NormalizeColor vult de standaardkleur aan of keurt een hexkleur goed.
118func NormalizeColor(s string) (string, error) {
119 s = strings.TrimSpace(s)
120 if s == "" {
121 return "#428fdc", nil
122 }
123 if !labelColor.MatchString(s) {
124 return "", i18n.E("err.labelColor")
125 }
126 return strings.ToLower(s), nil
127}
128
129// ValidMilestoneTitle eist een korte titel.
130func ValidMilestoneTitle(s string) error {
131 s = strings.TrimSpace(s)
132 if s == "" || len([]rune(s)) > 80 {
133 return i18n.E("err.milestoneName")
134 }
135 for _, r := range s {
136 if r == ' ' || r == '-' || r == '_' || r == '.' || unicode.IsLetter(r) || unicode.IsDigit(r) {
137 continue
138 }
139 return i18n.E("err.milestoneName")
140 }
141 return nil
142}
143
144func limitIssueText(s string) error {
145 if len([]rune(s)) > 20000 {
146 return i18n.E("err.issueBody")
147 }
148 return nil
149}
150
151// UpsertLabel maakt een label of werkt de kleur bij.
152func (s *Store) UpsertLabel(ctx context.Context, repoID int64, name, color string) (Label, error) {
153 name = strings.TrimSpace(name)
154 if err := ValidLabelName(name); err != nil {
155 return Label{}, err
156 }
157 color, err := NormalizeColor(color)
158 if err != nil {
159 return Label{}, err
160 }
161 if _, err := s.db.ExecContext(ctx, `INSERT INTO labels (repo_id, name, color) VALUES (?, ?, ?)
162 ON CONFLICT(repo_id, name) DO UPDATE SET color = excluded.color`, repoID, name, color); err != nil {
163 return Label{}, err
164 }
165 return s.LabelByName(ctx, repoID, name)
166}
167
168// LabelByName leest één label.
169func (s *Store) LabelByName(ctx context.Context, repoID int64, name string) (Label, error) {
170 var l Label
171 err := s.db.QueryRowContext(ctx, `SELECT id, repo_id, name, color FROM labels WHERE repo_id = ? AND name = ?`, repoID, strings.TrimSpace(name)).
172 Scan(&l.ID, &l.RepoID, &l.Name, &l.Color)
173 if errors.Is(err, sql.ErrNoRows) {
174 return Label{}, errNotFound
175 }
176 return l, err
177}
178
179// ListLabels geeft de labels op naam.
180func (s *Store) ListLabels(ctx context.Context, repoID int64) ([]Label, error) {
181 rows, err := s.db.QueryContext(ctx, `SELECT id, repo_id, name, color FROM labels WHERE repo_id = ? ORDER BY name`, repoID)
182 if err != nil {
183 return nil, err
184 }
185 defer rows.Close()
186 out := []Label{}
187 for rows.Next() {
188 var l Label
189 if err := rows.Scan(&l.ID, &l.RepoID, &l.Name, &l.Color); err != nil {
190 return nil, err
191 }
192 out = append(out, l)
193 }
194 return out, rows.Err()
195}
196
197// UpsertMilestone maakt een mijlpaal of werkt de datum bij.
198func (s *Store) UpsertMilestone(ctx context.Context, repoID int64, title, due string) (Milestone, error) {
199 title = strings.TrimSpace(title)
200 if err := ValidMilestoneTitle(title); err != nil {
201 return Milestone{}, err
202 }
203 due = strings.TrimSpace(due)
204 if err := ValidDue(due); err != nil {
205 return Milestone{}, err
206 }
207 if _, err := s.db.ExecContext(ctx, `INSERT INTO milestones (repo_id, title, due_on, state) VALUES (?, ?, ?, 'open')
208 ON CONFLICT(repo_id, title) DO UPDATE SET due_on = excluded.due_on`, repoID, title, due); err != nil {
209 return Milestone{}, err
210 }
211 return s.MilestoneByTitle(ctx, repoID, title)
212}
213
214// MilestoneByTitle leest één mijlpaal.
215func (s *Store) MilestoneByTitle(ctx context.Context, repoID int64, title string) (Milestone, error) {
216 var m Milestone
217 err := s.db.QueryRowContext(ctx, `SELECT id, repo_id, title, due_on, state FROM milestones WHERE repo_id = ? AND title = ?`, repoID, strings.TrimSpace(title)).
218 Scan(&m.ID, &m.RepoID, &m.Title, &m.DueOn, &m.State)
219 if errors.Is(err, sql.ErrNoRows) {
220 return Milestone{}, errNotFound
221 }
222 return m, err
223}
224
225// ListMilestones geeft de mijlpalen op titel.
226func (s *Store) ListMilestones(ctx context.Context, repoID int64) ([]Milestone, error) {
227 rows, err := s.db.QueryContext(ctx, `SELECT id, repo_id, title, due_on, state FROM milestones WHERE repo_id = ? ORDER BY title`, repoID)
228 if err != nil {
229 return nil, err
230 }
231 defer rows.Close()
232 out := []Milestone{}
233 for rows.Next() {
234 var m Milestone
235 if err := rows.Scan(&m.ID, &m.RepoID, &m.Title, &m.DueOn, &m.State); err != nil {
236 return nil, err
237 }
238 out = append(out, m)
239 }
240 return out, rows.Err()
241}
242
243const issueSelect = `SELECT i.id, i.repo_id, i.number, i.title, i.description, i.author_id, u.username,
244i.status, i.confidential, i.milestone_id, COALESCE(m.title, ''), i.due_on, i.created_at, i.updated_at, i.closed_at,
245COALESCE((SELECT group_concat(l.id || char(31) || l.name || char(31) || l.color, char(30)) FROM issue_labels il JOIN labels l ON l.id = il.label_id WHERE il.issue_id = i.id), ''),
246COALESCE((SELECT group_concat(au.id || char(31) || au.username, char(30)) FROM issue_assignees ia JOIN users au ON au.id = ia.user_id WHERE ia.issue_id = i.id), '')
247FROM issues i
248JOIN users u ON u.id = i.author_id
249LEFT JOIN milestones m ON m.id = i.milestone_id AND m.id <> 0`
250
251// CreateIssue nummert per repository en zet labels en toewijzingen.
252func (s *Store) CreateIssue(ctx context.Context, repoID, authorID int64, in NewIssue) (Issue, error) {
253 title := trim(strings.TrimSpace(in.Title), 200)
254 if title == "" {
255 return Issue{}, i18n.E("err.issueTitle")
256 }
257 if err := limitIssueText(in.Description); err != nil {
258 return Issue{}, err
259 }
260 in.DueOn = strings.TrimSpace(in.DueOn)
261 if err := ValidDue(in.DueOn); err != nil {
262 return Issue{}, err
263 }
264 tx, err := s.db.BeginTx(ctx, nil)
265 if err != nil {
266 return Issue{}, err
267 }
268 defer func() { _ = tx.Rollback() }()
269 if err := ensureIssueRefs(ctx, tx, repoID, in.MilestoneID, in.LabelIDs, in.AssigneeIDs); err != nil {
270 return Issue{}, err
271 }
272 var n int64
273 if err := tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(number), 0) FROM issues WHERE repo_id = ?`, repoID).Scan(&n); err != nil {
274 return Issue{}, err
275 }
276 ts := now()
277 conf := 0
278 if in.Confidential {
279 conf = 1
280 }
281 res, err := tx.ExecContext(ctx, `INSERT INTO issues (repo_id, number, title, description, author_id, status, confidential, milestone_id, due_on, created_at, updated_at)
282 VALUES (?, ?, ?, ?, ?, 'open', ?, ?, ?, ?, ?)`, repoID, n+1, title, in.Description, authorID, conf, in.MilestoneID, in.DueOn, ts, ts)
283 if err != nil {
284 return Issue{}, err
285 }
286 id, _ := res.LastInsertId()
287 if err := replaceIssueLinks(ctx, tx, id, in.LabelIDs, in.AssigneeIDs); err != nil {
288 return Issue{}, err
289 }
290 if err := tx.Commit(); err != nil {
291 return Issue{}, err
292 }
293 return s.IssueByNumber(ctx, repoID, n+1)
294}
295
296// IssueByNumber leest #nummer.
297func (s *Store) IssueByNumber(ctx context.Context, repoID, number int64) (Issue, error) {
298 row := s.db.QueryRowContext(ctx, issueSelect+` WHERE i.repo_id = ? AND i.number = ?`, repoID, number)
299 return scanIssue(row)
300}
301
302// ListIssues geeft issues, nieuwste nummer eerst.
303// Zonder triage blijven andermans vertrouwelijke issues weg.
304func (s *Store) ListIssues(ctx context.Context, repoID int64, f IssueFilter) ([]Issue, error) {
305 q := issueSelect + ` WHERE i.repo_id = ?`
306 args := []any{repoID}
307 if !f.Triage {
308 q += ` AND (i.confidential = 0 OR i.author_id = ?)`
309 args = append(args, f.ViewerID)
310 }
311 switch f.State {
312 case "closed":
313 q += ` AND i.status = 'closed'`
314 case "all":
315 default:
316 q += ` AND i.status = 'open'`
317 }
318 if strings.TrimSpace(f.Query) != "" {
319 q += ` AND (instr(lower(i.title), lower(?)) > 0 OR instr(lower(i.description), lower(?)) > 0)`
320 args = append(args, strings.TrimSpace(f.Query), strings.TrimSpace(f.Query))
321 }
322 if strings.TrimSpace(f.Label) != "" {
323 q += ` AND EXISTS (SELECT 1 FROM issue_labels il JOIN labels l ON l.id = il.label_id WHERE il.issue_id = i.id AND l.name = ?)`
324 args = append(args, strings.TrimSpace(f.Label))
325 }
326 if strings.TrimSpace(f.Assignee) != "" {
327 q += ` AND EXISTS (SELECT 1 FROM issue_assignees ia JOIN users au ON au.id = ia.user_id WHERE ia.issue_id = i.id AND au.username = ?)`
328 args = append(args, strings.ToLower(strings.TrimSpace(f.Assignee)))
329 }
330 q += ` ORDER BY i.number DESC`
331 rows, err := s.db.QueryContext(ctx, q, args...)
332 if err != nil {
333 return nil, err
334 }
335 defer rows.Close()
336 out := []Issue{}
337 for rows.Next() {
338 iss, err := scanIssue(rows)
339 if err != nil {
340 return nil, err
341 }
342 out = append(out, iss)
343 }
344 return out, rows.Err()
345}
346
347// UpdateIssueText wijzigt titel en beschrijving.
348func (s *Store) UpdateIssueText(ctx context.Context, id int64, title, description string) error {
349 title = trim(strings.TrimSpace(title), 200)
350 if title == "" {
351 return i18n.E("err.issueTitle")
352 }
353 if err := limitIssueText(description); err != nil {
354 return err
355 }
356 _, err := s.db.ExecContext(ctx, `UPDATE issues SET title = ?, description = ?, updated_at = ? WHERE id = ?`, title, description, now(), id)
357 return err
358}
359
360// SetIssueMeta wijzigt vertrouwelijkheid, mijlpaal en vervaldatum.
361func (s *Store) SetIssueMeta(ctx context.Context, repoID, id, milestoneID int64, confidential bool, due string) error {
362 due = strings.TrimSpace(due)
363 if err := ValidDue(due); err != nil {
364 return err
365 }
366 if err := ensureIssueRefs(ctx, s.db, repoID, milestoneID, nil, nil); err != nil {
367 return err
368 }
369 flag := 0
370 if confidential {
371 flag = 1
372 }
373 _, err := s.db.ExecContext(ctx, `UPDATE issues SET confidential = ?, milestone_id = ?, due_on = ?, updated_at = ? WHERE id = ?`, flag, milestoneID, due, now(), id)
374 return err
375}
376
377// SetIssueLabels vervangt de labels van een issue.
378func (s *Store) SetIssueLabels(ctx context.Context, repoID, id int64, labelIDs []int64) error {
379 tx, err := s.db.BeginTx(ctx, nil)
380 if err != nil {
381 return err
382 }
383 defer func() { _ = tx.Rollback() }()
384 if err := ensureIssueRefs(ctx, tx, repoID, 0, labelIDs, nil); err != nil {
385 return err
386 }
387 if _, err := tx.ExecContext(ctx, `DELETE FROM issue_labels WHERE issue_id = ?`, id); err != nil {
388 return err
389 }
390 for _, lid := range labelIDs {
391 if _, err := tx.ExecContext(ctx, `INSERT INTO issue_labels (issue_id, label_id) VALUES (?, ?)`, id, lid); err != nil {
392 return err
393 }
394 }
395 if _, err := tx.ExecContext(ctx, `UPDATE issues SET updated_at = ? WHERE id = ?`, now(), id); err != nil {
396 return err
397 }
398 return tx.Commit()
399}
400
401// SetIssueAssignees vervangt de toewijzingen.
402func (s *Store) SetIssueAssignees(ctx context.Context, repoID, id int64, userIDs []int64) error {
403 tx, err := s.db.BeginTx(ctx, nil)
404 if err != nil {
405 return err
406 }
407 defer func() { _ = tx.Rollback() }()
408 if err := ensureIssueRefs(ctx, tx, repoID, 0, nil, userIDs); err != nil {
409 return err
410 }
411 if _, err := tx.ExecContext(ctx, `DELETE FROM issue_assignees WHERE issue_id = ?`, id); err != nil {
412 return err
413 }
414 for _, uid := range userIDs {
415 if _, err := tx.ExecContext(ctx, `INSERT INTO issue_assignees (issue_id, user_id) VALUES (?, ?)`, id, uid); err != nil {
416 return err
417 }
418 }
419 if _, err := tx.ExecContext(ctx, `UPDATE issues SET updated_at = ? WHERE id = ?`, now(), id); err != nil {
420 return err
421 }
422 return tx.Commit()
423}
424
425// SetIssueState zet open of closed. changed is onwaar als de status al zo was.
426func (s *Store) SetIssueState(ctx context.Context, id int64, status string) (bool, error) {
427 if status != "open" && status != "closed" {
428 return false, i18n.E("err.issueState")
429 }
430 closed := ""
431 if status == "closed" {
432 closed = now()
433 }
434 res, err := s.db.ExecContext(ctx, `UPDATE issues SET status = ?, closed_at = ?, updated_at = ? WHERE id = ? AND status <> ?`, status, closed, now(), id, status)
435 if err != nil {
436 return false, err
437 }
438 n, _ := res.RowsAffected()
439 return n > 0, nil
440}
441
442// DeleteIssue verwijdert een issue met reacties, labels en koppelingen.
443func (s *Store) DeleteIssue(ctx context.Context, repoID, id int64) error {
444 tx, err := s.db.BeginTx(ctx, nil)
445 if err != nil {
446 return err
447 }
448 defer func() { _ = tx.Rollback() }()
449 for _, q := range []string{
450 `DELETE FROM issue_notes WHERE issue_id = ?`,
451 `DELETE FROM issue_labels WHERE issue_id = ?`,
452 `DELETE FROM issue_assignees WHERE issue_id = ?`,
453 } {
454 if _, err := tx.ExecContext(ctx, q, id); err != nil {
455 return err
456 }
457 }
458 if _, err := tx.ExecContext(ctx, `DELETE FROM issue_links WHERE a = ? OR b = ?`, id, id); err != nil {
459 return err
460 }
461 res, err := tx.ExecContext(ctx, `DELETE FROM issues WHERE id = ? AND repo_id = ?`, id, repoID)
462 if err != nil {
463 return err
464 }
465 n, _ := res.RowsAffected()
466 if n == 0 {
467 return errNotFound
468 }
469 return tx.Commit()
470}
471
472// AddIssueNote bewaart een reactie.
473func (s *Store) AddIssueNote(ctx context.Context, repoID, issueID, authorID int64, body string) (IssueNote, error) {
474 body = strings.TrimSpace(body)
475 if body == "" {
476 return IssueNote{}, i18n.E("err.issueNote")
477 }
478 if err := limitIssueText(body); err != nil {
479 return IssueNote{}, err
480 }
481 ts := now()
482 res, err := s.db.ExecContext(ctx, `INSERT INTO issue_notes (repo_id, issue_id, author_id, body, created_at) VALUES (?, ?, ?, ?, ?)`, repoID, issueID, authorID, body, ts)
483 if err != nil {
484 return IssueNote{}, err
485 }
486 _, _ = s.db.ExecContext(ctx, `UPDATE issues SET updated_at = ? WHERE id = ?`, ts, issueID)
487 id, _ := res.LastInsertId()
488 return s.issueNote(ctx, id)
489}
490
491// ListIssueNotes geeft reacties, oudste eerst.
492func (s *Store) ListIssueNotes(ctx context.Context, issueID int64) ([]IssueNote, error) {
493 rows, err := s.db.QueryContext(ctx, `SELECT n.id, n.repo_id, n.issue_id, n.author_id, u.username, n.body, n.created_at
494 FROM issue_notes n JOIN users u ON u.id = n.author_id WHERE n.issue_id = ? ORDER BY n.id`, issueID)
495 if err != nil {
496 return nil, err
497 }
498 defer rows.Close()
499 out := []IssueNote{}
500 for rows.Next() {
501 n, err := scanIssueNote(rows)
502 if err != nil {
503 return nil, err
504 }
505 out = append(out, n)
506 }
507 return out, rows.Err()
508}
509
510// LinkIssues koppelt twee issues in beide richtingen.
511func (s *Store) LinkIssues(ctx context.Context, repoID, a, b int64) error {
512 if a == 0 || b == 0 || a == b {
513 return nil
514 }
515 _, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO issue_links (repo_id, a, b) VALUES (?, ?, ?), (?, ?, ?)`, repoID, a, b, repoID, b, a)
516 return err
517}
518
519// RelatedIssues geeft de gekoppelde issues.
520func (s *Store) RelatedIssues(ctx context.Context, repoID, issueID int64) ([]Issue, error) {
521 rows, err := s.db.QueryContext(ctx, `SELECT b FROM issue_links WHERE repo_id = ? AND a = ? ORDER BY b`, repoID, issueID)
522 if err != nil {
523 return nil, err
524 }
525 defer rows.Close()
526 var ids []int64
527 for rows.Next() {
528 var id int64
529 if err := rows.Scan(&id); err != nil {
530 return nil, err
531 }
532 ids = append(ids, id)
533 }
534 if err := rows.Err(); err != nil {
535 return nil, err
536 }
537 out := []Issue{}
538 for _, id := range ids {
539 iss, err := s.issueByID(ctx, repoID, id)
540 if err != nil {
541 continue
542 }
543 out = append(out, iss)
544 }
545 return out, nil
546}
547
548func (s *Store) issueByID(ctx context.Context, repoID, id int64) (Issue, error) {
549 row := s.db.QueryRowContext(ctx, issueSelect+` WHERE i.repo_id = ? AND i.id = ?`, repoID, id)
550 return scanIssue(row)
551}
552
553// IssueByID leest een issue op de interne id.
554func (s *Store) IssueByID(ctx context.Context, repoID, id int64) (Issue, error) {
555 return s.issueByID(ctx, repoID, id)
556}
557
558// IssueNoteByID leest een reactie in deze repository.
559func (s *Store) IssueNoteByID(ctx context.Context, repoID, id int64) (IssueNote, error) {
560 n, err := s.issueNote(ctx, id)
561 if err != nil {
562 return IssueNote{}, err
563 }
564 if n.RepoID != repoID {
565 return IssueNote{}, errNotFound
566 }
567 return n, nil
568}
569
570// UpdateIssueNoteBody vervangt de tekst van een issue-reactie.
571func (s *Store) UpdateIssueNoteBody(ctx context.Context, repoID, id int64, body string) error {
572 if strings.TrimSpace(body) == "" {
573 return i18n.E("err.issueNote")
574 }
575 if err := limitIssueText(body); err != nil {
576 return err
577 }
578 res, err := s.db.ExecContext(ctx, `UPDATE issue_notes SET body = ? WHERE id = ? AND repo_id = ?`, body, id, repoID)
579 if err != nil {
580 return err
581 }
582 n, _ := res.RowsAffected()
583 if n == 0 {
584 return errNotFound
585 }
586 return nil
587}
588
589func (s *Store) issueNote(ctx context.Context, id int64) (IssueNote, error) {
590 row := s.db.QueryRowContext(ctx, `SELECT n.id, n.repo_id, n.issue_id, n.author_id, u.username, n.body, n.created_at
591 FROM issue_notes n JOIN users u ON u.id = n.author_id WHERE n.id = ?`, id)
592 return scanIssueNote(row)
593}
594
595type rowScanner interface {
596 Scan(dest ...any) error
597}
598
599func scanIssue(sc rowScanner) (Issue, error) {
600 var iss Issue
601 var created, updated, closed, packedLabels, packedUsers string
602 var conf int
603 if err := sc.Scan(&iss.ID, &iss.RepoID, &iss.Number, &iss.Title, &iss.Description, &iss.AuthorID, &iss.Author,
604 &iss.Status, &conf, &iss.MilestoneID, &iss.Milestone, &iss.DueOn, &created, &updated, &closed, &packedLabels, &packedUsers); err != nil {
605 if errors.Is(err, sql.ErrNoRows) {
606 return Issue{}, errNotFound
607 }
608 return Issue{}, err
609 }
610 iss.Confidential = conf == 1
611 iss.CreatedAt = parseTime(created)
612 iss.UpdatedAt = parseTime(updated)
613 iss.ClosedAt = parseTime(closed)
614 iss.Labels = parsePackedLabels(packedLabels)
615 iss.AssigneeIDs, iss.Assignees = parsePackedUsers(packedUsers)
616 return iss, nil
617}
618
619func scanIssueNote(sc rowScanner) (IssueNote, error) {
620 var n IssueNote
621 var created string
622 if err := sc.Scan(&n.ID, &n.RepoID, &n.IssueID, &n.AuthorID, &n.Author, &n.Body, &created); err != nil {
623 if errors.Is(err, sql.ErrNoRows) {
624 return IssueNote{}, errNotFound
625 }
626 return IssueNote{}, err
627 }
628 n.CreatedAt = parseTime(created)
629 return n, nil
630}
631
632func parsePackedLabels(raw string) []Label {
633 out := []Label{}
634 if raw == "" {
635 return out
636 }
637 for _, part := range strings.Split(raw, "\x1e") {
638 bits := strings.Split(part, "\x1f")
639 if len(bits) != 3 {
640 continue
641 }
642 id, _ := strconv.ParseInt(bits[0], 10, 64)
643 out = append(out, Label{ID: id, Name: bits[1], Color: bits[2]})
644 }
645 sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
646 return out
647}
648
649func parsePackedUsers(raw string) ([]int64, []string) {
650 type pair struct {
651 id int64
652 name string
653 }
654 var pairs []pair
655 if raw != "" {
656 for _, part := range strings.Split(raw, "\x1e") {
657 bits := strings.SplitN(part, "\x1f", 2)
658 if len(bits) != 2 {
659 continue
660 }
661 id, _ := strconv.ParseInt(bits[0], 10, 64)
662 pairs = append(pairs, pair{id, bits[1]})
663 }
664 }
665 sort.Slice(pairs, func(i, j int) bool { return pairs[i].name < pairs[j].name })
666 ids := []int64{}
667 names := []string{}
668 for _, p := range pairs {
669 ids = append(ids, p.id)
670 names = append(names, p.name)
671 }
672 return ids, names
673}
674
675type execQuerier interface {
676 ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
677 QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
678}
679
680func ensureIssueRefs(ctx context.Context, q execQuerier, repoID, milestoneID int64, labelIDs, userIDs []int64) error {
681 if milestoneID != 0 {
682 var n int
683 if err := q.QueryRowContext(ctx, `SELECT COUNT(*) FROM milestones WHERE id = ? AND repo_id = ?`, milestoneID, repoID).Scan(&n); err != nil {
684 return err
685 }
686 if n != 1 {
687 return i18n.E("err.milestone")
688 }
689 }
690 for _, id := range labelIDs {
691 var n int
692 if err := q.QueryRowContext(ctx, `SELECT COUNT(*) FROM labels WHERE id = ? AND repo_id = ?`, id, repoID).Scan(&n); err != nil {
693 return err
694 }
695 if n != 1 {
696 return i18n.E("err.labelMissing", id)
697 }
698 }
699 for _, id := range userIDs {
700 var name string
701 err := q.QueryRowContext(ctx, `SELECT username FROM users WHERE id = ?`, id).Scan(&name)
702 if errors.Is(err, sql.ErrNoRows) {
703 return i18n.E("err.assignee", id)
704 }
705 if err != nil {
706 return err
707 }
708 }
709 return nil
710}
711
712func replaceIssueLinks(ctx context.Context, tx *sql.Tx, issueID int64, labelIDs, userIDs []int64) error {
713 for _, id := range labelIDs {
714 if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO issue_labels (issue_id, label_id) VALUES (?, ?)`, issueID, id); err != nil {
715 return err
716 }
717 }
718 for _, id := range userIDs {
719 if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO issue_assignees (issue_id, user_id) VALUES (?, ?)`, issueID, id); err != nil {
720 return err
721 }
722 }
723 return nil
724}