Skip to main content

gitpoulpi_hosting/
board.rs

1//! The Kanban board's column logic (slice L2): which columns an issue source
2//! has, which column each issue sits in, what a move changes, and the board
3//! filters. Pure data in, pure data out: no IO and no UI, so the TUI, a CLI
4//! and a provider added later (Linear, YouTrack) share it.
5//!
6//! A provider declares how its issues form columns with
7//! [`HostingClient::board_source`](crate::HostingClient::board_source) and, for
8//! the status-like sources, the ordered names with
9//! [`HostingClient::issue_statuses`](crate::HostingClient::issue_statuses).
10//! Moving a card is [`HostingClient::move_issue`](crate::HostingClient::move_issue),
11//! whose default executes the [`MovePlan`] computed here.
12
13use std::collections::HashSet;
14
15use crate::model::{IssueState, IssueSummary};
16use crate::{Error, Result};
17
18/// How an issue source forms its columns.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
20pub enum BoardSource {
21    /// Open / Closed only: a provider with no workflow, nothing configured.
22    #[default]
23    OpenClosed,
24    /// A status the tool owns and can change (local Markdown notes).
25    LocalStatus,
26    /// A workflow status of the provider that cannot be changed from here
27    /// (`IssueSummary::status_label`; Jira and Azure now use `LocalStatus`:
28    /// their clients override `move_issue` with a transition / state patch;
29    /// nothing uses this today). Read-only until the client overrides
30    /// `move_issue`.
31    ProviderStatus,
32    /// A list of the provider's board (`IssueSummary::kind_label`: Trello).
33    Lists,
34    /// A configurable set of labels, one per column, plus Open and Closed
35    /// (GitHub, GitLab, Gitea, Forgejo).
36    Labels,
37}
38
39impl BoardSource {
40    /// Whether a card can be moved at all with the default `move_issue`.
41    pub fn movable(self) -> bool {
42        !matches!(self, BoardSource::ProviderStatus)
43    }
44}
45
46/// What a source needs to lay its board out.
47#[derive(Debug, Clone, PartialEq, Eq, Default)]
48pub struct BoardSpec {
49    pub source: BoardSource,
50    /// The ordered column names the provider declares
51    /// (`HostingClient::issue_statuses`); the status-like sources only.
52    pub declared: Vec<String>,
53    /// The labels that form the columns of a [`BoardSource::Labels`] board,
54    /// in board order (configured per repository).
55    pub labels: Vec<String>,
56}
57
58/// What a column is, so the frontend can translate the two fixed ones.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum ColumnRole {
61    /// A status, a list or a label: `name` is shown as it is.
62    Named,
63    /// The column of open issues with no status label.
64    Open,
65    /// The column of closed issues.
66    Closed,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct BoardColumn {
71    pub name: String,
72    pub role: ColumnRole,
73}
74
75impl BoardColumn {
76    fn named(name: &str) -> Self {
77        Self {
78            name: name.to_string(),
79            role: ColumnRole::Named,
80        }
81    }
82
83    fn open() -> Self {
84        Self {
85            name: "Open".into(), // i18n-english
86            role: ColumnRole::Open,
87        }
88    }
89
90    fn closed() -> Self {
91        Self {
92            name: "Closed".into(), // i18n-english
93            role: ColumnRole::Closed,
94        }
95    }
96}
97
98/// The status-like value of an issue for `source` (`None` for the sources
99/// that do not use one, or an issue with no value).
100fn status_of(source: BoardSource, issue: &IssueSummary) -> Option<&str> {
101    let value = match source {
102        BoardSource::LocalStatus | BoardSource::ProviderStatus => issue.status_label.as_deref(),
103        BoardSource::Lists => issue.kind_label.as_deref(),
104        BoardSource::OpenClosed | BoardSource::Labels => None,
105    };
106    value.map(str::trim).filter(|v| !v.is_empty())
107}
108
109fn same(a: &str, b: &str) -> bool {
110    a.trim().eq_ignore_ascii_case(b.trim())
111}
112
113/// The columns of the board, left to right: the declared names first, then
114/// any other value the issues carry (in order of first appearance).
115pub fn columns(spec: &BoardSpec, issues: &[IssueSummary]) -> Vec<BoardColumn> {
116    match spec.source {
117        BoardSource::OpenClosed => vec![BoardColumn::open(), BoardColumn::closed()],
118        BoardSource::Labels => {
119            let mut out = vec![BoardColumn::open()];
120            let mut seen: Vec<&str> = Vec::new();
121            for label in &spec.labels {
122                if !seen.iter().any(|s| same(s, label)) && !label.trim().is_empty() {
123                    seen.push(label);
124                    out.push(BoardColumn::named(label.trim()));
125                }
126            }
127            out.push(BoardColumn::closed());
128            out
129        }
130        BoardSource::LocalStatus | BoardSource::ProviderStatus | BoardSource::Lists => {
131            let mut names: Vec<String> = Vec::new();
132            let declared = spec.declared.iter().map(String::as_str);
133            let seen = issues.iter().filter_map(|i| status_of(spec.source, i));
134            for name in declared.chain(seen) {
135                let name = name.trim();
136                if !name.is_empty() && !names.iter().any(|n| same(n, name)) {
137                    names.push(name.to_string());
138                }
139            }
140            if names.is_empty() {
141                // Nothing declared and nothing seen: a board still has columns.
142                return vec![BoardColumn::open(), BoardColumn::closed()];
143            }
144            names.iter().map(|n| BoardColumn::named(n)).collect()
145        }
146    }
147}
148
149/// The index in `cols` of the column `issue` sits in. An issue with no
150/// status goes to the first column (open) or the last (closed).
151pub fn column_index(spec: &BoardSpec, cols: &[BoardColumn], issue: &IssueSummary) -> usize {
152    let last = cols.len().saturating_sub(1);
153    let closed_slot = || {
154        cols.iter()
155            .position(|c| c.role == ColumnRole::Closed)
156            .unwrap_or(last)
157    };
158    match spec.source {
159        BoardSource::OpenClosed => usize::from(issue.state == IssueState::Closed),
160        BoardSource::Labels => {
161            if issue.state == IssueState::Closed {
162                return closed_slot();
163            }
164            spec.labels
165                .iter()
166                .find(|l| issue.labels.iter().any(|have| same(have, l)))
167                .and_then(|l| cols.iter().position(|c| same(&c.name, l)))
168                .unwrap_or(0)
169        }
170        _ => match status_of(spec.source, issue) {
171            Some(value) => cols.iter().position(|c| same(&c.name, value)).unwrap_or(
172                if issue.state == IssueState::Closed {
173                    last
174                } else {
175                    0
176                },
177            ),
178            None if issue.state == IssueState::Closed => closed_slot(),
179            None => 0,
180        },
181    }
182}
183
184/// What moving an issue to a column changes. Only the parts that differ are
185/// set.
186#[derive(Debug, Clone, Default, PartialEq, Eq)]
187pub struct MovePlan {
188    /// The new status (local Markdown).
189    pub status: Option<String>,
190    /// The new list (Trello).
191    pub list: Option<String>,
192    /// The complete new label set.
193    pub labels: Option<Vec<String>>,
194    /// Close (`true`) or reopen (`false`).
195    pub closed: Option<bool>,
196}
197
198impl MovePlan {
199    pub fn is_empty(&self) -> bool {
200        self.status.is_none()
201            && self.list.is_none()
202            && self.labels.is_none()
203            && self.closed.is_none()
204    }
205}
206
207/// What it takes to move `issue` to `to`. `Err(Unsupported)` for a read-only
208/// source.
209pub fn plan_move(spec: &BoardSpec, issue: &IssueSummary, to: &BoardColumn) -> Result<MovePlan> {
210    let mut plan = MovePlan::default();
211    match spec.source {
212        BoardSource::ProviderStatus => {
213            return Err(Error::Unsupported("moving an issue to a column".into()));
214        }
215        BoardSource::LocalStatus => {
216            if !status_of(spec.source, issue).is_some_and(|s| same(s, &to.name)) {
217                plan.status = Some(to.name.clone());
218            }
219        }
220        BoardSource::Lists => {
221            if !status_of(spec.source, issue).is_some_and(|s| same(s, &to.name)) {
222                plan.list = Some(to.name.clone());
223            }
224        }
225        BoardSource::OpenClosed | BoardSource::Labels => {
226            let is_closed = issue.state == IssueState::Closed;
227            let want_closed = to.role == ColumnRole::Closed;
228            if is_closed != want_closed {
229                plan.closed = Some(want_closed);
230            }
231            if spec.source == BoardSource::Labels && !want_closed {
232                let mut labels: Vec<String> = issue
233                    .labels
234                    .iter()
235                    .filter(|have| !spec.labels.iter().any(|l| same(have, l)))
236                    .cloned()
237                    .collect();
238                if to.role == ColumnRole::Named {
239                    labels.push(to.name.clone());
240                }
241                if labels != issue.labels {
242                    plan.labels = Some(labels);
243                }
244            }
245        }
246    }
247    Ok(plan)
248}
249
250/// Applies `plan` to the cached copy of the issue, so the board shows the
251/// result without waiting for the next listing.
252pub fn apply_plan(issue: &mut IssueSummary, plan: &MovePlan) {
253    if let Some(status) = &plan.status {
254        issue.status_label = Some(status.clone());
255    }
256    if let Some(list) = &plan.list {
257        issue.kind_label = Some(list.clone());
258    }
259    if let Some(labels) = &plan.labels {
260        issue.labels = labels.clone();
261    }
262    if let Some(closed) = plan.closed {
263        issue.state = if closed {
264            IssueState::Closed
265        } else {
266            IssueState::Open
267        };
268    }
269}
270
271/// The board filters: an empty field matches everything.
272#[derive(Debug, Clone, Default, PartialEq, Eq)]
273pub struct BoardFilter {
274    pub assignee: Option<String>,
275    pub label: Option<String>,
276    pub milestone: Option<String>,
277    pub text: String,
278}
279
280impl BoardFilter {
281    pub fn is_empty(&self) -> bool {
282        self.assignee.is_none()
283            && self.label.is_none()
284            && self.milestone.is_none()
285            && self.text.trim().is_empty()
286    }
287
288    pub fn matches(&self, issue: &IssueSummary) -> bool {
289        if let Some(a) = &self.assignee {
290            if !issue.assignees.iter().any(|have| same(have, a)) {
291                return false;
292            }
293        }
294        if let Some(l) = &self.label {
295            if !issue.labels.iter().any(|have| same(have, l)) {
296                return false;
297            }
298        }
299        if let Some(m) = &self.milestone {
300            if !issue.milestone.as_deref().is_some_and(|have| same(have, m)) {
301                return false;
302            }
303        }
304        let q = self.text.trim().to_lowercase();
305        q.is_empty()
306            || [&issue.title, &issue.iid_label, &issue.reference]
307                .iter()
308                .any(|f| f.to_lowercase().contains(&q))
309    }
310}
311
312/// The distinct values the filter comboboxes offer, sorted.
313#[derive(Debug, Clone, Default, PartialEq, Eq)]
314pub struct FilterChoices {
315    pub assignees: Vec<String>,
316    pub labels: Vec<String>,
317    pub milestones: Vec<String>,
318}
319
320pub fn filter_choices(issues: &[IssueSummary]) -> FilterChoices {
321    fn distinct<'a>(values: impl Iterator<Item = &'a str>) -> Vec<String> {
322        let mut seen: HashSet<String> = HashSet::new();
323        let mut out: Vec<String> = values
324            .filter(|v| !v.trim().is_empty() && seen.insert(v.to_lowercase()))
325            .map(str::to_string)
326            .collect();
327        out.sort_by_key(|v| v.to_lowercase());
328        out
329    }
330    FilterChoices {
331        assignees: distinct(
332            issues
333                .iter()
334                .flat_map(|i| i.assignees.iter().map(String::as_str)),
335        ),
336        labels: distinct(
337            issues
338                .iter()
339                .flat_map(|i| i.labels.iter().map(String::as_str)),
340        ),
341        milestones: distinct(issues.iter().filter_map(|i| i.milestone.as_deref())),
342    }
343}
344
345/// The labels that look like statuses (`status::todo`, `status:doing`,
346/// `status/done`, `Status: Review`), for the "Set status labels" prompt to
347/// propose. Order is the order given.
348pub fn status_like_labels(all: &[String]) -> Vec<String> {
349    all.iter()
350        .filter(|l| {
351            let lower = l.trim().to_lowercase();
352            ["status::", "status:", "status/", "status-"]
353                .iter()
354                .any(|p| lower.starts_with(p))
355        })
356        .cloned()
357        .collect()
358}
359
360/// Splits a typed `a, b, c` into the label list.
361pub fn parse_label_list(text: &str) -> Vec<String> {
362    let mut out: Vec<String> = Vec::new();
363    for part in text.split(',') {
364        let part = part.trim();
365        if !part.is_empty() && !out.iter().any(|o| same(o, part)) {
366            out.push(part.to_string());
367        }
368    }
369    out
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    fn issue(n: u64, status: Option<&str>, closed: bool, labels: &[&str]) -> IssueSummary {
377        IssueSummary {
378            number: n,
379            id: n.to_string(),
380            iid_label: format!("#{n}"),
381            title: format!("Issue {n}"),
382            status_label: status.map(str::to_string),
383            labels: labels.iter().map(|s| s.to_string()).collect(),
384            state: if closed {
385                IssueState::Closed
386            } else {
387                IssueState::Open
388            },
389            ..IssueSummary::default()
390        }
391    }
392
393    fn names(cols: &[BoardColumn]) -> Vec<&str> {
394        cols.iter().map(|c| c.name.as_str()).collect()
395    }
396
397    fn local(declared: &[&str]) -> BoardSpec {
398        BoardSpec {
399            source: BoardSource::LocalStatus,
400            declared: declared.iter().map(|s| s.to_string()).collect(),
401            labels: Vec::new(),
402        }
403    }
404
405    fn labels_spec(labels: &[&str]) -> BoardSpec {
406        BoardSpec {
407            source: BoardSource::Labels,
408            declared: Vec::new(),
409            labels: labels.iter().map(|s| s.to_string()).collect(),
410        }
411    }
412
413    #[test]
414    fn status_columns_are_the_declared_ones_then_the_values_seen() {
415        let spec = local(&["todo", "doing", "done"]);
416        let issues = [
417            issue(1, Some("review"), false, &[]),
418            issue(2, Some("DOING"), false, &[]),
419            issue(3, Some("blocked"), false, &[]),
420            issue(4, Some("review"), false, &[]),
421        ];
422        let cols = columns(&spec, &issues);
423        assert_eq!(
424            names(&cols),
425            ["todo", "doing", "done", "review", "blocked"],
426            "declared order first, the rest as first seen, no case duplicates"
427        );
428        assert_eq!(
429            column_index(&spec, &cols, &issues[1]),
430            1,
431            "case-insensitive"
432        );
433        assert_eq!(column_index(&spec, &cols, &issues[2]), 4);
434    }
435
436    #[test]
437    fn a_status_board_with_nothing_still_has_open_and_closed() {
438        let cols = columns(&local(&[]), &[]);
439        assert_eq!(names(&cols), ["Open", "Closed"]);
440        assert_eq!(cols[1].role, ColumnRole::Closed);
441    }
442
443    #[test]
444    fn an_issue_without_a_status_goes_first_or_last_by_state() {
445        let spec = BoardSpec {
446            source: BoardSource::ProviderStatus,
447            declared: vec!["To Do".into(), "In Progress".into(), "Done".into()],
448            labels: Vec::new(),
449        };
450        let cols = columns(&spec, &[]);
451        assert_eq!(column_index(&spec, &cols, &issue(1, None, false, &[])), 0);
452        assert_eq!(column_index(&spec, &cols, &issue(2, None, true, &[])), 2);
453        // A closed issue whose status is not a column (renamed workflow).
454        assert_eq!(
455            column_index(&spec, &cols, &issue(3, Some("Gone"), true, &[])),
456            2
457        );
458    }
459
460    #[test]
461    fn trello_lists_come_from_kind_label() {
462        let spec = BoardSpec {
463            source: BoardSource::Lists,
464            declared: vec!["Backlog".into(), "Doing".into()],
465            labels: Vec::new(),
466        };
467        let mut card = issue(1, None, false, &[]);
468        card.kind_label = Some("Doing".into());
469        let cols = columns(&spec, std::slice::from_ref(&card));
470        assert_eq!(names(&cols), ["Backlog", "Doing"]);
471        assert_eq!(column_index(&spec, &cols, &card), 1);
472        let plan = plan_move(&spec, &card, &cols[0]).unwrap();
473        assert_eq!(plan.list.as_deref(), Some("Backlog"));
474        assert!(plan_move(&spec, &card, &cols[1]).unwrap().is_empty());
475    }
476
477    #[test]
478    fn a_label_board_is_open_the_labels_then_closed() {
479        let spec = labels_spec(&["status::todo", "status::doing"]);
480        let issues = [
481            issue(1, None, false, &["bug"]),
482            issue(2, None, false, &["bug", "status::doing"]),
483            issue(3, None, true, &["status::todo"]),
484        ];
485        let cols = columns(&spec, &issues);
486        assert_eq!(
487            names(&cols),
488            ["Open", "status::todo", "status::doing", "Closed"]
489        );
490        assert_eq!(column_index(&spec, &cols, &issues[0]), 0);
491        assert_eq!(column_index(&spec, &cols, &issues[1]), 2);
492        assert_eq!(
493            column_index(&spec, &cols, &issues[2]),
494            3,
495            "closed wins over a status label"
496        );
497    }
498
499    #[test]
500    fn without_a_label_set_a_host_board_is_open_and_closed() {
501        let spec = labels_spec(&[]);
502        let cols = columns(&spec, &[]);
503        assert_eq!(names(&cols), ["Open", "Closed"]);
504        assert_eq!(
505            column_index(&spec, &cols, &issue(1, None, true, &[])),
506            1,
507            "closed"
508        );
509    }
510
511    #[test]
512    fn moving_on_a_label_board_swaps_the_status_label_and_keeps_the_others() {
513        let spec = labels_spec(&["status::todo", "status::doing"]);
514        let cols = columns(&spec, &[]);
515        let card = issue(1, None, false, &["bug", "status::todo"]);
516        let plan = plan_move(&spec, &card, &cols[2]).unwrap();
517        assert_eq!(
518            plan.labels,
519            Some(vec!["bug".to_string(), "status::doing".to_string()])
520        );
521        assert_eq!(plan.closed, None);
522        // Back to Open drops the status label.
523        let plan = plan_move(&spec, &card, &cols[0]).unwrap();
524        assert_eq!(plan.labels, Some(vec!["bug".to_string()]));
525    }
526
527    #[test]
528    fn closing_and_reopening_on_a_label_board() {
529        let spec = labels_spec(&["status::todo"]);
530        let cols = columns(&spec, &[]);
531        let open = issue(1, None, false, &["status::todo"]);
532        let plan = plan_move(&spec, &open, &cols[2]).unwrap();
533        assert_eq!(plan.closed, Some(true));
534        assert_eq!(plan.labels, None, "closing leaves the labels alone");
535        let closed = issue(2, None, true, &[]);
536        let plan = plan_move(&spec, &closed, &cols[1]).unwrap();
537        assert_eq!(plan.closed, Some(false));
538        assert_eq!(plan.labels, Some(vec!["status::todo".to_string()]));
539    }
540
541    #[test]
542    fn moving_on_an_open_closed_board_only_changes_the_state() {
543        let spec = BoardSpec::default();
544        let cols = columns(&spec, &[]);
545        let card = issue(1, None, false, &["bug"]);
546        let plan = plan_move(&spec, &card, &cols[1]).unwrap();
547        assert_eq!(
548            plan,
549            MovePlan {
550                closed: Some(true),
551                ..MovePlan::default()
552            }
553        );
554    }
555
556    #[test]
557    fn local_status_move_sets_the_status_and_a_no_op_is_empty() {
558        let spec = local(&["todo", "doing", "done"]);
559        let cols = columns(&spec, &[]);
560        let card = issue(1, Some("todo"), false, &[]);
561        assert_eq!(
562            plan_move(&spec, &card, &cols[1]).unwrap().status.as_deref(),
563            Some("doing")
564        );
565        assert!(plan_move(&spec, &card, &cols[0]).unwrap().is_empty());
566    }
567
568    #[test]
569    fn a_provider_status_board_is_read_only() {
570        let spec = BoardSpec {
571            source: BoardSource::ProviderStatus,
572            declared: vec!["To Do".into(), "Done".into()],
573            labels: Vec::new(),
574        };
575        assert!(!spec.source.movable());
576        let cols = columns(&spec, &[]);
577        let err = plan_move(&spec, &issue(1, Some("To Do"), false, &[]), &cols[1]);
578        assert!(matches!(err, Err(Error::Unsupported(_))));
579    }
580
581    #[test]
582    fn apply_plan_updates_the_cached_issue() {
583        let mut card = issue(1, Some("todo"), false, &["bug"]);
584        apply_plan(
585            &mut card,
586            &MovePlan {
587                status: Some("done".into()),
588                labels: Some(vec![]),
589                closed: Some(true),
590                ..MovePlan::default()
591            },
592        );
593        assert_eq!(card.status_label.as_deref(), Some("done"));
594        assert!(card.labels.is_empty());
595        assert_eq!(card.state, IssueState::Closed);
596    }
597
598    #[test]
599    fn filters_combine_and_an_empty_filter_matches_everything() {
600        let mut a = issue(1, Some("todo"), false, &["bug"]);
601        a.assignees = vec!["Kai".into()];
602        a.milestone = Some("v0.1".into());
603        let b = issue(2, Some("todo"), false, &["ui"]);
604        assert!(BoardFilter::default().matches(&a));
605        assert!(BoardFilter::default().is_empty());
606        let f = BoardFilter {
607            assignee: Some("kai".into()),
608            label: Some("BUG".into()),
609            milestone: Some("v0.1".into()),
610            text: "issue 1".into(),
611        };
612        assert!(f.matches(&a));
613        assert!(!f.matches(&b));
614        let only_text = BoardFilter {
615            text: "#2".into(),
616            ..BoardFilter::default()
617        };
618        assert!(!only_text.matches(&a));
619        assert!(only_text.matches(&b));
620    }
621
622    #[test]
623    fn filter_choices_are_distinct_and_sorted() {
624        let mut a = issue(1, None, false, &["ui", "bug"]);
625        a.assignees = vec!["kai".into(), "Anna".into()];
626        a.milestone = Some("v2".into());
627        let mut b = issue(2, None, false, &["BUG"]);
628        b.assignees = vec!["anna".into()];
629        b.milestone = Some("v1".into());
630        let c = filter_choices(&[a, b]);
631        assert_eq!(c.assignees, ["Anna", "kai"]);
632        assert_eq!(c.labels, ["bug", "ui"]);
633        assert_eq!(c.milestones, ["v1", "v2"]);
634    }
635
636    #[test]
637    fn label_lists_are_parsed_and_proposed() {
638        assert_eq!(
639            parse_label_list(" status::todo , status::doing,,STATUS::todo"),
640            ["status::todo", "status::doing"]
641        );
642        let all: Vec<String> = ["bug", "status::todo", "Status: Review", "status/done"]
643            .iter()
644            .map(|s| s.to_string())
645            .collect();
646        assert_eq!(
647            status_like_labels(&all),
648            ["status::todo", "Status: Review", "status/done"]
649        );
650    }
651}