rust_releases_io/
io.rs

1use std::path::{Path, PathBuf};
2use std::time::Duration;
3use std::{io, time};
4
5/// Determines whether a stored resource is stale
6pub fn is_stale<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<bool, IsStaleError> {
7    let metadata = std::fs::metadata(path).map_err(IsStaleError::ReadMetadata)?;
8    let modification = metadata
9        .modified()
10        .map_err(IsStaleError::ReadModificationDate)?;
11    let duration = modification
12        .elapsed()
13        .map_err(IsStaleError::ElapsedSinceModified)?;
14
15    Ok(timeout < duration)
16}
17
18/// Returned in case the staleness check [`is_stale`] faults.
19#[derive(Debug, thiserror::Error)]
20#[non_exhaustive]
21pub enum IsStaleError {
22    /// Returned when the staleness check could not be completed because the
23    /// cache file metadata could not be read.
24    #[error("Failed to check if file is stale: unable to read metadata ({0})")]
25    ReadMetadata(io::Error),
26
27    /// Returned when the staleness check could not be completed because the
28    /// cache file modification time could not be read.
29    #[error("Failed to check if file is stale: unable to read modification date ({0})")]
30    ReadModificationDate(io::Error),
31
32    /// Returned when the staleness check could not be completed because the
33    /// modification date of the cache file is more recent than the current system time.
34    /// The modification date should not be in the future.
35    #[error("Failed to check if file is stale: modification date is more recent than the current system time ({0})")]
36    ElapsedSinceModified(time::SystemTimeError),
37}
38
39/// The default cache dir used by `rust-releases` crates
40pub fn base_cache_dir() -> Result<PathBuf, BaseCacheDirError> {
41    let cache = directories_next::ProjectDirs::from("com", "ilumeo", "rust-releases")
42        .ok_or(BaseCacheDirError)?;
43    let cache = cache.cache_dir();
44
45    Ok(cache.to_path_buf())
46}
47
48/// Returned when the base cache folder is used, but can not be located.
49#[derive(Debug, thiserror::Error)]
50#[error("Unable to locate base cache folder")]
51pub struct BaseCacheDirError;