Implement @set

This commit is contained in:
Nixon Enraght-Moony 2021-02-20 01:25:09 +00:00
parent a00eb7ee1d
commit cd5f603c31
3 changed files with 26 additions and 0 deletions

View File

@ -7,15 +7,18 @@
// @is nested.json "$.index[*][?(@.name=='l1')].kind" \"module\"
// @is - "$.index[*][?(@.name=='l1')].inner.is_crate" false
// @count - "$.index[*][?(@.name=='l1')].inner.items[*]" 2
// @set l1_id = - "$.index[*][?(@.name=='l1')].id"
pub mod l1 {
// @is nested.json "$.index[*][?(@.name=='l3')].kind" \"module\"
// @is - "$.index[*][?(@.name=='l3')].inner.is_crate" false
// @count - "$.index[*][?(@.name=='l3')].inner.items[*]" 1
// @set l3_id = - "$.index[*][?(@.name=='l3')].id"
pub mod l3 {
// @is nested.json "$.index[*][?(@.name=='L4')].kind" \"struct\"
// @is - "$.index[*][?(@.name=='L4')].inner.struct_type" \"unit\"
// @set l4_id = - "$.index[*][?(@.name=='L4')].id"
pub struct L4;
}
// @is nested.json "$.index[*][?(@.inner.span=='l3::L4')].kind" \"import\"

View File

@ -9,6 +9,7 @@ pub struct Cache {
root: PathBuf,
files: HashMap<PathBuf, String>,
values: HashMap<PathBuf, Value>,
pub variables: HashMap<String, Value>,
last_path: Option<PathBuf>,
}
@ -19,6 +20,7 @@ impl Cache {
root: Path::new(doc_dir).to_owned(),
files: HashMap::new(),
values: HashMap::new(),
variables: HashMap::new(),
last_path: None,
}
}

View File

@ -49,6 +49,7 @@ pub enum CommandKind {
Has,
Count,
Is,
Set,
}
impl CommandKind {
@ -56,6 +57,7 @@ impl CommandKind {
let count = match self {
CommandKind::Has => (1..=3).contains(&args.len()),
CommandKind::Count | CommandKind::Is => 3 == args.len(),
CommandKind::Set => 4 == args.len(),
};
if !count {
@ -85,6 +87,7 @@ impl fmt::Display for CommandKind {
CommandKind::Has => "has",
CommandKind::Count => "count",
CommandKind::Is => "is",
CommandKind::Set => "set",
};
write!(f, "{}", text)
}
@ -130,6 +133,7 @@ fn get_commands(template: &str) -> Result<Vec<Command>, ()> {
"has" => CommandKind::Has,
"count" => CommandKind::Count,
"is" => CommandKind::Is,
"set" => CommandKind::Set,
_ => {
print_err(&format!("Unrecognized command name `@{}`", cmd), lineno);
errors = true;
@ -236,6 +240,23 @@ fn check_command(command: Command, cache: &mut Cache) -> Result<(), CkError> {
Err(_) => false,
}
}
// FIXME, Figure out semantics for @!set
CommandKind::Set => {
// @set <name> = <path> <jsonpath>
assert_eq!(command.args.len(), 4);
assert_eq!(command.args[1], "=", "Expected an `=`");
let val = cache.get_value(&command.args[2])?;
match select(&val, &command.args[3]) {
Ok(results) => {
assert_eq!(results.len(), 1);
let r = cache.variables.insert(command.args[0].clone(), results[0].clone());
assert!(r.is_none(), "Name collision");
true
}
Err(_) => false,
}
}
};
if result == command.negated {