Skip to main content

lean_ctx_cloud/tasks/
fields.rs

1// SPDX-License-Identifier: Apache-2.0
2//! A task's priority and labels (C0 2.2 E47): the order of work on a board.
3//!
4//! - Priority is `high` or `normal` (absent on the wire means `normal`);
5//!   labels are at most 16 unique `[a-z0-9-]{1,32}`. A wrong value is
6//!   refused here, before any request.
7//! - A write is a `PATCH` at the task's `fields_version`. When another write
8//!   came first (`409 stale_base`) the task is read again and the write is
9//!   sent once more at the new version; a second conflict is shown.
10//! - Lists show `high` before `normal`, then by number.
11
12use std::path::Path;
13
14use lean_ctx_protocol::cloud::lease::CloudRight;
15use lean_ctx_protocol::cloud::tasks::{
16    TASK_FIELDS_SCHEMA, TaskAckV1, TaskFieldsRequestV1, TaskPriority, TaskSummaryV1,
17    validate_labels,
18};
19
20use super::{Link, connected};
21use crate::{CloudError, TaskRefusal};
22
23/// What a priority or labels write changes; `None` keeps the field.
24#[derive(Debug, Clone, Default, PartialEq, Eq)]
25pub struct FieldsChange {
26    pub priority: Option<TaskPriority>,
27    /// The whole new list (`Some(vec![])` clears it).
28    pub labels: Option<Vec<String>>,
29}
30
31impl FieldsChange {
32    /// Refuses a change that changes nothing or carries bad labels.
33    pub fn validate(&self) -> Result<(), CloudError> {
34        if self.priority.is_none() && self.labels.is_none() {
35            return Err(CloudError::Config("set a priority, labels or both".into()));
36        }
37        if let Some(labels) = &self.labels {
38            validate_labels(labels).map_err(|e| CloudError::Config(format!("labels: {e}")))?;
39        }
40        Ok(())
41    }
42}
43
44/// `high` or `normal`, exactly; anything else is refused with what is allowed.
45pub fn parse_priority(value: &str) -> Result<TaskPriority, CloudError> {
46    match value.trim() {
47        "high" => Ok(TaskPriority::High),
48        "normal" => Ok(TaskPriority::Normal),
49        other => Err(CloudError::Config(format!(
50            "priority is high or normal (got {:?})",
51            other.chars().take(32).collect::<String>()
52        ))),
53    }
54}
55
56/// The wire word of a priority (`normal` when absent).
57#[must_use]
58pub fn priority_word(priority: Option<TaskPriority>) -> &'static str {
59    match priority.unwrap_or_default() {
60        TaskPriority::High => "high",
61        TaskPriority::Normal => "normal",
62    }
63}
64
65/// Labels from `a,b,c` (spaces around a label are dropped, an empty value
66/// is no labels), validated as Cloud validates them.
67pub fn parse_labels(value: &str) -> Result<Vec<String>, CloudError> {
68    let labels: Vec<String> = value
69        .split(',')
70        .map(str::trim)
71        .filter(|label| !label.is_empty())
72        .map(str::to_owned)
73        .collect();
74    validate_labels(&labels).map_err(|e| CloudError::Config(format!("labels: {e}")))?;
75    Ok(labels)
76}
77
78/// The board order: `high` first, then by number.
79pub fn sort_by_priority(tasks: &mut [TaskSummaryV1]) {
80    tasks.sort_by_key(|task| (rank(task.priority), task.number));
81}
82
83/// `0` for `high`, `1` for `normal` (and absent).
84#[must_use]
85pub fn rank(priority: Option<TaskPriority>) -> u8 {
86    match priority.unwrap_or_default() {
87        TaskPriority::High => 0,
88        TaskPriority::Normal => 1,
89    }
90}
91
92/// Set task `number`'s priority and/or labels in the project's vault.
93pub fn set_fields(
94    project_root: &Path,
95    number: u64,
96    change: &FieldsChange,
97) -> Result<TaskAckV1, CloudError> {
98    change.validate()?;
99    let c = connected(project_root, CloudRight::TasksPropose)?;
100    set_fields_via(&c.link(), number, change)
101}
102
103pub(super) fn set_fields_via(
104    link: &Link<'_>,
105    number: u64,
106    change: &FieldsChange,
107) -> Result<TaskAckV1, CloudError> {
108    change.validate()?;
109    let send = || {
110        let base_version = link
111            .call(|api| api.show(number))?
112            .fields_version
113            .unwrap_or(0);
114        let request = TaskFieldsRequestV1 {
115            schema: TASK_FIELDS_SCHEMA.into(),
116            base_version,
117            priority: change.priority,
118            labels: change.labels.clone(),
119        };
120        link.call(|api| api.fields(number, &request))
121    };
122    match send() {
123        Err(CloudError::Task {
124            refusal: TaskRefusal::StaleBase,
125            ..
126        }) => send(),
127        other => other,
128    }
129}