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
use crate::{
config::{FileWorkerConfig, SavePolicy},
error::Result,
todo::ToDo,
ToDoError,
};
use notify::{
event::{AccessKind, AccessMode, EventKind},
Config as NotifyConfig, RecommendedWatcher, RecursiveMode, Watcher,
};
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Read, Write};
use std::path::Path;
use std::str::FromStr;
use std::sync::mpsc::Sender;
use std::sync::{mpsc, Arc, Mutex};
use std::{thread, time::Duration};
use todo_txt::Task;
/// Commands that can be sent to the `FileWorker` for various file-related operations.
pub enum FileWorkerCommands {
ForceSave,
Save,
Load,
Exit,
}
/// Manages file operations for the todo list and archive.
pub struct FileWorker {
config: FileWorkerConfig,
todo: Arc<Mutex<ToDo>>,
}
impl FileWorker {
/// Creates a new `FileWorker` instance.
///
/// # Arguments
///
/// * `todo_path` - The path to the todo list file.
/// * `archive_path` - The optional path to the archive file.
/// * `todo` - A shared reference to the `ToDo` data structure.
///
/// # Returns
///
/// A `FileWorker` instance.
pub fn new(config: FileWorkerConfig, todo: Arc<Mutex<ToDo>>) -> FileWorker {
log::info!(
"Init file worker: file: {:?}, archive: {:?}",
config.todo_path,
config.archive_path
);
FileWorker { config, todo }
}
/// Loads todo list data from the file(s).
///
/// This method loads data from the main todo list file and optionally from an archive file.
///
/// # Returns
///
/// An `ioResult` indicating success or an error if file operations fail.
pub fn load(&self) -> Result<()> {
let mut todo = ToDo::default(); // TODO this can be improved
Self::load_tasks(
File::open(&self.config.todo_path)
.map_err(|e| ToDoError::io_operation_failed(&self.config.todo_path, e))?,
&mut todo,
)?;
log::info!(
"Load tasks from file {}",
self.config.todo_path.to_string_lossy()
);
if let Some(path) = &self.config.archive_path {
log::info!("Load tasks from achive file {}", path.to_string_lossy());
Self::load_tasks(
File::open(path).map_err(|e| ToDoError::io_operation_failed(path, e))?,
&mut todo,
)?;
}
log::debug!("Loaded pending {}x tasks", todo.pending.len());
log::debug!("Loaded done {}x tasks", todo.done.len());
self.todo.lock().unwrap().move_data(todo);
Ok(())
}
/// Loads tasks from a given reader and adds them to the provided `ToDo` instance.
///
/// # Arguments
///
/// * `reader` - A readable source (e.g., a file) to load tasks from.
/// * `todo` - A mutable reference to the `ToDo` instance where tasks will be added.
///
/// # Returns
///
/// An `ioResult` indicating success or an error if file operations fail.
fn load_tasks<R: Read>(reader: R, todo: &mut ToDo) -> Result<()> {
for line in BufReader::new(reader).lines() {
let line = line?;
let line = line.trim();
if line.is_empty() {
continue;
}
match Task::from_str(line) {
Ok(task) => todo.add_task(task),
Err(e) => log::warn!("Task cannot be load due {e}: {line}"),
}
}
Ok(())
}
/// Saves todo list data to the file(s).
///
/// This method saves data to the main todo list file and optionally to an archive file.
///
/// # Returns
///
/// An `ioResult` indicating success or an error if file operations fail.
fn save(&self) -> Result<()> {
let mut f = File::create(&self.config.todo_path)
.map_err(|e| ToDoError::io_operation_failed(&self.config.todo_path, e))?;
let todo = self.todo.lock().unwrap();
log::info!(
"Saving todo task to {}{}",
self.config.todo_path.to_string_lossy(),
self.config
.archive_path
.as_ref()
.map_or(String::from(""), |p| String::from(" and")
+ &p.to_string_lossy()),
);
Self::save_tasks(&mut f, &todo.pending)?;
match &self.config.archive_path {
Some(s) => Self::save_tasks(
&mut File::create(s).map_err(|err| ToDoError::io_operation_failed(s, err))?,
&todo.done,
),
None => Self::save_tasks(&mut f, &todo.done),
}
}
/// Saves a list of tasks to the provided writer.
///
/// # Arguments
///
/// * `writer` - A writable destination (e.g., a file) where tasks will be saved.
/// * `tasks` - A reference to a slice of tasks to be saved.
///
/// # Returns
///
/// An `ioResult` indicating success or an error if file operations fail.
fn save_tasks<W: Write>(writer: &mut W, tasks: &[Task]) -> Result<()> {
let mut writer = BufWriter::new(writer);
for task in tasks.iter() {
writer.write_all((task.to_string() + "\n").as_bytes())?;
}
Ok(())
}
/// Runs the `FileWorker` thread.
///
/// This method starts the `FileWorker` thread and handles file-related operations and
/// synchronization with other parts of the application.
///
/// # Arguments
///
/// * `autosave_duration` - The duration between automatic saves of todo data.
/// * `handle_changes` - A flag indicating whether to handle file change events.
///
/// # Returns
///
/// A `Sender` that can be used to send commands to the `FileWorker` thread.
pub fn run(self) -> Result<Sender<FileWorkerCommands>> {
use FileWorkerCommands::*;
let (tx, rx) = mpsc::channel::<FileWorkerCommands>();
match self.config.save_policy {
SavePolicy::AutoSave if !self.config.autosave_duration.is_zero() => {
Self::spawn_autosave(tx.clone(), self.config.autosave_duration);
}
SavePolicy::OnChange => {
self.todo.lock().unwrap().get_version_mut().tx = Some(tx.clone());
}
_ => {}
}
if self.config.file_watcher {
Self::spawn_watcher(tx.clone(), &self.config.todo_path)?;
if let Some(path) = &self.config.archive_path {
Self::spawn_watcher(tx.clone(), path)?;
}
}
thread::spawn(move || {
let mut versions = self.todo.lock().unwrap().get_version().get_version_all();
let mut save_queue = 0;
for received in rx {
log::debug!("Save queue value: {save_queue}");
if let Err(e) = match received {
Save => {
log::trace!("Try to save Todo list.");
if self
.todo
.lock()
.unwrap()
.get_version()
.is_actual_all(versions)
{
log::info!("File Worker: Todo list is actual.");
Ok(())
} else {
save_queue += 1;
if self.config.archive_path.is_some() {
save_queue += 1;
}
self.save()
}
}
ForceSave => {
log::trace!("Force save Todo list.");
save_queue += 1;
if self.config.archive_path.is_some() {
save_queue += 1;
}
let result = self.save();
versions = self.todo.lock().unwrap().get_version().get_version_all();
result
}
Load => {
if save_queue == 0 {
let result = self.load();
versions = self.todo.lock().unwrap().get_version().get_version_all();
log::info!("Todo list updated from file.");
result
} else {
save_queue -= 1;
Ok(())
}
}
Exit => break,
} {
log::error!("File Worker: {}", e);
}
}
});
Ok(tx)
}
/// Spawns an autosave thread that periodically saves the todo list data.
///
/// # Arguments
///
/// * `tx` - A sender for sending `FileWorkerCommands` to the `FileWorker` thread.
/// * `duration` - The duration between automatic saves of todo data.
fn spawn_autosave(tx: Sender<FileWorkerCommands>, duration: Duration) {
log::trace!("Start autosaver");
thread::spawn(move || loop {
thread::sleep(duration);
log::trace!("Autosave with duration {}", duration.as_secs_f64());
if tx.send(FileWorkerCommands::Save).is_err() {
log::trace!("Autosave end");
}
});
}
/// Spawns a file watcher thread to monitor changes to a specific file.
///
/// # Arguments
///
/// * `tx` - A sender for sending `FileWorkerCommands` to the `FileWorker` thread.
/// * `path` - The path to the file to be watched for changes.
fn spawn_watcher(tx: Sender<FileWorkerCommands>, path: &Path) -> Result<()> {
log::trace!("Start file watcher");
let (tx_handle, rx_handle) = std::sync::mpsc::channel();
let mut watcher: RecommendedWatcher = Watcher::new(tx_handle, NotifyConfig::default())?;
watcher.watch(Path::new(path), RecursiveMode::NonRecursive)?;
let path = path.to_path_buf();
thread::spawn(move || {
for res in rx_handle {
match res {
Ok(event) => match event.kind {
EventKind::Access(AccessKind::Close(AccessMode::Write)) => {
log::trace!("File {} changed", path.to_string_lossy());
if tx.send(FileWorkerCommands::Load).is_err() {
break;
};
}
_ => log::debug!("Change: {event:?}"),
},
Err(error) => log::error!("Error: {error:?}"),
}
}
drop(watcher);
});
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
const TESTING_STRING: &str = r#"
x (A) 2023-05-21 2023-04-30 measure space for 1 +project1 @context1 #hashtag1 due:2023-06-30
2023-04-30 measure space for 2 +project2 @context2 due:2023-06-30
(C) 2023-04-30 measure space for 3 +project3 @context3 due:2023-06-30
measure space for 4 +project2 @context3 #hashtag1 due:2023-06-30
x measure space for 5 +project3 @context3 #hashtag2 due:2023-06-30
measure space for 6 +project3 @context2 #hashtag2 due:2023-06-30
"#;
#[test]
fn test_load_tasks() -> Result<()> {
let mut todo = ToDo::default();
FileWorker::load_tasks(TESTING_STRING.as_bytes(), &mut todo)?;
assert_eq!(todo.pending.len(), 4);
assert_eq!(todo.done.len(), 2);
assert_eq!(
todo.pending[0].subject,
"measure space for 2 +project2 @context2"
);
assert_eq!(
todo.pending[1].subject,
"measure space for 3 +project3 @context3"
);
assert_eq!(todo.pending[1].priority, 2);
assert_eq!(
todo.pending[2].subject,
"measure space for 4 +project2 @context3 #hashtag1"
);
assert_eq!(
todo.pending[3].subject,
"measure space for 6 +project3 @context2 #hashtag2"
);
assert_eq!(
todo.done[0].subject,
"measure space for 1 +project1 @context1 #hashtag1"
);
assert_eq!(
todo.done[1].subject,
"measure space for 5 +project3 @context3 #hashtag2"
);
Ok(())
}
#[test]
fn test_write_tasks() -> Result<()> {
let mut todo = ToDo::default();
FileWorker::load_tasks(TESTING_STRING.as_bytes(), &mut todo)?;
let get_expected = |line: fn(&String) -> bool| {
TESTING_STRING
.trim()
.lines()
.map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
.filter(line)
.collect::<Vec<String>>()
.join("\n")
+ "\n"
};
let pretty_assert = |tasks, expected: &str, msg: &str| -> Result<()> {
let mut buf: Vec<u8> = Vec::new();
FileWorker::save_tasks(&mut buf, tasks)?;
assert_eq!(
expected.as_bytes(),
buf,
// if test failed print data in string not only in byte array
"\n-----{}-----\nGET:\n{}\n----------------\nEXPECTED:\n{}\n",
msg,
String::from_utf8(buf.clone()).unwrap(),
expected
);
Ok(())
};
pretty_assert(
&todo.pending,
&get_expected(|line| !line.starts_with("x ")),
"Pending check is wrong",
)?;
pretty_assert(
&todo.done,
&get_expected(|line| line.starts_with("x ")),
"Done check is wrong",
)?;
Ok(())
}
}