diff --git a/src/links.rs b/src/links.rs index 11eb916..8ba938f 100644 --- a/src/links.rs +++ b/src/links.rs @@ -41,3 +41,40 @@ pub fn get_links<'a>(ast: &'a Node<'a, RefCell>) -> Vec { let r = links.borrow().to_vec(); r } + +pub fn iterate_images<'a, F>(ast: &'a Node<'a, RefCell>, iterator: F) +where + F: Fn(&mut NodeLink), +{ + utils::iter_nodes(ast, &|node| { + if let NodeValue::Image(ref mut l) = &mut node.data.borrow_mut().value { + iterator(l); + }; + }); +} + +pub fn replace_images<'a>(ast: &'a Node<'a, RefCell>, from: &'a str, to: &'a str) { + iterate_images(ast, |l| { + if l.url == from { + l.url = String::from(to) + } + }); +} + +pub fn remove_image<'a>(ast: &'a Node<'a, RefCell>, url: &'a str) { + utils::iter_nodes(ast, &|node| { + if let NodeValue::Image(ref mut l) = &mut node.data.borrow_mut().value { + if l.url == url { + node.children().for_each(|n| node.insert_before(n)); + node.detach(); + } + } + }) +} + +pub fn get_images<'a>(ast: &'a Node<'a, RefCell>) -> Vec { + let images: RefCell> = RefCell::new(vec![]); + iterate_images(ast, |l| images.borrow_mut().push(l.url.clone())); + let r = images.borrow().to_vec(); + r +} diff --git a/src/main.rs b/src/main.rs index 276078b..031537a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -74,12 +74,29 @@ enum LinksCommands { }, } +#[derive(Debug, Subcommand)] +enum ImagesCommands { + List {}, + Replace { + #[clap(num_args = 2, value_names = ["FROM", "TO"], required = true)] + replace: Vec, + }, + Remove { + #[clap(num_args = 1, value_names = ["URL"], required = true)] + images: Vec, + }, +} + #[derive(Debug, Subcommand)] enum Commands { Links { #[command(subcommand)] command: LinksCommands, }, + Images { + #[command(subcommand)] + command: ImagesCommands, + }, Frontmatter { #[command(subcommand)] command: FrontmatterCommands, @@ -128,6 +145,19 @@ fn main() { cli::ResultType::Markdown(ast) } }, + Commands::Images { command } => match command { + ImagesCommands::List {} => cli::ResultType::List(links::get_images(ast)), + ImagesCommands::Replace { replace } => { + replace + .chunks(2) + .for_each(|p| links::replace_images(ast, &p[0], &p[1])); + cli::ResultType::Markdown(ast) + } + ImagesCommands::Remove { images } => { + images.iter().for_each(|l| links::remove_image(ast, l)); + cli::ResultType::Markdown(ast) + } + }, Commands::Frontmatter { command } => { if let None = ast.children().find(|c| { if let NodeValue::FrontMatter(_) = c.data.borrow().value {