use std::{
env::{self, current_dir},
fs::read_dir,
path::{Path, PathBuf},
};
use crate::path;
use super::state::{Result, UtpmError};
pub const TYPST_PACKAGE_URL: &str = "https://github.com/typst/packages";
pub const UTPM_SUBDIR: &str = "utpm";
pub const MANIFEST_FILE: &str = "typst.toml";
pub const LOCAL_PACKAGES: &str = "git-packages";
fn env_path(key: &str) -> Option<PathBuf> {
env::var(key).ok().map(PathBuf::from)
}
fn not_found(message: &str) -> UtpmError {
std::io::Error::new(std::io::ErrorKind::NotFound, message).into()
}
pub fn package_cache_path() -> Result<PathBuf> {
env_path("TYPST_PACKAGE_CACHE_PATH")
.or_else(typst_kit::package::default_package_cache_path)
.ok_or_else(|| not_found("Could not find package cache directory"))
}
pub fn package_path() -> Result<PathBuf> {
env_path("TYPST_PACKAGE_PATH")
.or_else(typst_kit::package::default_package_path)
.ok_or_else(|| not_found("Could not find package directory"))
}
pub fn utpm_data_path() -> Result<PathBuf> {
env_path("UTPM_DATA_PATH")
.or_else(|| dirs::data_dir().map(|data_dir| path!(data_dir, UTPM_SUBDIR)))
.ok_or_else(|| not_found("Could not find utpm data directory"))
}
pub fn local_package_path() -> Result<PathBuf> {
Ok(path!(utpm_data_path()?, LOCAL_PACKAGES))
}
pub fn get_current_dir() -> Result<PathBuf> {
env_path("UTPM_CURRENT_DIR")
.ok_or(())
.or_else(|()| current_dir())
.map_err(Into::into)
}
pub fn has_content(path: impl AsRef<Path>) -> Result<bool> {
Ok(read_dir(path)?.next().is_some())
}
pub fn check_path_dir(path: impl AsRef<Path>) -> bool {
path.as_ref().is_dir()
}
pub fn check_path_file(path: impl AsRef<Path>) -> bool {
path.as_ref().is_file()
}