use std::env;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{self, BufReader};
use std::path::PathBuf;
use anyhow::{Context, Result};
use crate::db::Dir;
use crate::import::{ImportError, Importer, z};
#[derive(clap::Args, Clone, Debug)]
pub(crate) struct ZLua {}
impl Importer for ZLua {
fn dirs(&self) -> Result<impl Iterator<Item = Result<Dir<'static>, ImportError>>> {
let path = data_path()?;
let err = match File::open(&path) {
Ok(file) => return Ok(z::Iter::new(BufReader::new(file), path)),
Err(e) if e.kind() == io::ErrorKind::NotFound => e,
Err(e) => return Err(e).with_context(|| format!("could not read {path:?}")),
};
let fish_path = data_path_fish()?;
let file = match File::open(&fish_path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return Err(err).with_context(|| format!("could not read {path:?}"));
}
Err(e) => return Err(e).with_context(|| format!("could not read {fish_path:?}")),
};
Ok(z::Iter::new(BufReader::new(file), fish_path))
}
}
fn data_path() -> Result<PathBuf> {
if let Some(path) = env::var_os("_ZL_DATA")
.filter(|path| !path.is_empty())
.filter(|path| cfg!(target_os = "windows") || !looks_like_windows_path(path))
{
return Ok(PathBuf::from(path));
}
let mut path = dirs::home_dir().context("could not find home directory")?;
path.push(".zlua");
Ok(path)
}
fn data_path_fish() -> Result<PathBuf> {
let mut path = match env::var_os("XDG_DATA_HOME") {
Some(xdg) => PathBuf::from(xdg),
None => {
let mut path = dirs::home_dir().context("could not find home directory")?;
path.push(".local");
path.push("share");
path
}
};
path.push("zlua");
path.push("zlua.txt");
Ok(path)
}
fn looks_like_windows_path(s: &OsStr) -> bool {
let bytes = s.as_encoded_bytes();
bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& (bytes[2] == b'/' || bytes[2] == b'\\')
}