Skip to content

Commit

Permalink
feat: add used_vars in TemplateFix
Browse files Browse the repository at this point in the history
part of #1070
  • Loading branch information
HerringtonDarkholme committed Apr 23, 2024
1 parent 02f2467 commit 0908d3e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
10 changes: 10 additions & 0 deletions crates/core/src/replacer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ enum MetaVarExtract {
Transformed(MetaVariableID),
}

impl MetaVarExtract {
fn used_var(&self) -> &str {
match self {
MetaVarExtract::Single(s) => s,
MetaVarExtract::Multiple(s) => s,
MetaVarExtract::Transformed(s) => s,
}
}
}

fn split_first_meta_var(
src: &str,
meta_char: char,
Expand Down
22 changes: 21 additions & 1 deletion crates/core/src/replacer/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ use crate::matcher::NodeMatch;
use crate::meta_var::MetaVarEnv;
use crate::source::{Content, Doc};

use std::borrow::Cow;
use thiserror::Error;

use std::borrow::Cow;
use std::collections::HashSet;

pub enum TemplateFix {
// no meta_var, pure text
Textual(String),
Expand All @@ -25,6 +27,14 @@ impl TemplateFix {
pub fn with_transform<L: Language>(tpl: &str, lang: &L, trans: &[String]) -> Self {
create_template(tpl, lang.meta_var_char(), trans)
}

pub fn used_vars(&self) -> HashSet<&str> {
let template = match self {
TemplateFix::WithMetaVar(t) => t,
TemplateFix::Textual(_) => return HashSet::new(),
};
template.vars.iter().map(|v| v.0.used_var()).collect()
}
}

impl<D: Doc> Replacer<D> for TemplateFix {
Expand Down Expand Up @@ -313,6 +323,16 @@ if (true) {
test_template_replace("$B $A", &[("A", "World"), ("B", "Hello")], "Hello World");
}

#[test]
fn test_template_vars() {
let tf = TemplateFix::try_new("$A $B $C", &Tsx).expect("ok");
assert_eq!(tf.used_vars(), ["A", "B", "C"].into_iter().collect());
let tf = TemplateFix::try_new("$a$B$C", &Tsx).expect("ok");
assert_eq!(tf.used_vars(), ["B", "C"].into_iter().collect());
let tf = TemplateFix::try_new("$a$B$C", &Tsx).expect("ok");
assert_eq!(tf.used_vars(), ["B", "C"].into_iter().collect());
}

// GH #641
#[test]
fn test_multi_row_replace() {
Expand Down

0 comments on commit 0908d3e

Please sign in to comment.