kanorg 0.5.0

Simple Kanban management in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
extern crate custom_error;
extern crate serde;

use custom_error::custom_error;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;

pub type WorkflowResult<T> = Result<T, WorkflowError>;

custom_error! { pub WorkflowError
    WorkflowNotFound{workflow: String} = "Workflow `{workflow}` not found. It has to be one of: \
        backlog, todo, doing or done",
    TaskNotFoundInWorkflow{task: u16, workflow: String} = "Task `{task}`, was not found in the \
        workflow `{workflow}`",
    DeserializationError{ string: String, error: String } = "Error deserializing from string: {string}: \
        {error}"
}

/// Base config file translation.
///
/// In order to have a correct config file, you will need to provide the five fields: `backlog`,
/// `todo`, `doing`, `done` and `last_task`.
///
/// When serialising/deserialising to/from a config file with the [`toml`] package by default, the
/// following format will be found:
///
/// ```plain,no_run
/// backlog = [12, 11, 10, 9]
/// todo = [8]
/// doing = [7, 6]
/// done = [5, 4, 3, 2, 1]
/// last_task = 12
/// ```
///
/// The four workflows plus the last task must be found in order the deserialisation to work
/// properly.
#[derive(Deserialize, Serialize, Debug)]
pub struct Workflows {
    /// All the tasks that are in the bench, for future pick up.
    backlog: VecDeque<u16>,
    /// Current Sprint tasks.
    todo: VecDeque<u16>,
    /// The tasks that are currently under development.
    doing: VecDeque<u16>,
    /// Completed tasks. This will contain the last 10 completed. The other rest are in the archive.
    done: VecDeque<u16>,
    /// Last task ID.
    last_task: u16,
}

impl Workflows {
    /// Build a [`Workflows`] object from a config String.
    ///
    /// # Arguments:
    ///
    /// * `config_str` - the String containing the configuration.
    ///
    /// # Errors:
    ///
    /// * [`DeserializationError`] if the parsing goes wrong.
    ///
    /// [`DeserializationError`]: WorkflowError::DeserializationError
    pub fn from_str(config_str: &str) -> WorkflowResult<Self> {
        match toml::from_str(&config_str) {
            Ok(workflow) => Ok(workflow),
            Err(err) => Err(WorkflowError::DeserializationError {
                string: config_str.to_owned(),
                error: err.to_string(),
            }),
        }
    }
    /// Retrieves last task value.
    pub fn last_task(&self) -> u16 {
        self.last_task
    }
    /// Retrieves a workflow by its name.
    ///
    /// # Arguments:
    ///
    /// * `workflow_name` - name of the column we want to retrieve.
    ///
    /// # Errors:
    ///
    /// * [`WorkflowNotFound`] - if the given name does not exist as a workflow.
    ///
    /// [`WorkflowNotFound`]: WorkflowError::WorkflowNotFound
    pub fn workflow(&self, workflow_name: &str) -> WorkflowResult<&VecDeque<u16>> {
        match workflow_name {
            "backlog" => Ok(&self.backlog),
            "todo" => Ok(&self.todo),
            "doing" => Ok(&self.doing),
            "done" => Ok(&self.done),
            _ => Err(WorkflowError::WorkflowNotFound {
                workflow: workflow_name.to_owned(),
            }),
        }
    }
    /// Retrieves a workflow by its name in mutable mode.
    ///
    /// # Arguments:
    ///
    /// * `workflow_name` - name of the column we want to retrieve.
    ///
    /// # Errors:
    ///
    /// * [`WorkflowNotFound`] - if the given name does not exist as a workflow.
    ///
    /// [`WorkflowNotFound`]: WorkflowError::WorkflowNotFound
    pub fn workflow_mut(&mut self, workflow_name: &str) -> WorkflowResult<&mut VecDeque<u16>> {
        match workflow_name {
            "backlog" => Ok(&mut self.backlog),
            "todo" => Ok(&mut self.todo),
            "doing" => Ok(&mut self.doing),
            "done" => Ok(&mut self.done),
            _ => Err(WorkflowError::WorkflowNotFound {
                workflow: workflow_name.to_owned(),
            }),
        }
    }
    /// Obtains the workflow name where a task belongs.
    ///
    /// If the task does not exist in any of the workflows, `None` will be returned.
    ///
    /// # Arguments:
    ///
    /// * `task` - task ID to search for.
    pub fn find_workflow_name(&self, task: &u16) -> Option<&str> {
        if self.backlog.contains(task) {
            Some("backlog")
        } else if self.todo.contains(task) {
            Some("todo")
        } else if self.doing.contains(task) {
            Some("doing")
        } else if self.done.contains(task) {
            Some("done")
        } else {
            None
        }
    }
    /// Obtains the max number of tasks that are in any of the `todo`, `doing` or `done` workflows.
    pub fn main_max_len(&self) -> usize {
        match vec![self.todo.len(), self.doing.len(), self.done.len()]
            .iter()
            .max()
        {
            None => 0,
            Some(max_len) => max_len.clone(),
        }
    }
    /// Removes a task from a chosen workflow.
    ///
    /// # Arguments:
    ///
    /// * `task` - the ID of the task to delete,
    ///
    /// * `workflow_name` - the name of the workflow we want to remove `task`.
    ///
    /// # Errors:
    ///
    /// * [`WorkflowNotFound`] if the wofklow does not exist.
    ///
    /// * [`TaskNotFoundInWorkflow`] if the `task` couldn't be found in the workflow.
    ///
    /// * Panics if the found position to remove in the workflow is out of bounds.
    ///
    /// [`WorkflowNotFound`]: WorkflowError::TaskNotFoundInWorkflow
    /// [`TaskNotFoundInWorkflow`]: WorkflowError::WorkflowNotFound
    pub fn remove_task(&mut self, task: u16, workflow_name: &str) -> WorkflowResult<()> {
        match self.workflow_mut(workflow_name) {
            Ok(workflow) => match workflow.iter().position(|t| t == &task) {
                Some(pos) => {
                    workflow.remove(pos).expect(&format!(
                        "The index `{}` is out of bounds from: `{:?}.",
                        pos, workflow,
                    ));
                    Ok(())
                }
                None => {
                    return Err(WorkflowError::TaskNotFoundInWorkflow {
                        task: task,
                        workflow: workflow_name.to_owned(),
                    })
                }
            },
            Err(_) => {
                return Err(WorkflowError::WorkflowNotFound {
                    workflow: workflow_name.to_owned(),
                })
            }
        }
    }
    /// Adds a new task to the chosen workflow.
    ///
    /// # Arguments:
    ///
    /// * `task` - the selected task.
    ///
    /// * `workflow_name` - the workflow name to add the `task` to.
    ///
    /// # Errors:
    ///
    /// * [`WorkflowNotFound`] if the workflow does not exist.
    ///
    /// [`WorkflowNotFound`]: WorkflowError::WorkflowNotFound
    fn add_task(&mut self, task: u16, workflow_name: &str) -> WorkflowResult<Option<u16>> {
        match workflow_name {
            "done" => {
                self.done.push_front(task);
                if self.done.len() > 5 {
                    return Ok(self.done.pop_back());
                }
            }
            "backlog" | "todo" | "doing" => {
                self.workflow_mut(workflow_name).unwrap().push_front(task)
            }
            _ => {
                return Err(WorkflowError::WorkflowNotFound {
                    workflow: workflow_name.to_owned(),
                })
            }
        }
        Ok(None)
    }
    /// Adds a task to the top of a workflow
    ///
    /// If the selected workflow is `done`, as it has a limit of *5* `task`s, the oldest one will be
    /// removed from the workflow.
    ///
    /// # Arguments:
    ///
    /// * `workflow_name` - name of the column we want to add a `task` to.
    ///
    /// # Errors:
    ///
    /// * [`WorkflowNotFound`] if the workflow does not exist.
    ///
    /// [`WorkflowNotFound`]: WorkflowError::WorkflowNotFound
    pub fn add_new_task(&mut self, workflow_name: &str) -> WorkflowResult<Option<u16>> {
        self.last_task += 1;
        self.add_task(self.last_task, workflow_name)
    }
    /// Moves a task from some workflow to other.
    ///
    /// # Arguments:
    ///
    /// * `task` - identificator of the task we want to move.
    ///
    /// * `from` - name of the origin workflow.
    ///
    /// * `to` - name of the target workflow.
    ///
    /// # Errors:
    ///
    /// * If there is a problem removing the `task`.
    ///
    /// * If there is a problem adding the new `task`.
    pub fn move_task(&mut self, task: u16, from: &str, to: &str) -> WorkflowResult<Option<u16>> {
        self.remove_task(task, from)?;
        self.add_task(task, to)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn last_task() {
        let w: Workflows = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };
        assert_eq!(w.last_task(), 12u16);
    }

    #[test]
    fn workflow() {
        let w: Workflows = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        assert_eq!(
            w.workflow("backlog").unwrap().as_slices().0,
            &[12u16, 11u16, 10u16, 9u16][..]
        );

        assert!(w.workflow("haha greetings").is_err());
    }
    #[test]
    fn workflow_mut() {
        let mut w: Workflows = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        let backlog = w.workflow_mut("backlog").unwrap();

        assert_eq!(backlog.as_slices().0, &[12u16, 11u16, 10u16, 9u16][..]);

        backlog.push_back(1000u16);

        assert_eq!(
            backlog.as_slices().0,
            &[12u16, 11u16, 10u16, 9u16, 1000u16][..]
        );

        assert!(w.workflow_mut("haha greetings").is_err());
    }
    #[test]
    fn find_workflow_name() {
        let w = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        assert_eq!(w.find_workflow_name(&4u16), Some("done"));
        assert_eq!(w.find_workflow_name(&200u16), None);
    }

    #[test]
    fn main_max_len() {
        let w = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };
        assert_eq!(w.main_max_len(), 5);

        let w = Workflows {
            backlog: VecDeque::new(),
            todo: VecDeque::new(),
            doing: VecDeque::new(),
            done: VecDeque::new(),
            last_task: 0,
        };
        assert_eq!(w.main_max_len(), 0);
    }

    #[test]
    fn remove_task() {
        let mut w = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        // Everything ok
        assert!(w.remove_task(4, "done").is_ok());

        assert!(!w.done.contains(&4u16));

        // Workflow does not exist
        assert!(w.remove_task(4, "none").is_err());

        // Task is not contained in workflow
        assert!(w.remove_task(2000, "backlog").is_err());
    }
    #[test]
    fn add_task() {
        let mut w = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        assert!(w.add_task(1000, "doing").is_ok());

        assert!(w.doing.contains(&1000u16));
    }

    #[test]
    fn add_new_task() {
        let mut w = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        assert!(!w.done.contains(&13u16));

        assert!(w.add_new_task("done").is_ok());

        assert!(w.done.contains(&13u16));
        assert_eq!(w.last_task, 13u16);
    }

    #[test]
    fn move_task() {
        let mut w = Workflows {
            backlog: vec![12, 11, 10, 9].into_iter().collect(),
            todo: vec![8].into_iter().collect(),
            doing: vec![7, 6].into_iter().collect(),
            done: vec![5, 4, 3, 2, 1].into_iter().collect(),
            last_task: 12,
        };

        assert!(w.move_task(10u16, "backlog", "todo").is_ok());

        assert!(!w.backlog.contains(&10u16));
        assert!(w.todo.contains(&10u16));

        assert!(w.move_task(1000u16, "todo", "done").is_err());
    }
}