Skip to main content

logbook_dy/
lib.rs

1//! Records observations in a logbook file, or lists previous
2//! observations.
3
4use std::{
5    fs::{self, File},
6    io::Write,
7    path::Path,
8};
9
10use anyhow::Result;
11
12
13/// Reads the contents of a logbook at file `path`.
14///
15/// Returns [`None`] if the file does not exist or is is empty
16///
17/// # Errors
18///
19/// Returns any error from [`fs::exists`] or [`fs::read_to_string`].
20pub fn read(path: impl AsRef<Path>) -> Result<Option<String>> {
21    if fs::exists(&path)? {
22        let text = fs::read_to_string(path)?;
23
24        if text.is_empty() {
25            Ok(None)
26        } else {
27            Ok(Some(text))
28        }
29    } else {
30        Ok(None)
31    }
32}
33
34/// Appends `msg` to the logbook file at `path`, creating the file
35/// if necessary.
36///
37/// # Errors
38///
39/// Returns any error from [`open`](fs::OpenOptions::open) or
40/// [`writeln!`].
41pub fn append(path: impl AsRef<Path>, data: &str) -> Result<()> {
42    let mut file = File::options().create(true).append(true).open(path)?;
43    writeln!(file, "{data}")?;
44    Ok(())
45}