find data dir properly

This commit is contained in:
2023-04-28 22:34:17 -07:00
parent c5dcc2e50a
commit b761d3b493
5 changed files with 90 additions and 36 deletions

@ -75,35 +75,32 @@ pub fn set_auto_launch(is_configured: bool) -> Result<(), SetupError> {
let auto = AutoLaunchBuilder::new()
.set_app_name("Creddy")
.set_app_path(&path)
.build().expect("Failed to build");
.build()?;
let is_enabled = auto.is_enabled()?;
if is_configured && !is_enabled {
auto.enable().expect("Failed to enable");
auto.enable()?;
}
else if !is_configured && is_enabled {
auto.disable().expect("Failed to disable");
auto.disable()?;
}
Ok(())
}
pub fn get_or_create_db_path() -> PathBuf {
pub fn get_or_create_db_path() -> Result<PathBuf, DataDirError> {
if cfg!(debug_assertions) {
return PathBuf::from("./creddy.db");
return Ok(PathBuf::from("./creddy.db"));
}
let mut parent = std::env::var("HOME")
.map(|h| {
let mut p = PathBuf::from(h);
p.push(".config");
p
})
.unwrap_or(PathBuf::from("."));
let mut path = dirs::data_dir()
.ok_or(DataDirError::NotFound)?;
parent.push("creddy.db");
parent
std::fs::create_dir_all(&path)?;
path.push("creddy.db");
Ok(path)
}

@ -91,6 +91,17 @@ pub enum SetupError {
AutoLaunchError(#[from] auto_launch::Error),
#[error("Failed to start listener: {0}")]
ServerSetupError(#[from] std::io::Error),
#[error("Failed to resolve data directory: {0}")]
DataDir(#[from] DataDirError),
}
#[derive(Debug, ThisError, AsRefStr)]
pub enum DataDirError {
#[error("Could not determine data directory")]
NotFound,
#[error("Failed to create data directory: {0}")]
Io(#[from] std::io::Error),
}

@ -38,7 +38,7 @@ async fn setup(app: &mut App) -> Result<(), Box<dyn Error>> {
APP.set(app.handle()).unwrap();
let conn_opts = SqliteConnectOptions::new()
.filename(config::get_or_create_db_path())
.filename(config::get_or_create_db_path()?)
.create_if_missing(true);
let pool_opts = SqlitePoolOptions::new();
let pool: SqlitePool = pool_opts.connect_with(conn_opts).await?;