lean_ctx_cloud/tasks/
fields.rs1use 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
25pub struct FieldsChange {
26 pub priority: Option<TaskPriority>,
27 pub labels: Option<Vec<String>>,
29}
30
31impl FieldsChange {
32 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
44pub 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#[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
65pub 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
78pub fn sort_by_priority(tasks: &mut [TaskSummaryV1]) {
80 tasks.sort_by_key(|task| (rank(task.priority), task.number));
81}
82
83#[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
92pub 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}