tasky_cli/
storage.rs

1use serde_json;
2use std::fs;
3use std::sync::OnceLock;
4
5use crate::task::Task;
6
7// Global storage for overriding file path (used in tests)
8static TASKS_FILE: OnceLock<String> = OnceLock::new();
9
10/// Set a custom file path (mainly for tests)
11pub fn set_tasks_file(path: &str) {
12    // Ignore error if already set (so first call wins)
13    let _ = TASKS_FILE.set(path.to_string());
14}
15
16/// Get current tasks file, defaults to "tasks.json"
17pub fn tasks_file() -> String {
18    TASKS_FILE
19        .get()
20        .cloned()
21        .unwrap_or_else(|| "tasks.json".to_string())
22}
23
24pub fn load_tasks() -> Vec<Task> {
25    load_tasks_from_file(&tasks_file())
26}
27
28pub fn load_tasks_from_file(file: &str) -> Vec<Task> {
29    fs::read_to_string(file)
30        .map(|s| serde_json::from_str(&s).unwrap_or(vec![]))
31        .unwrap_or(vec![])
32}
33
34pub fn save_tasks(tasks: &[Task]) {
35    save_tasks_to_file(tasks, &tasks_file())
36}
37
38pub fn save_tasks_to_file(tasks: &[Task], file: &str) {
39    let json = serde_json::to_string_pretty(tasks).expect("Failed to serialize tasks");
40    fs::write(file, json).expect("Failed to write tasks file");
41}