rtimelog 1.1.1

System for tracking time in a text-log-based format.
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
//! Interface to the stack file for the timelog application.
//!
//! # Examples
//!
//! ```rust
//! use timelog::stack::Stack;
//! # fn main() -> Result<(), timelog::Error> {
//! let stack = Stack::new("./stack.txt" )?;
//!
//! stack.push("+Project @Task More detail");
//! let task = stack.pop().expect("Can't pop task");
//! println!("{:?}", task);
//! stack.clear();
//! #   Ok(())
//! # }
//! ```

use std::fs::{self, File};
use std::io;
use std::io::prelude::*;
use std::num::NonZeroU32;
use std::path::Path;
use std::result;

#[doc(inline)]
use crate::error::{Error, PathError};
#[doc(inline)]
use crate::file;

/// Represent the stack file on disk.
#[derive(Debug)]
pub struct Stack(String);

impl Stack {
    /// Creates a [`Stack`] object wrapping the supplied file.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FilenameMissing`] if the `file` has no filename.
    /// - Return [`PathError::InvalidPath`] if the path part of `file` is not a valid path.
    /// - Return [`PathError::InvalidStackPath`] if stack path is invalid.
    pub fn new(file: &str) -> result::Result<Self, PathError> {
        file::canonical_filename(file, file::FileKind::StackFile).map(Self)
    }

    /// Open the stack file for reading, return a [`File`].
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if unable to open the file.
    pub fn open(&self) -> result::Result<File, PathError> {
        File::open(&self.0).map_err(|e| PathError::FileAccess(self.clone_file(), e.to_string()))
    }

    // Clone the filename
    fn clone_file(&self) -> String { self.0.clone() }

    /// Return `true` if the timelog file exists
    pub fn exists(&self) -> bool { Path::new(&self.0).exists() }

    /// Truncates the stack file, removing all items from the stack.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file is not accessible.
    pub fn clear(&self) -> result::Result<(), PathError> {
        fs::remove_file(&self.0).map_err(|e| PathError::FileAccess(self.clone_file(), e.to_string()))
    }

    /// Adds a new event to the stack file.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the stack file cannot be written.
    pub fn push(&self, task: &str) -> result::Result<(), PathError> {
        let file = file::append_open(&self.0)?;
        let mut stream = io::BufWriter::new(file);
        writeln!(&mut stream, "{task}")
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        stream
            .flush()
            .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
        Ok(())
    }

    /// Remove the most recent task from the stack file and return the task string.
    pub fn pop(&self) -> Option<String> {
        let mut file = file::rw_open(&self.0).ok()?;
        file::pop_last_line(&mut file)
    }

    /// Remove one or more tasks from the stack file.
    ///
    /// Remove `num` items from the stack.
    ///
    /// # Errors
    ///
    /// - Return [`Error::StackPop`] if attempts to pop more items than exist in the stack file.
    pub fn drop(&self, num: NonZeroU32) -> crate::Result<()> {
        (0..num.get())
            .try_for_each(|_| self.pop().map(|_| ()))
            .ok_or(Error::StackPop)
    }

    /// Remove everything except the top `num` tasks from the stack.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the stack file cannot be written.
    /// - Return [`PathError::RenameFailure`] if the stack file cannot be renamed.
    pub fn keep(&self, num: NonZeroU32) -> crate::Result<()> {
        let file = self.open()?;
        let unum = num.get() as usize;
        let len = io::BufReader::new(file).lines().count();

        if len > unum {
            let backfile = format!("{}-bak", self.0);
            let outfile = file::append_open(&backfile)?;
            let mut stream = io::BufWriter::new(outfile);
            let reader = io::BufReader::new(self.open()?);
            for line in reader.lines().skip(len - unum).flatten() {
                writeln!(&mut stream, "{line}")
                    .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;
            }
            stream
                .flush()
                .map_err(|e| PathError::FileWrite(self.clone_file(), e.to_string()))?;

            fs::rename(&backfile, self.clone_file())
                .map_err(|e| PathError::RenameFailure(self.clone_file(), e.to_string()))?;
        }
        Ok(())
    }

    /// Process the stack top-down, passing the index and lines to the supplied function.
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the stack file cannot be written.
    /// - Return [`PathError::RenameFailure`] if the stack file cannot be renamed.
    pub fn process_down_stack<F>(&self, mut func: F) -> crate::Result<()>
    where
        F: FnMut(usize, &str)
    {
        let file = self.open()?;
        let lines: Vec<String> = io::BufReader::new(file).lines().map_while(Result::ok).collect();
        for (i, ln) in lines.iter().rev().enumerate() {
            func(i, ln);
        }
        Ok(())
    }

    /// Format the stack as a [`String`].
    ///
    /// The stack will be formatted such that the most recent item is listed
    /// first.
    pub fn list(&self) -> String {
        let mut output = String::new();
        let Ok(_) = self.process_down_stack(|_, l| {
            output.push_str(l);
            output.push('\n');
        })
        else {
            return String::new();
        };

        output
    }

    /// Return the top of the stack as a [`String`].
    ///
    /// # Errors
    ///
    /// - Return [`PathError::FileAccess`] if the stack file cannot be opened or created.
    /// - Return [`PathError::FileWrite`] if the stack file cannot be written.
    /// - Return [`PathError::RenameFailure`] if the stack file cannot be renamed.
    pub fn top(&self) -> crate::Result<String> {
        let file = self.open()?;
        let reader = io::BufReader::new(file).lines().map_while(Result::ok);
        Ok(reader.last().unwrap_or_default())
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use assert2::{assert, let_assert};
    use nzliteral::nzliteral;
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_new_missing_file() {
        let_assert!(Err(err) = Stack::new(""));
        assert!(err == PathError::FilenameMissing);
    }

    #[test]
    fn test_new_bad_path() {
        let mut stackdir = TempDir::new()
            .expect("Cannot make tempdir")
            .path()
            .to_path_buf();
        stackdir.push("foo");
        stackdir.push("stack.txt");

        let_assert!(Some(file) = stackdir.as_path().to_str());
        let_assert!(Err(e) = Stack::new(file));
        assert!(e == PathError::InvalidPath(
            file.to_string(),
            "No such file or directory (os error 2)".to_string()
        ));
    }

    #[test]
    fn test_new() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        assert!(Stack::new(filename).is_ok());
    }

    #[test]
    fn test_push() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(!Path::new(filename).exists());

        let task = "+house @todo change filters";
        assert!(stack.push(task).is_ok());
        let path = Path::new(filename);
        assert!(path.is_file());

        // test file length and handle newline lengths
        let_assert!(Ok(filelen) = path.metadata().map(|m| m.len() as usize));
        assert!(filelen == task.len() + 1);

        assert!(stack.push(task).is_ok());
        let_assert!(Ok(filelen) = path.metadata().map(|m| m.len() as usize));
        assert!(filelen == 2 * task.len() + 2);
    }

    #[test]
    fn test_pop() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo second"));
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo first"));

        let path = Path::new(filename);
        assert!(path.is_file());
        // test file length and handle newline lengths
        let_assert!(Ok(filelen) = path.metadata().map(|m| m.len() as usize));
        assert!(filelen == 0);
    }

    #[test]
    fn test_clear() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(stack.clear().is_ok());
        assert!(!Path::new(filename).exists());
    }

    #[test]
    fn test_drop_1() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n"), "Cannot fill file");

        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(stack.drop(nzliteral!(1u32)).is_ok());
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo first"));
    }

    #[test]
    fn test_drop_2() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n+home @todo third\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(stack.drop(nzliteral!(2u32)).is_ok());
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo first"));
    }

    #[test]
    fn test_keep_1() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(stack.keep(nzliteral!(1u32)).is_ok());
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo second"));
        assert!(stack.pop().is_none());
    }

    #[test]
    fn test_keep_2() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n+home @todo third\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(stack.keep(nzliteral!(2u32)).is_ok());
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo third"));
        let_assert!(Some(line) = stack.pop());
        assert!(line == String::from("+home @todo second"));
        assert!(stack.pop().is_none());
    }

    #[test]
    fn test_list() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n+home @todo third\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        assert!(stack.list() == String::from(
            "+home @todo third\n+home @todo second\n+home @todo first\n"
        ));
    }

    #[test]
    fn test_top() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(mut file) = File::create(filename));
        let_assert!(Ok(_) = file.write_all(b"+home @todo first\n+home @todo second\n+home @todo third\n"));

        let_assert!(Ok(stack) = Stack::new(filename));
        let_assert!(Ok(line) = stack.top());
        assert!(line == String::from("+home @todo third"));
    }

    #[test]
    fn test_top_empty() {
        let_assert!(Ok(tmpdir) = TempDir::new());
        let mut path = tmpdir.path().to_path_buf();
        path.push("stack.txt");

        let_assert!(Some(filename) = path.to_str());
        let_assert!(Ok(_) = File::create(filename));

        let_assert!(Ok(stack) = Stack::new(filename));
        let_assert!(Ok(line) = stack.top());
        assert!(line == String::new());
    }
}