summaryrefslogtreecommitdiff
path: root/schist_desktop_gui/src/paths.rs
blob: b09885997ee04d2ab95eae1bab5f9b9e82c71ebf (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
55
56
use std::{
    fs::{create_dir_all, read_dir, FileType},
    path::{Path, PathBuf},
};

use anyhow::Context;

const SCHIST_DATA_DIR: &'static str = "schist";

pub fn get_file_paths() -> Vec<PathBuf> {
    get_file_paths_checked()
        .inspect(|paths| println!("Found file paths: {:?}", paths))
        .inspect_err(|err| println!("Couldn't find any file paths: {:?}", err))
        .unwrap_or_else(|_| Vec::new())
}

fn get_file_paths_checked() -> anyhow::Result<Vec<PathBuf>> {
    let schist_data_dir = get_and_make_schist_data_dir()?;
    Ok(read_dir(schist_data_dir)?
        .filter_map(|entry| match entry {
            Ok(entry) => {
                if is_sqlite_file(&entry) {
                    Some(entry.path().to_path_buf())
                } else {
                    None
                }
            }
            Err(_) => None,
        })
        .collect())
}

fn is_sqlite_file(entry: &std::fs::DirEntry) -> bool {
    entry
        .file_type()
        .is_ok_and(|ft| FileType::is_file(&ft) || FileType::is_symlink(&ft))
        && entry
            .path()
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("sqlite"))
}

pub fn get_schist_database_directory() -> anyhow::Result<std::path::PathBuf> {
    get_and_make_schist_data_dir()
}

fn get_and_make_schist_data_dir() -> anyhow::Result<PathBuf> {
    let data_dir = dirs::data_dir().context("Failed to get app data directory")?;
    let schist_data_dir = data_dir.join(Path::new(SCHIST_DATA_DIR));
    create_dir_all(&schist_data_dir).context(format!(
        "Failed to create app data directory at {}",
        schist_data_dir.display()
    ))?;
    println!("Found app data directory at {:?}", schist_data_dir);
    Ok(schist_data_dir)
}