diff options
Diffstat (limited to 'examples/full-todolist/src/todolist.rs')
| -rw-r--r-- | examples/full-todolist/src/todolist.rs | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/examples/full-todolist/src/todolist.rs b/examples/full-todolist/src/todolist.rs new file mode 100644 index 0000000..e447f5d --- /dev/null +++ b/examples/full-todolist/src/todolist.rs @@ -0,0 +1,66 @@ +//! Data structures, read and write logic for the todo list + +use mingling::{ + macros::{r_println, renderer}, + Groupped, +}; +use serde::{Deserialize, Serialize}; +use std::{env::current_dir, path::PathBuf}; + +use crate::ResProgramFlags; + +#[derive(Debug, Serialize, Deserialize, Clone, Default, Groupped)] +pub struct ResTodoList { + pub items: Vec<Todo>, +} + +#[derive(Debug, Serialize, Deserialize, Clone, Default)] +pub struct Todo { + pub item: String, + pub completed: bool, +} + +fn get_todo_list_path() -> PathBuf { + current_dir().unwrap().join(".todo.json") +} + +pub fn read_todo_list() -> ResTodoList { + let path = get_todo_list_path(); + if !path.exists() { + return ResTodoList::default(); + } + let file = match std::fs::File::open(&path) { + Ok(f) => f, + Err(_) => return ResTodoList::default(), + }; + let reader = std::io::BufReader::new(file); + serde_json::from_reader(reader).unwrap_or_default() +} + +#[renderer] +pub fn render_res_todo_list(todo_list: ResTodoList, program_flags: &ResProgramFlags) { + let mut idx = 0; + r_println!("TODO: "); + for item in &todo_list.items { + if item.completed && !program_flags.all { + idx += 1; + continue; + } + r_println!( + " {idx}. [{}] - \"{}\"", + if item.completed { "x" } else { " " }, + item.item + ); + idx += 1; + } +} + +pub fn write_todo_list(todo_list: ResTodoList) { + let path = get_todo_list_path(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + let file = std::fs::File::create(path).unwrap(); + let writer = std::io::BufWriter::new(file); + serde_json::to_writer(writer, &todo_list).unwrap(); +} |
