feat(images): quick implementation of image manipulation command

This commit is contained in:
Gustavo "Guz" L. de Mello
2024-05-02 11:36:58 -03:00
parent 69c6e6b17e
commit 4cd950a16f
2 changed files with 67 additions and 0 deletions

View File

@@ -41,3 +41,40 @@ pub fn get_links<'a>(ast: &'a Node<'a, RefCell<Ast>>) -> Vec<String> {
let r = links.borrow().to_vec();
r
}
pub fn iterate_images<'a, F>(ast: &'a Node<'a, RefCell<Ast>>, 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<Ast>>, 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<Ast>>, 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<Ast>>) -> Vec<String> {
let images: RefCell<Vec<String>> = RefCell::new(vec![]);
iterate_images(ast, |l| images.borrow_mut().push(l.url.clone()));
let r = images.borrow().to_vec();
r
}

View File

@@ -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<String>,
},
Remove {
#[clap(num_args = 1, value_names = ["URL"], required = true)]
images: Vec<String>,
},
}
#[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 {