Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Ignore a leading UTF-8 BOM in variable data set CSV import (#6485)

NetterSilvere66941bde17c
diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs
index 630826970..0a49d780d 100644
--- a/crates/engine/src/variables_cmds.rs
+++ b/crates/engine/src/variables_cmds.rs
@@ -286,6 +286,8 @@ fn import_data_sets(s: &mut Session, p: &Value) -> Result<Value> {
/// file beneath its read root and hands the text over (#3216).
pub fn import_data_sets_text(s: &mut Session, text: &str, p: &Value) -> Result<Value> {
let delim = p.get("delimiter").and_then(Value::as_str).and_then(|d| d.bytes().next()).unwrap_or(b',');
+ // Excel's "CSV UTF-8" starts with a byte order mark that is not part of the first header cell.
+ let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone();
let mut records = csv_records(text).filter(|r| !r.trim().is_empty());
let header: Vec<String> = records.next().map(|h| split_csv(h, delim)).unwrap_or_default();
diff --git a/crates/engine/src/variables_cmds/tests.rs b/crates/engine/src/variables_cmds/tests.rs
index c2a30cab6..8a0c591e7 100644
--- a/crates/engine/src/variables_cmds/tests.rs
+++ b/crates/engine/src/variables_cmds/tests.rs
@@ -136,6 +136,38 @@ fn csv_import_and_apply() {
assert_eq!(text_of(&s, title), "On Sale");
}
+#[test]
+fn csv_import_ignores_utf8_bom() {
+ let dir = tmp("csv-bom");
+ let csv = format!("{dir}/sets.csv");
+
+ // BOM before the `DataSet` name column: sets keep their names.
+ let (mut s, _p, badge, title) = session();
+ s.execute(
+ "image.variables.define",
+ json!({"defs": [
+ {"name": "showBadge", "layer": badge.0, "type": "visibility"},
+ {"name": "headline", "layer": title.0, "type": "textReplacement"},
+ ]}),
+ )
+ .unwrap();
+ std::fs::write(&csv, "\u{feff}DataSet,showBadge,headline\nrow-on,true,On Sale\n").unwrap();
+ let r = s.execute("file.import.variableDataSets", json!({"path": csv})).unwrap();
+ assert_eq!(r["imported"], 1);
+ s.execute("image.applyDataSet", json!({"name": "row-on"})).unwrap();
+ assert!(doc(&s).layer(badge).unwrap().visible);
+ assert_eq!(text_of(&s, title), "On Sale");
+
+ // BOM before a variable column (no name column): the variable is still imported.
+ let (mut s, _p, badge, title) = session();
+ s.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": title.0, "type": "textReplacement"}]})).unwrap();
+ let _ = badge;
+ let r = import_data_sets_text(&mut s, "\u{feff}headline\nHello\n", &json!({})).unwrap();
+ assert_eq!(r["imported"], 1);
+ s.execute("image.applyDataSet", json!({"index": 0})).unwrap();
+ assert_eq!(text_of(&s, title), "Hello");
+}
+
#[test]
fn csv_fields_preserve_unicode_and_quoting() {
for (line, delimiter, expected) in [