use clap::Parser;
use directories::ProjectDirs;
use oflow::{Cli, TodoList, execute_command};
use sqlx::SqlitePool;
use std::path::PathBuf;
fn get_data_dir(data_dir_option: Option<String>, is_release: bool) -> color_eyre::Result<PathBuf> {
if let Some(dir) = data_dir_option {
let path = PathBuf::from(dir);
if !path.exists() {
std::fs::create_dir_all(&path)?;
}
return Ok(path);
}
if is_release && let Some(proj_dirs) = ProjectDirs::from("com", "oasistodo", "oasistodo") {
let data_dir = proj_dirs.data_dir().to_path_buf();
if !data_dir.exists() {
std::fs::create_dir_all(&data_dir)?;
}
return Ok(data_dir);
}
Ok(PathBuf::from("."))
}
#[cfg(not(debug_assertions))]
const IS_RELEASE: bool = true;
#[cfg(debug_assertions)]
const IS_RELEASE: bool = false;
#[tokio::main]
async fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let cli = Cli::parse();
let data_dir = get_data_dir(cli.data_dir.clone(), IS_RELEASE)?;
let todos_toml_path = data_dir.join("todos.toml");
let todos_db_path = data_dir.join("todos.db");
let db_existed = todos_db_path.exists();
let toml_existed = todos_toml_path.exists();
let mut tdlist = TodoList::read_from_file(todos_toml_path.to_str().unwrap_or("todos.toml"))?;
let db_url = format!("sqlite:{}?mode=rwc", todos_db_path.display());
let pool = SqlitePool::connect(&db_url).await?;
sqlx::migrate!("./migrations").run(&pool).await?;
if db_existed {
tdlist.load_from_db(&pool).await?;
} else if toml_existed {
tdlist.sync_to_db(&pool).await?;
}
tdlist = execute_command(cli, tdlist, &pool, &data_dir).await?;
tdlist.write_to_file(todos_toml_path.to_str().unwrap_or("todos.toml"))?;
Ok(())
}