summaryrefslogtreecommitdiff
path: root/src/map.rs
blob: 0184fc1aa8776a83f4d3bade36603add005e9449 (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
use textwrap::fill;

pub use crate::from_yaml;
pub use crate::Status;
pub use crate::Step;


/// Error in Roadmap, from parsing or otherwise.
pub type RoadmapError<T> = Result<T, String>;


/// Represent a full project roadmap.
///
/// This stores all the steps needed to reach the end goal. See the
/// crate leve documentation for an example.
#[derive(Clone,Debug)]
pub struct Roadmap {
    steps: Vec<Step>,
}

impl Roadmap {
    /// Create a new, empty roadmap.
    ///
    /// You probably want the `from_yaml` function instead.
    pub fn new() -> Roadmap {
        Roadmap { steps: vec![] }
    }

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

    /// Iterate over step names.
    pub fn step_names(&self) -> impl Iterator<Item=&str> {
        self.steps.iter().map(|step| step.name())
    }

    /// Get a step, given its name.
    pub fn get_step(&self, name: &str) -> Option<&Step> {
        self.steps.iter().filter(|step| step.name() == name).next()
    }

    /// Add a step to the roadmap.
    pub fn add_step(&mut self, step: Step) {
        self.steps.push(step);
    }

    // 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 step.status() == Status::Unknown {
                    if self.is_goal(&step) {
                        step.set_status(Status::Goal);
                    } else if self.is_blocked(&step) {
                        step.set_status(Status::Blocked);
                    } else if self.is_ready(&step) {
                        step.set_status(Status::Ready);
                    }
                }
                step
            })
            .collect();

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

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

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

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

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


    // Validate that the parsed, constructed roadmap is valid.
    pub fn validate(&self) -> RoadmapError<()> {
        // Is there exactly one goal?
        match self.count_goals() {
            0 => return Err(format!("the roadmap doesn't have a goal")),
            1 => (),
            _ => return Err(format!("must have exactly one goal for roadmap")),
        }

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

        Ok(())
    }

    /// 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 format_as_dot(&self, label_width: usize) -> Result<String, Box<dyn std::error::Error>> {
        self.validate()?;

        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() {
            Status::Blocked => "#f4bada",
            Status::Finished => "#eeeeee",
            Status::Ready => "#ffffff",
            Status::Next => "#0cc00",
            Status::Goal => "#00eeee",
            Status::Unknown => "#ff0000",
        }
    }

    fn get_status_shape(step: &Step) -> &str {
        match step.status() {
            Status::Blocked => "rectangle",
            Status::Finished => "circle",
            Status::Ready => "ellipse",
            Status::Next => "ellipse",
            Status::Goal => "diamond",
            Status::Unknown => "house",
        }
    }
}

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

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

    #[test]
    fn add_step_to_roadmap() {
        let mut roadmap = Roadmap::new();
        let first = Step::new("first", "the first step");
        roadmap.add_step(first);
        let names: Vec<&str> = roadmap.step_names().collect();
        assert_eq!(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);
        let gotit = roadmap.get_step("first").unwrap();
        assert_eq!(gotit.name(), "first");
        assert_eq!(gotit.label(), "the first step");
    }

    #[test]
    fn set_missing_goal_status() {
        let mut r = 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(), Status::Goal);
        assert_eq!(r.get_step("finished").unwrap().status(), Status::Finished);
        assert_eq!(r.get_step("ready").unwrap().status(), Status::Ready);
        assert_eq!(r.get_step("next").unwrap().status(), Status::Next);
        assert_eq!(r.get_step("blocked").unwrap().status(), Status::Blocked);
    }

    #[test]
    fn empty_dot() {
        let roadmap = Roadmap::new();
        match roadmap.format_as_dot(999) {
            Err(_) => (),
            _ => panic!("expected error for empty roadmap"),
        }
    }

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