summaryrefslogtreecommitdiff
path: root/crates/vcs_data/src/data/local/cached_sheet.rs
blob: 0f4eee9782eb46bd056f9fd3ba6b8398ec3c5408 (plain)
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
use std::{io::Error, path::PathBuf};

use cfg_file::config::ConfigFile;
use string_proc::snake_case;

use crate::{
    constants::CLIENT_FILE_CACHED_SHEET,
    current::current_local_path,
    data::{
        member::MemberId,
        sheet::{SheetData, SheetName},
    },
};

const SHEET_NAME: &str = "{sheet_name}";
const ACCOUNT_NAME: &str = "{account}";

/// # Cached Sheet
/// The cached sheet is a read-only version cloned from the upstream repository to the local environment,
/// automatically generated during update operations,
/// which records the latest Sheet information stored locally to accelerate data access and reduce network requests.
pub struct CachedSheet;

impl CachedSheet {
    /// Read the cached sheet data.
    pub async fn cached_sheet_data(
        account_name: MemberId,
        sheet_name: SheetName,
    ) -> Result<SheetData, std::io::Error> {
        let account_name = snake_case!(account_name);
        let sheet_name = snake_case!(sheet_name);

        let Some(path) = Self::cached_sheet_path(account_name, sheet_name) else {
            return Err(Error::new(
                std::io::ErrorKind::NotFound,
                "Local workspace not found!",
            ));
        };
        let data = SheetData::read_from(path).await?;
        Ok(data)
    }

    /// Get the path to the cached sheet file.
    pub fn cached_sheet_path(account_name: MemberId, sheet_name: SheetName) -> Option<PathBuf> {
        let current_workspace = current_local_path()?;
        Some(
            current_workspace.join(
                CLIENT_FILE_CACHED_SHEET
                    .replace(SHEET_NAME, &sheet_name.to_string())
                    .replace(ACCOUNT_NAME, &account_name.to_string()),
            ),
        )
    }
}