aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::{fs, thread};
use tempfile::NamedTempFile;

use super::error::ClientError;

const REQUEST_COOLDOWN: Duration = Duration::from_secs(2);

pub(crate) fn root() -> Result<PathBuf, ClientError> {
    if let Some(value) = std::env::var_os("AOC_TOOLKIT_CACHE_DIR") {
        let path = PathBuf::from(value);

        if !path.is_absolute() {
            return Err(ClientError::InvalidCacheDirectory);
        }

        return Ok(path);
    }

    dirs::cache_dir()
        .map(|root| root.join("kyrboforge").join("aoc-toolkit"))
        .ok_or(ClientError::CacheDirectoryUnavailable)
}

pub(crate) fn store(path: &Path, content: &str) -> Result<(), ClientError> {
    let parent = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));

    fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;

    let mut temporary = NamedTempFile::new_in(parent).map_err(|source| io_error(parent, source))?;

    temporary
        .write_all(content.as_bytes())
        .map_err(|source| io_error(path, source))?;

    temporary
        .as_file()
        .sync_all()
        .map_err(|source| io_error(path, source))?;

    temporary
        .persist(path)
        .map_err(|error| io_error(path, error.error))?;

    Ok(())
}

pub(super) fn io_error(path: &Path, source: io::Error) -> ClientError {
    ClientError::Io {
        path: path.to_path_buf(),
        source,
    }
}

pub(crate) fn lock(path: &Path) -> Result<File, ClientError> {
    let parent = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));

    fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;

    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)
        .map_err(|source| io_error(path, source))?;

    file.lock().map_err(|source| io_error(path, source))?;

    Ok(file)
}

pub(super) fn with_request_cooldown<T>(operation: impl FnOnce() -> T) -> T {
    let result = operation();

    thread::sleep(REQUEST_COOLDOWN);

    result
}

#[cfg(test)]
mod tests;