otarustlings 1.0.0

otafablab rustlings
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
use crate::menu::Status;
use crate::utils::list_exercises;
use chrono::{DateTime, Utc};
use itertools::{GroupBy, Itertools};
use serde::{Deserialize, Serialize};
use std::collections::{btree_set, BTreeMap, BTreeSet};
use std::default::Default;
use std::fs::{read_to_string, File};
use std::io::{self, ErrorKind, Write};
use std::mem::swap;
use std::path::{Path, PathBuf};
use tracing::{debug, trace};

/// `Exercise` represents an exercise.
///
/// TODO Fix implicit equality and ordering of exercises
#[derive(Debug, Clone)]
pub struct Exercise {
    pub path: PathBuf,
    pub exercise_state: ExerciseState,
}

impl PartialEq for Exercise {
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path
    }
}

impl Eq for Exercise {}

impl PartialOrd for Exercise {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.path.partial_cmp(&other.path)
    }
}

impl Ord for Exercise {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.path.cmp(&other.path)
    }
}

impl From<(PathBuf, ExerciseState)> for Exercise {
    fn from(from: (PathBuf, ExerciseState)) -> Self {
        Self {
            path: from.0,
            exercise_state: from.1,
        }
    }
}

impl Exercise {
    pub fn file_name(&self) -> &str {
        self.path.file_name().unwrap().to_str().unwrap()
    }

    pub fn folder_name(&self) -> &str {
        self.path
            .parent()
            .unwrap()
            .file_name()
            .unwrap()
            .to_str()
            .unwrap()
    }

    pub fn status(&self) -> Status {
        match (self.exercise_state.started, self.exercise_state.completed) {
            (_, Some(_)) => Status::Completed,
            (Some(_), None) => Status::Started,
            (_, _) => Status::NotStarted,
        }
    }
}

#[derive(
    Copy, Clone, Serialize, Deserialize, Hash, Default, Debug, PartialEq, Eq, PartialOrd, Ord,
)]
pub struct ExerciseState {
    pub started: Option<DateTime<Utc>>,
    pub completed: Option<DateTime<Utc>>,
}

impl ExerciseState {
    pub fn start_exercise(&mut self) -> DateTime<Utc> {
        if let Some(date) = self.started {
            date
        } else {
            let now = Utc::now();
            self.started = Some(now);
            now
        }
    }

    pub fn complete_exercise(&mut self) -> DateTime<Utc> {
        if let Some(date) = self.completed {
            date
        } else {
            let now = Utc::now();
            self.completed = Some(now);
            now
        }
    }
}

/// State of the exercises.
#[derive(Debug, Default, Clone)]
pub struct State(pub BTreeSet<Exercise>);

impl From<BTreeMap<PathBuf, ExerciseState>> for State {
    fn from(map: BTreeMap<PathBuf, ExerciseState>) -> Self {
        Self(map.into_iter().map(Exercise::from).collect())
    }
}

impl State {
    /// Creates a new empty state.
    pub fn new() -> Self {
        Self::default()
    }

    /// Gets the exercise
    pub fn get(&self, path: impl AsRef<Path>) -> Option<&Exercise> {
        self.0.iter().find(|e| e.path == path.as_ref())
    }

    /// Collects all exercises under `path` as their own default [`ExerciseState`].
    ///
    /// If the folder at `path` is empty, the state will be empty too. TODO Should error.
    pub fn scan(path: impl AsRef<Path>) -> Self {
        debug!("scanning {:?}", path.as_ref());
        let exercises = list_exercises(path)
            .map(|path| (path, ExerciseState::default()).into())
            .collect();
        Self(exercises)
    }

    /// Tries to deserialize `exercises/state.toml` as [`Self`].
    ///
    /// # Errors
    ///
    /// Returns an [`io::Error`] if reading the state file fails or if
    /// the file contains invalid toml.
    pub fn open(path: impl AsRef<Path>) -> io::Result<Self> {
        debug!("opening state file in {:?}", path.as_ref());
        let map: BTreeMap<PathBuf, ExerciseState> =
            toml::from_str(&read_to_string(path.as_ref().join("state.toml"))?)?;
        Ok(map.into())
    }

    /// Reads `exercises/state.toml` if it exists and scans the.
    /// `exercises` directory extending the state from.
    /// `state.toml`. This is the logical option in most cases.
    ///
    /// # Errors
    ///
    /// Same errors as [`Self::open`].
    pub fn scan_open_default(path: impl AsRef<Path>) -> io::Result<Self> {
        let path = path.as_ref();
        let mut state = match Self::open(path) {
            Err(e) => {
                if e.kind() == ErrorKind::NotFound {
                    debug!("no previous state file found");
                    Self::default()
                } else {
                    return Err(e);
                }
            }
            Ok(state) => {
                debug!("previous state file found");
                state
            }
        };
        let other = Self::scan(path);
        trace!("{:?}", state);
        trace!("{:?}", other);
        state.extend(other);
        Ok(state)
    }

    /// Saves the state to `exercises/state.toml`.
    ///
    /// # Errors
    ///
    /// Returns an [`io::Error`] if creating or writing to the state
    /// file fails.
    pub fn save(&self) -> io::Result<()> {
        let mut file = File::create("exercises/state.toml")?;
        let mut map = BTreeMap::new();

        for ex in &self.0 {
            map.insert(&ex.path, &ex.exercise_state);
        }
        debug!("writing state to exercises/state.toml");
        file.write_all(
            toml::to_string(&map)
                .expect("state to be serializable")
                .as_bytes(),
        )?;
        Ok(())
    }

    /// Joins two states favoring self's exercises. Useful for adding
    /// missing exercises with:
    ///
    /// ```
    /// # use otarustlings::state::{State, Exercise, ExerciseState};
    /// let mut left = State::new();
    /// # left.0.insert(Exercise { path: "old_week1/ex1.rs".into(), exercise_state: ExerciseState::default() });
    /// left.extend(State::scan("exercises"));
    /// ```
    ///
    /// # Example
    ///
    /// ```
    /// # use chrono::Utc;
    /// # use otarustlings::state::{State, Exercise, ExerciseState};
    /// let started = ExerciseState {
    ///     started: Some(Utc::now()),
    ///     ..ExerciseState::default()
    /// };
    /// // left:
    /// //   week1
    /// //     ex1.rs (started)
    /// //   week2
    /// //     ex1.rs (default)
    /// //
    /// // right:
    /// //   week1
    /// //     ex1.rs (default)
    /// //   week3
    /// //     ex1.rs (default)
    ///
    /// let mut left = State::new();
    /// left.0.insert(Exercise { path: "week1/ex1.rs".into(), exercise_state: started.clone() });
    /// left.0.insert(Exercise { path: "week2/ex1.rs".into(), exercise_state: ExerciseState::default() });
    ///
    /// let mut right = State::new();
    /// right.0.insert(Exercise { path: "week1/ex1.rs".into(), exercise_state: ExerciseState::default() });
    /// right.0.insert(Exercise { path: "week3/ex1.rs".into(), exercise_state: ExerciseState::default() });
    ///
    /// // Extending `left` with `right` should give
    /// // left:
    /// //   week1
    /// //     ex1.rs (started)
    /// //   week2
    /// //     ex1.rs (default)
    /// //   week3
    /// //     ex1.rs (default)
    ///
    /// left.extend(right);
    ///
    /// assert_eq!(left.0.iter().nth(0).unwrap().exercise_state, started.clone());
    /// ```
    pub fn extend(&mut self, mut other: Self) {
        swap(&mut self.0, &mut other.0); // swapping sets inverts the priority
        self.0.append(&mut other.0);
    }

    /// Returns an iterator yielding [`Exercise`]s.
    pub fn iter(&self) -> impl Iterator<Item = &'_ Exercise> {
        self.0.iter()
    }

    /// Returns an iterator yielding a tuple of folder and the exercises within.
    pub fn group_by_folder<'s>(
        &'s self,
    ) -> GroupBy<&'_ str, btree_set::Iter<'_, Exercise>, impl FnMut(&'_ &'s Exercise) -> &'s str>
    {
        self.0.iter().group_by(|t| t.folder_name())
    }

    /// Returns the next exercise of the week or `None` if the exercise is the last one in the folder.
    ///
    /// # Examples
    ///
    /// Get the next exercise `ex2` when `ex1` comes before `ex2` in `week1`:
    ///
    /// ```
    /// # use chrono::Utc;
    /// # use otarustlings::state::{State, Exercise, ExerciseState};
    /// let started = ExerciseState {
    ///     started: Some(Utc::now()),
    ///     ..ExerciseState::default()
    /// };
    ///
    /// let ex1 = Exercise { path: "week1/ex1.rs".into(), exercise_state: started.clone() };
    /// let ex2 = Exercise { path: "week1/ex2.rs".into(), exercise_state: ExerciseState::default() };
    /// let mut state = State::new();
    /// state.0.insert(ex1.clone());
    /// state.0.insert(ex2.clone());
    ///
    /// assert_eq!(state.get_next_exercise_of_week(&ex1), Some(&ex2));
    /// ```
    ///
    /// Should return `None` if the exercise is last exercise of the week.
    ///
    /// ```
    /// # use chrono::Utc;
    /// # use otarustlings::state::{State, Exercise, ExerciseState};
    /// let started = ExerciseState {
    ///     started: Some(Utc::now()),
    ///     ..ExerciseState::default()
    /// };
    ///
    /// let w1ex1 = Exercise { path: "week1/ex1.rs".into(), exercise_state: started.clone() };
    /// let w2ex1 = Exercise { path: "week2/ex1.rs".into(), exercise_state: ExerciseState::default() };
    /// let mut state = State::new();
    /// state.0.insert(w1ex1.clone());
    /// state.0.insert(w2ex1.clone());
    ///
    /// assert_eq!(state.get_next_exercise_of_week(&w1ex1), None);
    /// ```
    pub fn get_next_exercise_of_week(&self, exercise: &Exercise) -> Option<&Exercise> {
        let mut exercises = self.0.iter();
        exercises.find(|&x| x == exercise);
        // Return None if the next exercise does not exist
        let not_last_exercise = exercises.next()?;
        // Return None if the next exercise is not in the same folder
        if not_last_exercise.folder_name() == exercise.folder_name() {
            Some(not_last_exercise)
        } else {
            None
        }
    }

    pub fn next_exercise(&self, exercise: &Exercise) -> &Exercise {
        let mut exercises = self.0.iter();

        exercises.find(|&x| x == exercise);
        exercises
            .next()
            .unwrap_or_else(|| self.0.iter().next().unwrap())
    }

    pub fn prev_exercise(&self, exercise: &Exercise) -> &Exercise {
        let mut exercises = self.0.iter().rev();

        exercises.find(|&x| x == exercise);
        exercises
            .next()
            .unwrap_or_else(|| self.0.iter().last().unwrap())
    }

    pub fn next_week_exercise(&self, exercise: &Exercise) -> Option<&Exercise> {
        let mut exercises = self.0.iter();
        // Walk the iterator until `exercise`
        exercises.find(|&x| x == exercise);
        // Walk the iterator until the week/folder_name is different
        exercises.find(|&x| x.folder_name() != exercise.folder_name())
    }

    pub fn prev_week_exercise(&self, exercise: &Exercise) -> Option<&Exercise> {
        let mut exercises = self.0.iter().rev();
        // Walk the iterator until `exercise`
        exercises.find(|&x| x == exercise);
        // Walk the iterator until the week/folder_name is different
        exercises.find(|&x| x.folder_name() != exercise.folder_name())
    }

    pub fn exercise_index(&self, exercise: &Exercise) -> usize {
        let (index, _) = self
            .0
            .iter()
            .enumerate()
            .find(|(_i, x)| x == &exercise)
            .expect("exercise to be in the state");
        index
    }

    pub fn first_unfinished(&self) -> Option<&Exercise> {
        self.0
            .iter()
            .find(|x| matches!(x.status(), Status::NotStarted | Status::Started))
    }

    pub fn start_exercise(&mut self, exercise: &Exercise) {
        assert!(
            self.0.remove(exercise), // remove returns true if the item existed
            "state did not contain the exercise"
        );

        let mut exercise = exercise.clone();
        exercise.exercise_state.start_exercise();
        self.0.insert(exercise);
    }

    pub fn complete_exercise(&mut self, exercise: &Exercise) {
        assert!(
            self.0.remove(exercise), // remove returns true if the item existed
            "state did not contain the exercise"
        );

        let mut exercise = exercise.clone();
        exercise.exercise_state.complete_exercise();
        self.0.insert(exercise);
    }

    /// Finds the best matching exercise from the state
    pub fn match_exercise(&self, path: impl AsRef<Path>) -> Option<&Exercise> {
        let path = path
            .as_ref()
            .strip_prefix("exercises")
            .unwrap_or_else(|_| path.as_ref());

        if let Some(e) = self.0.iter().find(|exercise| exercise.path == path) {
            Some(e)
        } else if let Some(e) = self.0.iter().find(|exercise| exercise.path.ends_with(path)) {
            Some(e)
        } else if let Some(e) = self
            .0
            .iter()
            .filter(|ex| ex.path.to_str().unwrap().contains(path.to_str().unwrap()))
            // Next unfineshed
            .find(|ex| matches!(ex.status(), Status::NotStarted | Status::Started))
        {
            Some(e)
        } else {
            None
        }
    }
}