mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 17:37:14 +00:00
Keep explicit imported calls within their declared scope
This commit is contained in:
1 parent
f0940f160f
commit
012342d87e
5 files changed
+113
-13
No files matched your search
@@ -137,7 +137,8 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec<
|
||||
.map(|u| format!("`{}` step {}: Photoshop's \"{}\" ({}) has no PhotoCraft equivalent yet", u.action, u.step + 1, u.name, u.event))
|
||||
.chain(imp.warnings.iter().cloned())
|
||||
.collect();
|
||||
photocraft_engine::atn_cmds::normalize_import(&mut imp, std::iter::empty()).map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?;
|
||||
photocraft_engine::atn_cmds::normalize_import(&mut imp, std::iter::empty(), false)
|
||||
.map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?;
|
||||
let play = vec![("actions.play".to_string(), json!({"action": imp.actions[selected].name}))];
|
||||
Ok((play, imp.actions, warnings))
|
||||
}
|
||||
@@ -1938,3 +1938,57 @@ fn batch_refuses_ambiguous_nested_atn_calls_before_output() {
|
||||
assert!(String::from_utf8_lossy(&stderr).contains("ambiguous cross-set"));
|
||||
assert!(!output.exists());
|
||||
}
|
||||
|
||||
/// An explicit archive scope cannot fall back to a namesake in another physical set.
|
||||
#[test]
|
||||
fn batch_refuses_missing_or_ambiguous_explicit_atn_scopes_before_output() {
|
||||
use photocraft_engine::{actions_cmds::Action, atn_cmds};
|
||||
use photocraft_psd::atn;
|
||||
for failure in ["missing-target", "missing-set", "ambiguous-set"] {
|
||||
for call in ["play", "shared", "then", "else"] {
|
||||
let directory = tmp(&format!("nested-atn-scope-{failure}-{call}"));
|
||||
let scope = if failure == "missing-set" { "Absent" } else { "A" };
|
||||
let file = directory.join("sets.atn");
|
||||
let finish = Action::new("Finish", vec![("layer.new.layer".into(), json!({}))]);
|
||||
let other = Action::new("Other", Vec::new());
|
||||
let (id, params) = match call {
|
||||
"play" => ("actions.play", json!({"action":"Finish","set":scope})),
|
||||
"shared" => ("actions.conditional", json!({"if":"always","then":"Finish","else":null,"set":scope})),
|
||||
"then" => ("actions.conditional", json!({"if":"always","then":"Finish","thenSet":scope,"else":"Finish","elseSet":"B"})),
|
||||
_ => ("actions.conditional", json!({"if":"always","then":"Finish","thenSet":"B","else":"Finish","elseSet":scope})),
|
||||
};
|
||||
let caller = Action::new("Caller", vec![(id.into(), params)]);
|
||||
let group = |name: &str, actions: &[&Action]| {
|
||||
let bytes = atn_cmds::export(name, actions, &[], false).unwrap().0;
|
||||
atn::parse(&bytes).unwrap()
|
||||
};
|
||||
let mut groups = vec![group("A", &[if failure == "ambiguous-set" { &finish } else { &other }])];
|
||||
if failure == "ambiguous-set" {
|
||||
groups.push(group("A", &[&finish]));
|
||||
}
|
||||
groups.push(group("B", &[&finish, &caller]));
|
||||
std::fs::write(&file, atn::write_sets(&groups).unwrap()).unwrap();
|
||||
let output = directory.join("out");
|
||||
let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
|
||||
let args = [
|
||||
"batch".as_ref(),
|
||||
"--in".as_ref(),
|
||||
directory.as_os_str(),
|
||||
"--out".as_ref(),
|
||||
output.as_os_str(),
|
||||
"--actions".as_ref(),
|
||||
file.as_os_str(),
|
||||
"--action".as_ref(),
|
||||
"Caller".as_ref(),
|
||||
];
|
||||
assert_eq!(photocraft_cli::run(args, &mut stdout, &mut stderr), 1);
|
||||
let error = match failure {
|
||||
"missing-set" => "missing set",
|
||||
"ambiguous-set" => "ambiguous action call set",
|
||||
_ => "missing from set",
|
||||
};
|
||||
assert!(String::from_utf8_lossy(&stderr).contains(error), "{call}: {}", String::from_utf8_lossy(&stderr));
|
||||
assert!(!output.exists());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,9 +44,14 @@ pub struct ImportedSet {
|
||||
}
|
||||
|
||||
/// Give imported actions globally unique playback names while keeping calls bound to their physical set.
|
||||
/// Explicit set references win over caller-local names; ambiguous cross-set calls are refused.
|
||||
/// Explicit archive scopes never fall back to another set; external scopes stay unrewritten.
|
||||
/// The caller owns the uncommitted import, so a refusal never changes a live library.
|
||||
pub fn normalize_import(imp: &mut Imported, reserved: impl IntoIterator<Item = String>) -> std::result::Result<Vec<String>, String> {
|
||||
/// `allow_external_calls` is false for a standalone CLI archive and true when importing into a session namespace.
|
||||
pub fn normalize_import(
|
||||
imp: &mut Imported,
|
||||
reserved: impl IntoIterator<Item = String>,
|
||||
allow_external_calls: bool,
|
||||
) -> std::result::Result<Vec<String>, String> {
|
||||
let mut set_for = vec![0usize; imp.actions.len()];
|
||||
for (index, set) in imp.sets.iter().enumerate() {
|
||||
set_for.get_mut(set.actions.clone()).ok_or_else(|| "invalid imported set range".to_string())?.fill(index);
|
||||
@@ -87,14 +92,10 @@ pub fn normalize_import(imp: &mut Imported, reserved: impl IntoIterator<Item = S
|
||||
};
|
||||
for key in keys {
|
||||
if let Some(target) = params.get(*key).and_then(Value::as_str) {
|
||||
let scope = params
|
||||
.get(format!("{key}Set"))
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| params.get("set").and_then(Value::as_str))
|
||||
.and_then(|name| imp.sets.iter().position(|set| set.name == name))
|
||||
.and_then(|index| renamed.get(index))
|
||||
.unwrap_or(local);
|
||||
let to = if let Some(to) = scope.get(target) {
|
||||
let scope = params.get(format!("{key}Set")).and_then(Value::as_str).or_else(|| params.get("set").and_then(Value::as_str));
|
||||
let to = if let Some(scope) = scope {
|
||||
scoped_call_target(&imp.sets, &renamed, scope, target, allow_external_calls)?
|
||||
} else if let Some(to) = local.get(target) {
|
||||
Some(to)
|
||||
} else {
|
||||
match global.get(target) {
|
||||
@@ -115,6 +116,26 @@ pub fn normalize_import(imp: &mut Imported, reserved: impl IntoIterator<Item = S
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Resolve only an identified physical archive scope, preserving external/deferred references.
|
||||
fn scoped_call_target<'a>(
|
||||
sets: &[ImportedSet],
|
||||
renamed: &'a [std::collections::HashMap<String, String>],
|
||||
scope: &str,
|
||||
target: &str,
|
||||
allow_external_calls: bool,
|
||||
) -> std::result::Result<Option<&'a String>, String> {
|
||||
let mut matching = sets.iter().enumerate().filter(|(_, set)| set.name == scope);
|
||||
let index = match matching.next() {
|
||||
Some((index, _)) => index,
|
||||
None if allow_external_calls => return Ok(None),
|
||||
None => return Err(format!("action call references missing set `{scope}`")),
|
||||
};
|
||||
if matching.next().is_some() {
|
||||
return Err(format!("ambiguous action call set `{scope}`"));
|
||||
}
|
||||
renamed.get(index).and_then(|names| names.get(target)).map(Some).ok_or_else(|| format!("action call target `{target}` is missing from set `{scope}`"))
|
||||
}
|
||||
|
||||
/// Retain an unsupported event's ID kind and descriptor for later export without executing it.
|
||||
fn photoshop_step(item: &AtnItem, label: String) -> (String, Value) {
|
||||
let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes()));
|
||||
|
||||
@@ -94,7 +94,8 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if old_rows.checked_add(new_rows).is_none_or(|count| count > super::atn::MAX_SETS) {
|
||||
return Err(bad(cmd, "too many action set rows"));
|
||||
}
|
||||
let names = super::normalize_import(&mut imp, s.actions.list.iter().filter(keep).map(|action| action.name.clone())).map_err(|error| bad(cmd, error))?;
|
||||
let names =
|
||||
super::normalize_import(&mut imp, s.actions.list.iter().filter(keep).map(|action| action.name.clone()), true).map_err(|error| bad(cmd, error))?;
|
||||
let keys = imp.function_keys.clone();
|
||||
let steps: usize = imp.actions.iter().map(|action| action.steps.len()).sum();
|
||||
let added = imp.actions;
|
||||
|
||||
@@ -118,7 +118,7 @@ fn portable_conditional_branches_retain_independent_set_scopes() {
|
||||
let mut inherited = projected.clone();
|
||||
inherited.actions[2].steps[0].1["thenSet"] = serde_json::Value::Null;
|
||||
inherited.actions[2].steps[0].1["set"] = json!("A");
|
||||
atn_cmds::normalize_import(&mut inherited, std::iter::empty()).unwrap();
|
||||
atn_cmds::normalize_import(&mut inherited, std::iter::empty(), false).unwrap();
|
||||
assert_eq!(inherited.actions[2].steps[0].1["then"], "Finish", "null branch scope inherits the shared set, like the writer");
|
||||
}
|
||||
let mut session = Session::new();
|
||||
@@ -143,3 +143,26 @@ fn portable_conditional_shared_scope_keeps_the_existing_command_shape() {
|
||||
assert_eq!(imported.actions[0].steps[0].1, params);
|
||||
}
|
||||
}
|
||||
|
||||
/// An out-of-archive scope still targets an existing library action after local names collide.
|
||||
#[test]
|
||||
fn imported_external_set_call_is_not_rewritten_to_an_archive_local_namesake() {
|
||||
use photocraft_engine::atn_cmds;
|
||||
let caller = Action::new("Caller", vec![("actions.play".into(), json!({"action":"Finish","set":"External"}))]);
|
||||
let local = finish("From B");
|
||||
let bytes = atn_cmds::export("B", &[&local, &caller], &[], false).unwrap().0;
|
||||
let mut deferred = atn_cmds::import(&bytes).unwrap();
|
||||
atn_cmds::normalize_import(&mut deferred, ["Finish".to_string()], true).unwrap();
|
||||
assert_ne!(deferred.actions[0].name, "Finish");
|
||||
assert_eq!(deferred.actions[1].steps[0].1, json!({"action":"Finish","set":"External"}), "deferred reference remains intact");
|
||||
let mut session = Session::new();
|
||||
session.execute("file.new", json!({"width":4,"height":4})).unwrap();
|
||||
let mut external = finish("From External");
|
||||
external.set = Some("External".into());
|
||||
session.actions.list.push(external);
|
||||
session.execute("actions.load", json!({"data":photocraft_engine::paint::tile::b64_encode(&bytes)})).unwrap();
|
||||
let result = session.execute("actions.play", json!({"action":"Caller"})).unwrap();
|
||||
assert!(result.get("failed").is_none(), "{result}");
|
||||
assert!(session.active().unwrap().doc.layers.iter().any(|layer| layer.name == "From External"));
|
||||
assert!(!session.active().unwrap().doc.layers.iter().any(|layer| layer.name == "From B"));
|
||||
}
|
||||
Reference in new issue
Block a user