summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: e5db651edaacc13d0ae354c451e5c0d55edb8913 (plain)
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Model project roadmaps and step dependencies
//!
//! This crate models a roadmap as steps, which may depend on each
//! other, and a directed acyclic graph (DAG) of said steps, which
//! leads to the end goal. There is no support for due dates,
//! estimates, or other such project management features. These roadmaps only
//! care about what steps need to be take, in what order, to reach the
//! goal.
//!
//! # Example
//! ```
//! # use roadmap::Step;
//! # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
//! let mut r = roadmap::Roadmap::from_yaml("
//! endgoal:
//!   label: The end goal
//!   depends:
//!   - first
//! first:
//!   label: The first step
//! ").unwrap();
//!
//! let n = r.step_names();
//! assert_eq!(n.len(), 2);
//! assert!(n.contains(&"first"));
//! assert!(n.contains(&"endgoal"));
//!
//! r.set_missing_statuses();
//! println!("{}", r.as_dot(30).unwrap());
//!
//! # Ok(())
//! # }
//! ```

use serde_yaml;
use serde_yaml::Value;
use std::collections::HashMap;
use std::error::Error;
use textwrap::fill;

/// A step in a roadmap.
#[derive(Clone, Debug, PartialEq)]
pub struct Step {
    name: String,
    status: String,
    label: String,
    depends: Vec<String>,
}

impl Step {
    /// Create a new step with a name and a label.
    pub fn new(name: &str, label: &str) -> Step {
        Step {
            name: name.to_string(),
            status: "".to_string(),
            label: label.to_string(),
            depends: vec![],
        }
    }

    /// Return the name of a step.
    pub fn name<'a>(&'a self) -> &'a str {
        &self.name
    }

    /// Return the label of a step.
    pub fn label<'a>(&'a self) -> &'a str {
        &self.label
    }

    /// Return the status of a step.
    pub fn status<'a>(&'a self) -> &'a str {
        &self.status
    }

    /// Set the status of a step.
    pub fn set_status(&mut self, status: &str) {
        self.status = String::from(status);
    }

    /// Return vector of names of dependencies for a step.
    pub fn dependencies(&self) -> impl Iterator<Item = &String> {
        self.depends.iter()
    }

    /// Add the name of a dependency to step.
    pub fn add_dependency(&mut self, name: &str) {
        self.depends.push(String::from(name));
    }

    /// Does this step depend on given other step?
    pub fn depends_on(&self, other_name: &str) -> bool {
        self.depends.iter().any(|depname| depname == other_name)
    }
}

/// Result type for roadmap parsing.
type ParseResult<T> = Result<T, String>;

/// All the steps to get to the end goal.
pub struct Roadmap {
    steps: Vec<Step>,
}

impl Roadmap {
    /// Create a new, empty roadmap.
    pub fn new() -> Roadmap {
        Roadmap { steps: vec![] }
    }

    /// Create a new roadmap from a YAML representation.
    pub fn from_yaml(yaml: &str) -> Result<Roadmap, Box<dyn Error>> {
        let mut roadmap = Roadmap::new();
        let map: HashMap<String, serde_yaml::Value> = serde_yaml::from_str(yaml)?;

        for (name, value) in map {
            let step = Roadmap::step_from_value(&name, &value)?;
            roadmap.add_step(&step)?;
        }

        roadmap.validate()?;
        Ok(roadmap)
    }

    // Convert a Value into a Step, if possible.
    fn step_from_value(name: &str, value: &Value) -> Result<Step, &'static str> {
        match value {
            Value::Mapping(_) => {
                let label = Roadmap::parse_label(&value);
                let mut step = Step::new(name, label);

                let status = Roadmap::parse_status(&value);
                step.set_status(status);

                for depname in Roadmap::parse_depends(&value).iter() {
                    step.add_dependency(depname);
                }

                Ok(step)
            }
            _ => Err("step is not a mapping"),
        }
    }

    // Get a sequence of depenencies.
    fn parse_depends(map: &Value) -> Vec<&str> {
        let key_name = "depends";
        let key = Value::String(key_name.to_string());
        let mut depends: Vec<&str> = vec![];

        if let Some(Value::Sequence(deps)) = map.get(&key) {
            for depname in deps.iter() {
                if let Value::String(depname) = depname {
                    depends.push(depname);
                }
            }
        }

        depends
    }

    // Get label string from a Mapping element, or empty string.
    fn parse_label<'a>(map: &'a Value) -> &'a str {
        Roadmap::parse_string("label", map)
    }

    // Get status string from a Mapping element, or empty string.
    fn parse_status<'a>(map: &'a Value) -> &'a str {
        Roadmap::parse_string("status", map)
    }

    // Get string value from a Mapping element, or empty string.
    fn parse_string<'a>(key_name: &str, map: &'a Value) -> &'a str {
        let key = Value::String(key_name.to_string());
        match map.get(&key) {
            Some(Value::String(s)) => s,
            _ => "",
        }
    }

    // Validate that the parsed, constructed roadmap is valid.
    fn validate(&self) -> ParseResult<()> {
        // Does every step has an acceptable status?
        for step in self.steps.iter() {
            let status = step.status();
            match status {
                "" | "goal" | "ready" | "finished" | "next" | "blocked" => (),
                _ => {
                    return Err(format!(
                        "step {:?} status {:?} is not allowed",
                        step.name(),
                        status
                    ))
                }
            }
        }

        // Is there exactly one goal?
        if self.count_goals() != 1 {
            return Err(format!("must have exactly one goal for roadmap"));
        }

        // Does every dependency exist?
        for step in self.steps.iter() {
            for depname in step.dependencies() {
                match self.get_step(depname) {
                    None => {
                        return Err(format!(
                            "step {} depends on missing {}",
                            step.name(),
                            depname
                        ))
                    }
                    Some(_) => (),
                }
            }
        }

        Ok(())
    }

    // Count number of steps that nothing depends on.
    fn count_goals(&self) -> usize {
        self.steps
            .iter()
            .map(|step| self.is_goal(step))
            .filter(|b| *b)
            .count()
    }

    /// Return list of step names.
    pub fn step_names<'a>(&'a self) -> Vec<&'a str> {
        let mut names = vec![];
        for step in self.steps.iter() {
            names.push(step.name());
        }
        names
    }

    /// Get a step, given its name.
    pub fn get_step<'a>(&'a self, name: &str) -> Option<&'a Step> {
        for step in self.steps.iter() {
            if step.name() == name {
                return Some(step);
            }
        }
        None
    }

    /// Add a step to the roadmap. This may fail, if there's a step
    /// with that name already.
    pub fn add_step(&mut self, step: &Step) -> Result<(), Box<dyn std::error::Error>> {
        self.steps.push(step.clone());
        Ok(())
    }

    // Get iterator over refs to steps.
    pub fn iter(&self) -> impl Iterator<Item = &Step> {
        self.steps.iter()
    }

    // Get iterator over mut refs to steps.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Step> {
        self.steps.iter_mut()
    }

    /// Compute status of any step for which it has not been specified
    /// in the input.
    pub fn set_missing_statuses(&mut self) {
        let new_steps: Vec<Step> = self
            .steps
            .iter()
            .map(|step| {
                let mut step = step.clone();
                if self.is_unset(&step) {
                    if self.is_goal(&step) {
                        step.set_status("goal");
                    } else if self.is_blocked(&step) {
                        step.set_status("blocked");
                    } else if self.is_ready(&step) {
                        step.set_status("ready");
                    }
                }
                step
            })
            .collect();

        if self.steps != new_steps {
            self.steps = new_steps;
            self.set_missing_statuses();
        }
    }

    // Is status unset?
    fn is_unset(&self, step: &Step) -> bool {
        step.status() == ""
    }

    // Should unset status be ready? In other words, if there are any
    // dependencies, they are all finished.
    fn is_ready(&self, step: &Step) -> bool {
        self.dep_statuses(step)
            .iter()
            .all(|status| status == &"finished")
    }

    // Should unset status be blocked? In other words, if there are
    // any dependencies, that aren't finished.
    fn is_blocked(&self, step: &Step) -> bool {
        self.dep_statuses(step)
            .iter()
            .any(|status| status != &"finished")
    }

    // Return vector of all statuses of all dependencies
    fn dep_statuses<'a>(&'a self, step: &Step) -> Vec<&'a str> {
        step.dependencies()
            .map(|depname| {
                if let Some(step) = self.get_step(depname) {
                    step.status()
                } else {
                    &""
                }
            })
            .collect()
    }

    // Should unset status be goal? In other words, does any other
    // step depend on this one?
    fn is_goal(&self, step: &Step) -> bool {
        let has_parent = self.steps.iter().any(|other| other.depends_on(step.name()));
        !has_parent
    }

    /// Get a Graphviz dot language representation of a roadmap. This
    /// is the textual representation, and the caller needs to use the
    /// Graphviz dot(1) tool to create an image from it.
    pub fn as_dot(self, label_width: usize) -> Result<String, Box<dyn std::error::Error>> {
        let labels = self.steps.iter().map(|step| {
            format!(
                "{} [label=\"{}\" style=filled fillcolor=\"{}\" shape=\"{}\"];\n",
                step.name(),
                fill(&step.label(), label_width).replace("\n", "\\n"),
                Roadmap::get_status_color(step),
                Roadmap::get_status_shape(step),
            )
        });

        let mut dot = String::new();
        dot.push_str("digraph \"roadmap\" {\n");
        for line in labels {
            dot.push_str(&line);
        }

        for step in self.iter() {
            for dep in step.dependencies() {
                let line = format!("{} -> {};\n", dep, step.name());
                dot.push_str(&line);
            }
        }

        dot.push_str("}\n");

        Ok(dot)
    }

    fn get_status_color(step: &Step) -> &str {
        match step.status() {
            "blocked" => "#f4bada",
            "finished" => "#eeeeee",
            "ready" => "#ffffff",
            "next" => "#0cc00",
            "goal" => "#00eeee",
            _ => "unknownstatus",
        }
    }

    fn get_status_shape(step: &Step) -> &str {
        match step.status() {
            "blocked" => "rectangle",
            "finished" => "circle",
            "ready" => "ellipse",
            "next" => "ellipse",
            "goal" => "diamond",
            _ => "unknownshape",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Roadmap, Step};

    #[test]
    fn new_step() {
        let step = Step::new("myname", "my label");
        assert_eq!(step.name(), "myname");
        assert_eq!(step.status(), "");
        assert_eq!(step.label(), "my label");
        assert_eq!(step.dependencies().count(), 0);
    }

    #[test]
    fn set_status() {
        let mut step = Step::new("myname", "my label");
        step.set_status("next");
        assert_eq!(step.status(), "next");
    }

    #[test]
    fn add_step_dependency() {
        let mut second = Step::new("second", "the second step");
        second.add_dependency("first");
        let deps: Vec<&String> = second.dependencies().collect();
        assert_eq!(deps, vec!["first"]);
    }

    #[test]
    fn new_roadmap() {
        let roadmap = Roadmap::new();
        assert_eq!(roadmap.step_names().len(), 0);
    }

    #[test]
    fn add_step_to_roadmap() {
        let mut roadmap = Roadmap::new();
        let first = Step::new("first", "the first step");
        roadmap.add_step(&first).unwrap();
        assert_eq!(roadmap.step_names().len(), 1);
        assert_eq!(roadmap.step_names(), vec!["first"]);
    }

    #[test]
    fn get_step_from_roadmap() {
        let mut roadmap = Roadmap::new();
        let first = Step::new("first", "the first step");
        roadmap.add_step(&first).unwrap();
        let gotit = roadmap.get_step("first").unwrap();
        assert_eq!(gotit.name(), "first");
        assert_eq!(gotit.label(), "the first step");
    }

    #[test]
    fn parse_yaml_is_list() {
        let r = Roadmap::from_yaml("[]");
        match r {
            Ok(_) => panic!("expected a parse error"),
            _ => (),
        }
    }

    #[test]
    fn parse_yaml_is_empty() {
        let r = Roadmap::from_yaml("");
        match r {
            Ok(_) => panic!("expected a parse error"),
            _ => (),
        }
    }

    #[test]
    fn parse_yaml_map_entries_not_maps() {
        let r = Roadmap::from_yaml("foo: []");
        match r {
            Ok(_) => panic!("expected a parse error"),
            _ => (),
        }
    }

    #[test]
    fn parse_yaml_unknown_dep() {
        let r = Roadmap::from_yaml("foo: {depends: [bar]}");
        match r {
            Ok(_) => panic!("expected a parse error"),
            _ => (),
        }
    }

    #[test]
    fn parse_yaml_unknown_status() {
        let r = Roadmap::from_yaml(r#"foo: {status: "bar"}"#);
        match r {
            Ok(_) => panic!("expected a parse error"),
            _ => (),
        }
    }

    #[test]
    fn set_missing_goal_status() {
        let mut r = Roadmap::from_yaml(
            "
goal:
  depends:
  - finished
  - blocked

finished:
  status: finished

ready:
  depends:
  - finished

next:
  status: next

blocked:
  depends:
  - ready
  - next
",
        )
        .unwrap();
        r.set_missing_statuses();
        assert_eq!(r.get_step("goal").unwrap().status(), "goal");
        assert_eq!(r.get_step("finished").unwrap().status(), "finished");
        assert_eq!(r.get_step("ready").unwrap().status(), "ready");
        assert_eq!(r.get_step("next").unwrap().status(), "next");
        assert_eq!(r.get_step("blocked").unwrap().status(), "blocked");
    }

    #[test]
    fn empty_dot() {
        let roadmap = Roadmap::new();
        assert_eq!(
            roadmap.as_dot(999).unwrap(),
            "digraph \"roadmap\" {
}
"
        );
    }

    #[test]
    fn simple_dot() {
        let mut roadmap = Roadmap::new();
        let mut first = Step::new("first", "");
        first.set_status("ready");
        let mut second = Step::new("second", "");
        second.add_dependency("first");
        second.set_status("goal");
        roadmap.add_step(&first).unwrap();
        roadmap.add_step(&second).unwrap();
        assert_eq!(
            roadmap.as_dot(999).unwrap(),
            "digraph \"roadmap\" {
first [label=\"\" style=filled fillcolor=\"#ffffff\" shape=\"ellipse\"];
second [label=\"\" style=filled fillcolor=\"#00eeee\" shape=\"diamond\"];
first -> second;
}
"
        );
    }

    #[test]
    fn from_empty_yaml() {
        let roadmap = Roadmap::from_yaml("{}");
        match roadmap {
            Ok(_) => panic!("expected error for empty dict"),
            _ => (),
        }
    }

    #[test]
    fn from_nonempty_yaml() {
        let roadmap = Roadmap::from_yaml(
            "
first:
  label: the first step
second:
  label: the second step
  depends:
  - first
",
        )
        .unwrap();

        let names = roadmap.step_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"first"));
        assert!(names.contains(&"second"));

        let first = roadmap.get_step("first").unwrap();
        assert_eq!(first.name(), "first");
        assert_eq!(first.label(), "the first step");
        let deps: Vec<&String> = first.dependencies().collect();
        assert_eq!(deps.len(), 0);

        let second = roadmap.get_step("second").unwrap();
        assert_eq!(second.name(), "second");
        assert_eq!(second.label(), "the second step");
        let deps: Vec<&String> = second.dependencies().collect();
        assert_eq!(deps, vec!["first"]);
    }
}