steid

@jamesgill /

Rust38.9 KBCode·Blame·History·Raw
1//! Labels: making them, changing them, deleting them, and putting them on an issue.
2//!
3//! The same split [`issue`](super::issue) sets, for the same reason: **reading follows
4//! the repository's visibility, and every write is owner-only.** Anyone who can see a
5//! repository can see what its labels mean — the pills are on the issues list already,
6//! and a legend nobody may read is a legend that does not work.
7//!
8//! Authorization is [`issue`](super::issue)'s `readable_repo` and `writable_repo`
9//! rather than a second copy of the same rule. Two copies would be two places for it to
10//! drift, and the answers have to agree: a label is only ever reached through the
11//! repository it belongs to.
12
13use std::{
14 collections::{HashMap, HashSet},
15 time::SystemTime,
16};
17
18use crate::domain::{
19 Actor, DomainError, IssueId, IssueNumber, Label, LabelColour, LabelId, OrgName, PullRequestId,
20 RepoName, Repository,
21 repository::{
22 IssueRepository, LabelRepository, MembershipRepository, OrgRepository,
23 PullRequestRepository, RepoRepository,
24 },
25};
26
27use super::{
28 error::{Error, Result},
29 issue::{existing_issue, readable_repo, writable_repo},
30 pull_request::existing_pull,
31};
32
33/// A label as a page renders it.
34///
35/// The id travels with it because the checkbox list and the edit form both address one,
36/// and `created_at` does not because nothing shows it: a label has no history worth a
37/// timestamp.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct LabelView {
40 pub id: LabelId,
41 pub name: String,
42 pub colour: LabelColour,
43 pub description: Option<String>,
44}
45
46impl From<Label> for LabelView {
47 fn from(label: Label) -> Self {
48 Self {
49 id: label.id,
50 name: label.name,
51 colour: label.colour,
52 description: label.description,
53 }
54 }
55}
56
57/// One row of the management page: the label, and how much use it is getting.
58///
59/// Two numbers rather than one total, because the row links to two lists and the delete
60/// confirmation says what the label comes off: a single number covering both would make
61/// that sentence wrong for whichever kind it was not counting.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct LabelRow {
64 pub label: LabelView,
65 pub issues: u64,
66 pub pulls: u64,
67}
68
69/// A repository's labels.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct LabelPage {
72 /// By name — the order both implementations promise, and the one you can scan.
73 pub labels: Vec<LabelRow>,
74 pub viewer_is_owner: bool,
75}
76
77/// What someone typed into the new-label form. Raw — validation is [`Label::new`]'s job.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct NewLabel {
80 pub name: String,
81 pub colour: LabelColour,
82 pub description: Option<String>,
83}
84
85/// A change to a label. The same shape as [`NewLabel`], kept separate so the two cannot
86/// be passed for one another.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct LabelEdit {
89 pub name: String,
90 pub colour: LabelColour,
91 pub description: Option<String>,
92}
93
94// --- Reads --------------------------------------------------------------------------
95
96/// A repository's labels, with a usage count on each.
97///
98/// `Ok(None)` means the repository is not there *or* the viewer may not see it, and the
99/// caller must render both identically — the rule
100/// [`view_repo`](super::view_repo) sets.
101pub async fn list_labels(
102 actor: &Actor,
103 handle: &OrgName,
104 name: &RepoName,
105 orgs: &impl OrgRepository,
106 memberships: &impl MembershipRepository,
107 repos: &impl RepoRepository,
108 labels: &impl LabelRepository,
109) -> Result<Option<LabelPage>> {
110 let Some((repo, viewer_is_owner)) =
111 readable_repo(actor, handle, name, orgs, memberships, repos).await?
112 else {
113 return Ok(None);
114 };
115
116 // One query for every row's count rather than one per row, and one per kind — the
117 // two tables are two counts.
118 let counts: HashMap<LabelId, u64> = labels.issue_counts(&repo.id).await?.into_iter().collect();
119 let pulls: HashMap<LabelId, u64> = labels.pull_counts(&repo.id).await?.into_iter().collect();
120
121 let rows = labels
122 .list_by_repo(&repo.id)
123 .await?
124 .into_iter()
125 .map(|label| LabelRow {
126 issues: counts.get(&label.id).copied().unwrap_or(0),
127 pulls: pulls.get(&label.id).copied().unwrap_or(0),
128 label: label.into(),
129 })
130 .collect();
131
132 Ok(Some(LabelPage {
133 labels: rows,
134 viewer_is_owner,
135 }))
136}
137
138/// Every label on a repository, keyed by the issue wearing it.
139///
140/// The shape a listing needs: one query for a whole page of rows, rather than one per
141/// row. Pairs arrive grouped and name-ordered, so each vector is already in the order
142/// the pills are drawn in.
143pub(super) async fn labels_by_issue(
144 repo: &Repository,
145 labels: &impl LabelRepository,
146) -> Result<HashMap<IssueId, Vec<LabelView>>> {
147 let mut grouped: HashMap<IssueId, Vec<LabelView>> = HashMap::new();
148
149 for (issue_id, label) in labels.labels_for_repo(&repo.id).await? {
150 grouped.entry(issue_id).or_default().push(label.into());
151 }
152
153 Ok(grouped)
154}
155
156/// Every label on a repository, keyed by the pull request wearing it.
157///
158/// [`labels_by_issue`]'s counterpart, and the same shape for the same reason.
159pub(super) async fn labels_by_pull(
160 repo: &Repository,
161 labels: &impl LabelRepository,
162) -> Result<HashMap<PullRequestId, Vec<LabelView>>> {
163 let mut grouped: HashMap<PullRequestId, Vec<LabelView>> = HashMap::new();
164
165 for (pull_id, label) in labels.labels_for_repo_pulls(&repo.id).await? {
166 grouped.entry(pull_id).or_default().push(label.into());
167 }
168
169 Ok(grouped)
170}
171
172// --- Writes -------------------------------------------------------------------------
173
174/// Creates a label. Owner only.
175///
176/// The duplicate check is here rather than left to the unique index so the refusal is a
177/// message the form can show. The index is still the backstop: two creations racing
178/// would both pass this and one would fail its insert, which is the right way round —
179/// a storage error for a race nobody will ever see, and a sentence for the case that
180/// happens.
181#[allow(clippy::too_many_arguments)]
182pub async fn create_label(
183 actor: &Actor,
184 handle: &OrgName,
185 name: &RepoName,
186 spec: &NewLabel,
187 now: SystemTime,
188 orgs: &impl OrgRepository,
189 memberships: &impl MembershipRepository,
190 repos: &impl RepoRepository,
191 labels: &impl LabelRepository,
192) -> Result<()> {
193 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
194
195 // Validated before the uniqueness check, so `" bug "` is refused as a duplicate of
196 // `bug` rather than saved beside it.
197 let label = Label::new(
198 LabelId::generate(),
199 repo.id.clone(),
200 spec.name.clone(),
201 spec.colour,
202 spec.description.clone(),
203 now,
204 )?;
205
206 if labels.find_by_name(&repo.id, &label.name).await?.is_some() {
207 return Err(taken(&label.name));
208 }
209
210 labels.save(&label).await?;
211
212 Ok(())
213}
214
215/// Renames, recolours or redescribes a label. Owner only.
216///
217/// The id is checked against the repository in the path, not merely looked up: without
218/// that, an id from somebody else's repository would be a way to edit their label from
219/// a form on yours.
220#[allow(clippy::too_many_arguments)]
221pub async fn update_label(
222 actor: &Actor,
223 handle: &OrgName,
224 name: &RepoName,
225 id: &LabelId,
226 edit: &LabelEdit,
227 orgs: &impl OrgRepository,
228 memberships: &impl MembershipRepository,
229 repos: &impl RepoRepository,
230 labels: &impl LabelRepository,
231) -> Result<()> {
232 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
233 let mut label = owned_label(&repo, id, labels).await?;
234
235 // Validated before anything is written, so a rejected name leaves the label exactly
236 // as it was.
237 label.edit(edit.name.clone(), edit.colour, edit.description.clone())?;
238
239 // A label may keep its own name — recolouring is an edit too — so the clash is only
240 // with a *different* label.
241 if let Some(existing) = labels.find_by_name(&repo.id, &label.name).await?
242 && existing.id != label.id
243 {
244 return Err(taken(&label.name));
245 }
246
247 labels.save(&label).await?;
248
249 Ok(())
250}
251
252/// Deletes a label. Owner only.
253///
254/// The issues wearing it keep everything they say; they stop wearing it. That is what
255/// `issue_labels`' `on delete cascade` means, and it is why this needs no confirmation
256/// beyond the one the page asks for: nothing else is lost.
257#[allow(clippy::too_many_arguments)]
258pub async fn delete_label(
259 actor: &Actor,
260 handle: &OrgName,
261 name: &RepoName,
262 id: &LabelId,
263 orgs: &impl OrgRepository,
264 memberships: &impl MembershipRepository,
265 repos: &impl RepoRepository,
266 labels: &impl LabelRepository,
267) -> Result<()> {
268 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
269 let label = owned_label(&repo, id, labels).await?;
270
271 labels.delete(&label.id).await?;
272
273 Ok(())
274}
275
276/// Replaces an issue's labels with exactly this set. Owner only.
277///
278/// **The whole set, not an add and a remove**, because the control that submits it is a
279/// list of checkboxes: what arrives is what is ticked, and applying it as a replacement
280/// is the only reading that matches what the person saw. It also makes a double
281/// submission a no-op instead of a toggle.
282///
283/// An id that is not this repository's is `NotFound` rather than quietly dropped:
284/// dropping it would let a tampered form put somebody else's label on an issue and give
285/// no sign it had happened.
286///
287/// The issue's `updated_at` does **not** move. It marks when what the issue *says* last
288/// changed — an edit, a comment, a close — and a label is a way of describing an issue
289/// rather than part of what it says.
290#[allow(clippy::too_many_arguments)]
291pub async fn set_issue_labels(
292 actor: &Actor,
293 handle: &OrgName,
294 name: &RepoName,
295 number: IssueNumber,
296 chosen: &[LabelId],
297 orgs: &impl OrgRepository,
298 memberships: &impl MembershipRepository,
299 repos: &impl RepoRepository,
300 issues: &impl IssueRepository,
301 labels: &impl LabelRepository,
302) -> Result<()> {
303 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
304 let issue = existing_issue(&repo, number, issues).await?;
305
306 let wanted = chosen_labels(&repo, chosen, labels).await?;
307
308 labels.set_issue_labels(&issue.id, &wanted).await?;
309
310 Ok(())
311}
312
313/// The ids a checkbox list submitted, checked against the repository and de-duplicated.
314///
315/// An id that is not this repository's is `NotFound` rather than quietly dropped:
316/// dropping it would let a tampered form put somebody else's label on something and give
317/// no sign it had happened.
318async fn chosen_labels(
319 repo: &Repository,
320 chosen: &[LabelId],
321 labels: &impl LabelRepository,
322) -> Result<Vec<LabelId>> {
323 let known: HashSet<LabelId> = labels
324 .list_by_repo(&repo.id)
325 .await?
326 .into_iter()
327 .map(|label| label.id)
328 .collect();
329
330 let mut seen = HashSet::new();
331 let mut wanted = Vec::with_capacity(chosen.len());
332
333 for id in chosen {
334 if !known.contains(id) {
335 return Err(Error::Domain(DomainError::NotFound { entity: "label" }));
336 }
337
338 // A checkbox cannot be ticked twice, so a repeat is a hand-made submission. It
339 // means the same thing either way, and the store would collapse it anyway.
340 if seen.insert(id.clone()) {
341 wanted.push(id.clone());
342 }
343 }
344
345 Ok(wanted)
346}
347
348/// Replaces a pull request's labels with exactly this set. Owner only.
349///
350/// [`set_issue_labels`]'s counterpart, down to the refusal of an id from another
351/// repository, and it shares [`chosen_labels`] with it so the two cannot come to
352/// disagree about what a tampered form means.
353#[allow(clippy::too_many_arguments)]
354pub async fn set_pull_labels(
355 actor: &Actor,
356 handle: &OrgName,
357 name: &RepoName,
358 number: IssueNumber,
359 chosen: &[LabelId],
360 orgs: &impl OrgRepository,
361 memberships: &impl MembershipRepository,
362 repos: &impl RepoRepository,
363 pulls: &impl PullRequestRepository,
364 labels: &impl LabelRepository,
365) -> Result<()> {
366 let repo = writable_repo(actor, handle, name, orgs, memberships, repos).await?;
367 let pull = existing_pull(&repo, number, pulls).await?;
368 let wanted = chosen_labels(&repo, chosen, labels).await?;
369
370 labels.set_pull_labels(&pull.id, &wanted).await?;
371
372 Ok(())
373}
374
375// --- Shared resolution ----------------------------------------------------------------
376
377/// The label with this id **on this repository**, or `NotFound`.
378async fn owned_label(
379 repo: &Repository,
380 id: &LabelId,
381 labels: &impl LabelRepository,
382) -> Result<Label> {
383 labels
384 .find_by_id(id)
385 .await?
386 .filter(|label| label.repo_id == repo.id)
387 .ok_or(Error::Domain(DomainError::NotFound { entity: "label" }))
388}
389
390/// The refusal a duplicate name earns, worded for the form that shows it.
391fn taken(name: &str) -> Error {
392 Error::Domain(DomainError::validation(
393 "name",
394 format!("this repository already has a label called {name:?}"),
395 ))
396}
397
398#[cfg(test)]
399mod tests {
400 use std::time::Duration;
401
402 use super::*;
403 use crate::{
404 domain::{
405 Email, Issue, IssueNumber, Membership, MembershipId, OrgId, Organization, PasswordHash,
406 RepoId, Role, User, UserId, Visibility,
407 repository::{MembershipRepository, OrgRepository, RepoRepository, UserRepository},
408 },
409 infrastructure::repository::{
410 InMemoryIssueRepo, InMemoryLabelRepo, InMemoryMembershipRepo, InMemoryOrgRepo,
411 InMemoryPullRequestRepo, InMemoryRepoRepo, InMemoryUserRepo,
412 },
413 };
414
415 fn at(seconds: u64) -> SystemTime {
416 SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)
417 }
418
419 struct Fixture {
420 orgs: InMemoryOrgRepo,
421 memberships: InMemoryMembershipRepo,
422 repos: InMemoryRepoRepo,
423 issues: InMemoryIssueRepo,
424 pulls: InMemoryPullRequestRepo,
425 users: InMemoryUserRepo,
426 labels: InMemoryLabelRepo,
427 handle: OrgName,
428 owner: Actor,
429 member: Actor,
430 stranger: Actor,
431 }
432
433 /// One organisation with an owner and a plain member, a public repository `steid`
434 /// and a second public one `other` — the second is what proves a label is scoped to
435 /// its repository rather than to the instance.
436 async fn fixture() -> Fixture {
437 let orgs = InMemoryOrgRepo::new();
438 let memberships = InMemoryMembershipRepo::new();
439 let repos = InMemoryRepoRepo::new();
440 let users = InMemoryUserRepo::new();
441
442 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
443 orgs.save(&org).await.expect("save org");
444
445 let mut actors = Vec::new();
446
447 for (email, role) in [
448 ("owner@example.com", Role::Owner),
449 ("member@example.com", Role::Member),
450 ] {
451 let user = User::new(
452 UserId::generate(),
453 Email::new(email).expect("valid email"),
454 PasswordHash::from_trusted("$argon2id$test"),
455 org.id.clone(),
456 );
457
458 users.save(&user).await.expect("save user");
459 memberships
460 .save(&Membership::new(
461 MembershipId::generate(),
462 org.id.clone(),
463 user.id.clone(),
464 role,
465 ))
466 .await
467 .expect("save membership");
468
469 actors.push(Actor::User(user.id));
470 }
471
472 for (name, visibility) in [
473 ("steid", Visibility::Public),
474 ("other", Visibility::Public),
475 ("secret", Visibility::Private),
476 ] {
477 repos
478 .save(
479 &Repository::new(
480 RepoId::generate(),
481 org.id.clone(),
482 name,
483 None,
484 visibility,
485 at(1_000),
486 )
487 .expect("valid repo"),
488 )
489 .await
490 .expect("save repo");
491 }
492
493 let member = actors.pop().expect("member");
494 let owner = actors.pop().expect("owner");
495
496 Fixture {
497 orgs,
498 memberships,
499 repos,
500 issues: InMemoryIssueRepo::new(),
501 pulls: InMemoryPullRequestRepo::new(),
502 users,
503 labels: InMemoryLabelRepo::new(),
504 handle: org.name.clone(),
505 owner,
506 member,
507 stranger: Actor::Anonymous,
508 }
509 }
510
511 fn repo(name: &str) -> RepoName {
512 RepoName::new(name).expect("valid name")
513 }
514
515 fn spec(name: &str, colour: LabelColour) -> NewLabel {
516 NewLabel {
517 name: name.to_owned(),
518 colour,
519 description: None,
520 }
521 }
522
523 async fn make(f: &Fixture, on: &str, name: &str, colour: LabelColour) -> Result<()> {
524 create_label(
525 &f.owner,
526 &f.handle,
527 &repo(on),
528 &spec(name, colour),
529 at(2_000),
530 &f.orgs,
531 &f.memberships,
532 &f.repos,
533 &f.labels,
534 )
535 .await
536 }
537
538 async fn page(f: &Fixture, actor: &Actor, on: &str) -> Option<LabelPage> {
539 list_labels(
540 actor,
541 &f.handle,
542 &repo(on),
543 &f.orgs,
544 &f.memberships,
545 &f.repos,
546 &f.labels,
547 )
548 .await
549 .expect("should list")
550 }
551
552 async fn id_of(f: &Fixture, on: &str, name: &str) -> LabelId {
553 page(f, &f.owner, on)
554 .await
555 .expect("visible")
556 .labels
557 .into_iter()
558 .find(|row| row.label.name == name)
559 .expect("label is there")
560 .label
561 .id
562 }
563
564 /// Opens an issue directly through the port: these tests are about labels, and
565 /// going through `create_issue` would only add its authorization to every one.
566 async fn open(f: &Fixture, on: &str, title: &str) -> Issue {
567 let repository = f
568 .repos
569 .find_by_org_and_name(
570 &f.orgs
571 .find_by_name(&f.handle)
572 .await
573 .expect("query")
574 .expect("org")
575 .id,
576 &repo(on),
577 )
578 .await
579 .expect("query")
580 .expect("repo");
581
582 let author = match &f.owner {
583 Actor::User(id) => id.clone(),
584 Actor::Anonymous => unreachable!("the owner is a user"),
585 };
586
587 let number = f.issues.next_number(&repository.id).await.expect("number");
588 let issue = Issue::new(
589 crate::domain::IssueId::generate(),
590 repository.id,
591 number,
592 title,
593 "",
594 author,
595 at(2_000),
596 )
597 .expect("valid issue");
598
599 f.issues.save(&issue).await.expect("save issue");
600
601 issue
602 }
603
604 async fn assign(f: &Fixture, on: &str, number: u64, chosen: &[LabelId]) -> Result<()> {
605 set_issue_labels(
606 &f.owner,
607 &f.handle,
608 &repo(on),
609 IssueNumber::from_trusted(number),
610 chosen,
611 &f.orgs,
612 &f.memberships,
613 &f.repos,
614 &f.issues,
615 &f.labels,
616 )
617 .await
618 }
619
620 async fn listed(f: &Fixture, on: &str, filter: Option<&str>) -> crate::application::IssueList {
621 crate::application::list_issues(
622 &f.owner,
623 &f.handle,
624 &repo(on),
625 crate::domain::IssueState::Open,
626 filter,
627 1,
628 &f.orgs,
629 &f.memberships,
630 &f.repos,
631 &f.issues,
632 &f.users,
633 &f.labels,
634 )
635 .await
636 .expect("should list")
637 .expect("visible")
638 }
639
640 // --- creating -------------------------------------------------------------------
641
642 #[tokio::test]
643 async fn a_created_label_is_listed_with_no_issues_on_it() {
644 let f = fixture().await;
645
646 make(&f, "steid", "bug", LabelColour::Red)
647 .await
648 .expect("should create");
649
650 let page = page(&f, &f.owner, "steid").await.expect("visible");
651
652 assert_eq!(page.labels.len(), 1);
653 assert_eq!(page.labels[0].label.name, "bug");
654 assert_eq!(page.labels[0].label.colour, LabelColour::Red);
655 assert_eq!(page.labels[0].issues, 0);
656 assert!(page.viewer_is_owner);
657 }
658
659 #[tokio::test]
660 async fn labels_are_listed_by_name() {
661 let f = fixture().await;
662
663 for name in ["docs", "bug", "chore"] {
664 make(&f, "steid", name, LabelColour::Gray)
665 .await
666 .expect("should create");
667 }
668
669 let names: Vec<String> = page(&f, &f.owner, "steid")
670 .await
671 .expect("visible")
672 .labels
673 .into_iter()
674 .map(|row| row.label.name)
675 .collect();
676
677 assert_eq!(names, ["bug", "chore", "docs"]);
678 }
679
680 #[tokio::test]
681 async fn a_name_is_unique_within_a_repository_and_free_on_another() {
682 let f = fixture().await;
683
684 make(&f, "steid", "bug", LabelColour::Red)
685 .await
686 .expect("should create");
687
688 // The same name again, including with the whitespace that trims to it.
689 assert!(matches!(
690 make(&f, "steid", "bug", LabelColour::Blue).await,
691 Err(Error::Domain(DomainError::Validation { .. }))
692 ));
693 assert!(matches!(
694 make(&f, "steid", " bug ", LabelColour::Blue).await,
695 Err(Error::Domain(DomainError::Validation { .. }))
696 ));
697
698 // A label belongs to its repository, so the same word is free next door.
699 make(&f, "other", "bug", LabelColour::Blue)
700 .await
701 .expect("should create");
702
703 assert_eq!(
704 page(&f, &f.owner, "steid")
705 .await
706 .expect("visible")
707 .labels
708 .len(),
709 1
710 );
711 assert_eq!(
712 page(&f, &f.owner, "other")
713 .await
714 .expect("visible")
715 .labels
716 .len(),
717 1
718 );
719 }
720
721 #[tokio::test]
722 async fn only_the_owner_writes_and_anyone_who_can_read_the_repository_reads() {
723 let f = fixture().await;
724
725 make(&f, "steid", "bug", LabelColour::Red)
726 .await
727 .expect("should create");
728
729 for actor in [&f.member, &f.stranger] {
730 assert!(page(&f, actor, "steid").await.is_some(), "readable");
731
732 assert!(matches!(
733 create_label(
734 actor,
735 &f.handle,
736 &repo("steid"),
737 &spec("wontfix", LabelColour::Gray),
738 at(3_000),
739 &f.orgs,
740 &f.memberships,
741 &f.repos,
742 &f.labels,
743 )
744 .await,
745 Err(Error::Domain(DomainError::Forbidden))
746 ));
747 }
748
749 // A private repository is absent rather than locked, for everyone but its owner.
750 assert!(page(&f, &f.stranger, "secret").await.is_none());
751 assert!(page(&f, &f.member, "secret").await.is_some());
752 }
753
754 // --- editing --------------------------------------------------------------------
755
756 #[tokio::test]
757 async fn a_label_can_be_renamed_and_recoloured_but_not_onto_another_name() {
758 let f = fixture().await;
759
760 make(&f, "steid", "bug", LabelColour::Red)
761 .await
762 .expect("should create");
763 make(&f, "steid", "docs", LabelColour::Blue)
764 .await
765 .expect("should create");
766
767 let bug = id_of(&f, "steid", "bug").await;
768
769 let edit = |name: &str, colour| LabelEdit {
770 name: name.to_owned(),
771 colour,
772 description: None,
773 };
774
775 let apply = async |id: &LabelId, edit: LabelEdit| {
776 update_label(
777 &f.owner,
778 &f.handle,
779 &repo("steid"),
780 id,
781 &edit,
782 &f.orgs,
783 &f.memberships,
784 &f.repos,
785 &f.labels,
786 )
787 .await
788 };
789
790 // Onto a name another label already has.
791 assert!(matches!(
792 apply(&bug, edit("docs", LabelColour::Red)).await,
793 Err(Error::Domain(DomainError::Validation { .. }))
794 ));
795
796 // Keeping its own name while changing the colour is not a clash with itself.
797 apply(&bug, edit("bug", LabelColour::Purple))
798 .await
799 .expect("should recolour");
800
801 apply(&bug, edit("defect", LabelColour::Purple))
802 .await
803 .expect("should rename");
804
805 let names: Vec<String> = page(&f, &f.owner, "steid")
806 .await
807 .expect("visible")
808 .labels
809 .into_iter()
810 .map(|row| row.label.name)
811 .collect();
812
813 assert_eq!(names, ["defect", "docs"]);
814 }
815
816 #[tokio::test]
817 async fn a_label_belonging_to_another_repository_is_not_found() {
818 let f = fixture().await;
819
820 make(&f, "other", "bug", LabelColour::Red)
821 .await
822 .expect("should create");
823 let elsewhere = id_of(&f, "other", "bug").await;
824
825 // Addressed through `steid`, which does not have it.
826 assert!(matches!(
827 delete_label(
828 &f.owner,
829 &f.handle,
830 &repo("steid"),
831 &elsewhere,
832 &f.orgs,
833 &f.memberships,
834 &f.repos,
835 &f.labels,
836 )
837 .await,
838 Err(Error::Domain(DomainError::NotFound { entity: "label" }))
839 ));
840
841 assert_eq!(
842 page(&f, &f.owner, "other")
843 .await
844 .expect("visible")
845 .labels
846 .len(),
847 1
848 );
849 }
850
851 // --- assignment -----------------------------------------------------------------
852
853 #[tokio::test]
854 async fn setting_the_full_set_replaces_what_was_there_and_repeats_are_no_ops() {
855 let f = fixture().await;
856
857 for name in ["bug", "docs", "chore"] {
858 make(&f, "steid", name, LabelColour::Gray)
859 .await
860 .expect("should create");
861 }
862
863 let bug = id_of(&f, "steid", "bug").await;
864 let docs = id_of(&f, "steid", "docs").await;
865 let chore = id_of(&f, "steid", "chore").await;
866
867 open(&f, "steid", "Blame is slow").await;
868
869 assign(&f, "steid", 1, &[bug.clone(), docs.clone()])
870 .await
871 .expect("should assign");
872 assert_eq!(carried(&f, "steid", 1).await, ["bug", "docs"]);
873
874 // Submitting the same thing twice changes nothing.
875 assign(&f, "steid", 1, &[bug.clone(), docs.clone()])
876 .await
877 .expect("should assign");
878 assert_eq!(carried(&f, "steid", 1).await, ["bug", "docs"]);
879
880 // The whole set, so what is absent comes off.
881 assign(&f, "steid", 1, std::slice::from_ref(&chore))
882 .await
883 .expect("should assign");
884 assert_eq!(carried(&f, "steid", 1).await, ["chore"]);
885
886 // An empty set clears it.
887 assign(&f, "steid", 1, &[]).await.expect("should assign");
888 assert!(carried(&f, "steid", 1).await.is_empty());
889
890 // The same id twice is one assignment, not a failure.
891 assign(&f, "steid", 1, &[bug.clone(), bug])
892 .await
893 .expect("should assign");
894 assert_eq!(carried(&f, "steid", 1).await, ["bug"]);
895 }
896
897 #[tokio::test]
898 async fn a_label_from_another_repository_cannot_be_put_on_an_issue() {
899 let f = fixture().await;
900
901 make(&f, "other", "bug", LabelColour::Red)
902 .await
903 .expect("should create");
904 let elsewhere = id_of(&f, "other", "bug").await;
905
906 open(&f, "steid", "Blame is slow").await;
907
908 assert!(matches!(
909 assign(&f, "steid", 1, &[elsewhere]).await,
910 Err(Error::Domain(DomainError::NotFound { entity: "label" }))
911 ));
912 assert!(carried(&f, "steid", 1).await.is_empty());
913 }
914
915 #[tokio::test]
916 async fn deleting_a_label_takes_it_off_every_issue_and_leaves_the_issues_alone() {
917 let f = fixture().await;
918
919 make(&f, "steid", "bug", LabelColour::Red)
920 .await
921 .expect("should create");
922 make(&f, "steid", "docs", LabelColour::Blue)
923 .await
924 .expect("should create");
925
926 let bug = id_of(&f, "steid", "bug").await;
927 let docs = id_of(&f, "steid", "docs").await;
928
929 open(&f, "steid", "Blame is slow").await;
930 open(&f, "steid", "Docs are thin").await;
931
932 assign(&f, "steid", 1, &[bug.clone(), docs.clone()])
933 .await
934 .expect("should assign");
935 assign(&f, "steid", 2, std::slice::from_ref(&bug))
936 .await
937 .expect("should assign");
938
939 assert_eq!(
940 page(&f, &f.owner, "steid")
941 .await
942 .expect("visible")
943 .labels
944 .into_iter()
945 .map(|row| (row.label.name, row.issues))
946 .collect::<Vec<_>>(),
947 [("bug".to_owned(), 2), ("docs".to_owned(), 1)]
948 );
949
950 delete_label(
951 &f.owner,
952 &f.handle,
953 &repo("steid"),
954 &bug,
955 &f.orgs,
956 &f.memberships,
957 &f.repos,
958 &f.labels,
959 )
960 .await
961 .expect("should delete");
962
963 assert_eq!(carried(&f, "steid", 1).await, ["docs"]);
964 assert!(carried(&f, "steid", 2).await.is_empty());
965 // Both issues are still there — a label is a way of describing an issue, not
966 // part of what it says.
967 assert_eq!(listed(&f, "steid", None).await.issues.items.len(), 2);
968 }
969
970 // --- filtering ------------------------------------------------------------------
971
972 #[tokio::test]
973 async fn the_issues_list_narrows_to_a_label_and_the_counts_follow() {
974 let f = fixture().await;
975
976 make(&f, "steid", "bug", LabelColour::Red)
977 .await
978 .expect("should create");
979 let bug = id_of(&f, "steid", "bug").await;
980
981 open(&f, "steid", "Blame is slow").await;
982 open(&f, "steid", "Docs are thin").await;
983 open(&f, "steid", "Search is slow").await;
984
985 assign(&f, "steid", 1, std::slice::from_ref(&bug))
986 .await
987 .expect("should assign");
988 assign(&f, "steid", 3, &[bug]).await.expect("should assign");
989
990 let all = listed(&f, "steid", None).await;
991 assert_eq!(all.issues.items.len(), 3);
992 assert_eq!(all.open, 3);
993 assert_eq!(all.filter, None);
994
995 let filtered = listed(&f, "steid", Some("bug")).await;
996 assert_eq!(
997 filtered
998 .issues
999 .items
1000 .iter()
1001 .map(|issue| issue.number.get())
1002 .collect::<Vec<_>>(),
1003 [3, 1]
1004 );
1005 // The toolbar's counts obey the filter, so "Open 2" is what is below it.
1006 assert_eq!(filtered.open, 2);
1007 assert_eq!(filtered.closed, 0);
1008 assert_eq!(
1009 filtered.filter.as_ref().map(|label| label.name.as_str()),
1010 Some("bug")
1011 );
1012
1013 // Every row carries its pills.
1014 assert_eq!(
1015 filtered.issues.items[0]
1016 .labels
1017 .iter()
1018 .map(|label| label.name.as_str())
1019 .collect::<Vec<_>>(),
1020 ["bug"]
1021 );
1022 }
1023
1024 #[tokio::test]
1025 async fn a_label_name_that_matches_nothing_filters_everything_out() {
1026 let f = fixture().await;
1027
1028 open(&f, "steid", "Blame is slow").await;
1029
1030 // Not "show me everything": a filter that quietly failed to resolve would show
1031 // a list that looks filtered and is not.
1032 let filtered = listed(&f, "steid", Some("nonesuch")).await;
1033
1034 assert!(filtered.issues.items.is_empty());
1035 assert_eq!(filtered.open, 0);
1036 assert_eq!(filtered.filter, None);
1037 }
1038
1039 /// The names of the labels on one issue, in the order they render.
1040 async fn carried(f: &Fixture, on: &str, number: u64) -> Vec<String> {
1041 crate::application::view_issue(
1042 &f.owner,
1043 &f.handle,
1044 &repo(on),
1045 IssueNumber::from_trusted(number),
1046 &f.orgs,
1047 &f.memberships,
1048 &f.repos,
1049 &f.issues,
1050 &f.users,
1051 &f.labels,
1052 )
1053 .await
1054 .expect("should read")
1055 .expect("visible")
1056 .labels
1057 .into_iter()
1058 .map(|label| label.name)
1059 .collect()
1060 }
1061
1062 // --- pull requests wear the same labels ------------------------------------------
1063
1064 /// Opens a pull request directly through the port, for the reason [`open`] does:
1065 /// these tests are about labels.
1066 async fn open_pull(f: &Fixture, on: &str, title: &str) -> crate::domain::PullRequest {
1067 let repository = f
1068 .repos
1069 .find_by_org_and_name(
1070 &f.orgs
1071 .find_by_name(&f.handle)
1072 .await
1073 .expect("query")
1074 .expect("org")
1075 .id,
1076 &repo(on),
1077 )
1078 .await
1079 .expect("query")
1080 .expect("repo");
1081
1082 let author = match &f.owner {
1083 Actor::User(id) => id.clone(),
1084 Actor::Anonymous => unreachable!("the owner is a user"),
1085 };
1086
1087 // The same allocator issues draw from, which is what makes `#7` one thing.
1088 let number = f.issues.next_number(&repository.id).await.expect("number");
1089 let pull = crate::domain::PullRequest::new(
1090 crate::domain::PullRequestId::generate(),
1091 repository.id,
1092 number,
1093 title,
1094 "",
1095 author,
1096 crate::domain::RefName::from_trusted("spike"),
1097 crate::domain::RefName::from_trusted("main"),
1098 at(2_000),
1099 )
1100 .expect("valid pull request");
1101
1102 f.pulls.save(&pull).await.expect("save pull request");
1103
1104 pull
1105 }
1106
1107 async fn assign_pull(f: &Fixture, on: &str, number: u64, chosen: &[LabelId]) -> Result<()> {
1108 set_pull_labels(
1109 &f.owner,
1110 &f.handle,
1111 &repo(on),
1112 IssueNumber::from_trusted(number),
1113 chosen,
1114 &f.orgs,
1115 &f.memberships,
1116 &f.repos,
1117 &f.pulls,
1118 &f.labels,
1119 )
1120 .await
1121 }
1122
1123 async fn listed_pulls(
1124 f: &Fixture,
1125 on: &str,
1126 filter: Option<&str>,
1127 ) -> crate::application::PullList {
1128 crate::application::list_pulls(
1129 &f.owner,
1130 &f.handle,
1131 &repo(on),
1132 crate::domain::PullRequestState::Open,
1133 filter,
1134 1,
1135 &f.orgs,
1136 &f.memberships,
1137 &f.repos,
1138 &f.pulls,
1139 &f.users,
1140 &f.labels,
1141 )
1142 .await
1143 .expect("should list")
1144 .expect("visible")
1145 }
1146
1147 #[tokio::test]
1148 async fn the_pull_request_list_narrows_to_a_label_and_the_counts_follow() {
1149 let f = fixture().await;
1150 make(&f, "steid", "bug", LabelColour::Red)
1151 .await
1152 .expect("made");
1153 let bug = id_of(&f, "steid", "bug").await;
1154
1155 let labelled = open_pull(&f, "steid", "Fix the parser").await;
1156 open_pull(&f, "steid", "Bump a dependency").await;
1157
1158 assign_pull(&f, "steid", labelled.number.get(), &[bug])
1159 .await
1160 .expect("assigned");
1161
1162 let all = listed_pulls(&f, "steid", None).await;
1163 assert_eq!(all.pulls.items.len(), 2);
1164 assert_eq!(all.open, 2);
1165
1166 let filtered = listed_pulls(&f, "steid", Some("bug")).await;
1167 assert_eq!(filtered.pulls.items.len(), 1);
1168 assert_eq!(filtered.pulls.items[0].number, labelled.number);
1169 // The toolbar must not say "Open 2" above one row.
1170 assert_eq!((filtered.open, filtered.merged, filtered.closed), (1, 0, 0));
1171 assert_eq!(
1172 filtered.filter.as_ref().map(|pill| pill.name.as_str()),
1173 Some("bug")
1174 );
1175 // The pills the row draws are the ones it wears.
1176 assert_eq!(
1177 filtered.pulls.items[0]
1178 .labels
1179 .iter()
1180 .map(|pill| pill.name.as_str())
1181 .collect::<Vec<_>>(),
1182 vec!["bug"]
1183 );
1184 }
1185
1186 #[tokio::test]
1187 async fn a_label_from_another_repository_cannot_be_put_on_a_pull_request() {
1188 let f = fixture().await;
1189 make(&f, "other", "bug", LabelColour::Red)
1190 .await
1191 .expect("made");
1192 let elsewhere = id_of(&f, "other", "bug").await;
1193 let pull = open_pull(&f, "steid", "Fix the parser").await;
1194
1195 assert!(matches!(
1196 assign_pull(&f, "steid", pull.number.get(), &[elsewhere]).await,
1197 Err(Error::Domain(DomainError::NotFound { entity: "label" }))
1198 ));
1199 }
1200
1201 #[tokio::test]
1202 async fn the_labels_page_counts_issues_and_pull_requests_apart() {
1203 // One number covering both would make the delete confirmation wrong for
1204 // whichever kind it was not counting.
1205 let f = fixture().await;
1206 make(&f, "steid", "bug", LabelColour::Red)
1207 .await
1208 .expect("made");
1209 let bug = id_of(&f, "steid", "bug").await;
1210
1211 let issue = open(&f, "steid", "It crashes").await;
1212 let pull = open_pull(&f, "steid", "Fix the crash").await;
1213
1214 assign(&f, "steid", issue.number.get(), std::slice::from_ref(&bug))
1215 .await
1216 .expect("assigned");
1217 assign_pull(&f, "steid", pull.number.get(), std::slice::from_ref(&bug))
1218 .await
1219 .expect("assigned");
1220
1221 let listed = page(&f, &f.owner, "steid").await.expect("visible");
1222 let row = &listed.labels[0];
1223
1224 assert_eq!((row.issues, row.pulls), (1, 1));
1225 }
1226
1227 #[tokio::test]
1228 async fn deleting_a_label_takes_it_off_pull_requests_too() {
1229 let f = fixture().await;
1230 make(&f, "steid", "bug", LabelColour::Red)
1231 .await
1232 .expect("made");
1233 let bug = id_of(&f, "steid", "bug").await;
1234 let pull = open_pull(&f, "steid", "Fix the parser").await;
1235
1236 assign_pull(&f, "steid", pull.number.get(), std::slice::from_ref(&bug))
1237 .await
1238 .expect("assigned");
1239
1240 delete_label(
1241 &f.owner,
1242 &f.handle,
1243 &repo("steid"),
1244 &bug,
1245 &f.orgs,
1246 &f.memberships,
1247 &f.repos,
1248 &f.labels,
1249 )
1250 .await
1251 .expect("deleted");
1252
1253 let listed = listed_pulls(&f, "steid", None).await;
1254 assert_eq!(listed.pulls.items.len(), 1);
1255 assert!(listed.pulls.items[0].labels.is_empty());
1256 }
1257}