use anyhow::Result;
use clap::Parser;
use std::path::PathBuf;
use crate::config::{edit_config, print_config};
use crate::open::open_links;
use crate::storage::Storage;
use crate::toml_storage::TomlStorage;
#[derive(Parser, Debug)]
#[command(name = "bookmarks")]
#[command(about = "Bookmarks in your filesystem")]
#[command(version)]
pub struct Args {
#[arg(short = 'f', long = "bookmarks-file")]
pub bookmarks_file: Option<PathBuf>,
#[arg(short, long)]
pub config: bool,
#[cfg(feature = "app")]
#[arg(short = 'a', long)]
pub app: bool,
#[cfg(feature = "webapp")]
#[arg(short = 'w', long)]
pub webapp: bool,
pub links: Vec<String>,
}
fn resolve_storage(bookmarks_file: Option<PathBuf>) -> Result<TomlStorage> {
if let Some(path) = bookmarks_file {
anyhow::ensure!(
path.exists(),
"bookmarks file not found: {}",
path.display()
);
return Ok(TomlStorage::new(path));
}
if let Some(cwd_path) = TomlStorage::cwd_path()
&& cwd_path.exists()
{
return Ok(TomlStorage::new(cwd_path));
}
let storage = TomlStorage::with_default_path()?;
storage.init()?;
Ok(storage)
}
pub fn run<I, T>(args: I) -> Result<()>
where
I: IntoIterator<Item = T>,
T: Into<std::ffi::OsString> + Clone,
{
let args = Args::parse_from(args);
let storage = resolve_storage(args.bookmarks_file)?;
#[cfg(feature = "app")]
if args.app {
return crate::app::run(Box::new(storage)).map_err(|e| anyhow::anyhow!("{e}"));
}
#[cfg(feature = "webapp")]
if args.webapp {
return crate::webapp::run(Box::new(storage));
}
if args.config {
if let Some(path) = storage.path() {
edit_config(path)?;
}
return Ok(());
}
let config = storage.load()?;
if args.links.is_empty() {
print_config(&config);
} else {
open_links(&args.links, &config)?;
}
if let Some(path) = storage.path() {
println!(
"(using {}, use --bookmarks-file to override)",
path.display()
);
}
Ok(())
}