Repository navigation
CSV exports: a field that starts with =, +, - or @ stays text in a spreadsheet (#12728) #12729
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| //! CSV text fields, as every SolidCraft export writes them and the parameter import reads them. | ||
| //! | ||
| //! A spreadsheet reads a field that starts with `=`, `+`, `-` or `@` as a formula, so a part | ||
| //! numbered `=1+1` would show `2`. A field like that is written with a `'` first, which | ||
| //! spreadsheets show as text (OWASP's CSV Injection page). [`unguard`] takes the `'` off again | ||
| //! when SolidCraft reads its own file back. | ||
|
|
||
| use std::borrow::Cow; | ||
|
|
||
| /// The first characters that make a spreadsheet read a field as a formula, from OWASP's list. | ||
| /// The full-width forms act as formulas in some locales, such as Japanese, so they are here too. | ||
| const FORMULA_STARTS: [char; 11] = ['=', '+', '-', '@', '\t', '\r', '\n', '=', '+', '-', '@']; | ||
|
|
||
| /// What makes a field need quotes: a separator (`;` as well as `,`, since a spreadsheet set to | ||
| /// `;` splits there and the new cell could start a formula), a quote, a tab or a line break. | ||
| const NEEDS_QUOTES: [char; 6] = [',', ';', '"', '\t', '\r', '\n']; | ||
|
|
||
| /// A text field, quoted only when it needs quotes. | ||
| pub fn field(text: &str) -> String { | ||
| let text = guard(text); | ||
| if text.contains(NEEDS_QUOTES) { quote(&text) } else { text.into_owned() } | ||
| } | ||
|
|
||
| /// A text field, always in quotes. | ||
| pub fn quoted(text: &str) -> String { | ||
| quote(&guard(text)) | ||
| } | ||
|
|
||
| /// A field as SolidCraft wrote it, with the `'` that [`field`] or [`quoted`] put first taken off. | ||
| /// A field without one is returned as it is. | ||
| pub fn unguard(text: &str) -> &str { | ||
| match text.strip_prefix('\'') { | ||
| Some(rest) if starts_a_formula(rest) => rest, | ||
| _ => text, | ||
| } | ||
| } | ||
|
|
||
| /// `text` with a `'` first when a spreadsheet would read it as a formula. A field that already | ||
| /// starts with `'` and then a formula gets one more, so [`unguard`] gives back exactly what was | ||
| /// written. A whole plain number (`-5`, `+1e-9`) is read as that number, not as a formula, so it | ||
| /// is left as it is. | ||
| fn guard(text: &str) -> Cow<'_, str> { | ||
| if starts_a_formula(text) && !plain_number(text) { Cow::Owned(format!("'{text}")) } else { Cow::Borrowed(text) } | ||
| } | ||
|
|
||
| /// Whether `text`, after any `'` and spaces it starts with, starts as a formula does. Spaces count | ||
| /// because a spreadsheet may take them off as it reads (LibreOffice's "Trim spaces"). | ||
| fn starts_a_formula(text: &str) -> bool { | ||
| text.trim_start_matches(['\'', ' ']).starts_with(FORMULA_STARTS) | ||
| } | ||
|
|
||
| /// A finite number and nothing else, spaces included. Rust's `f64` parsing also takes `inf`, | ||
| /// `infinity` and `NaN` in any case, and none of them is finite. | ||
| fn plain_number(text: &str) -> bool { | ||
| text.parse::<f64>().is_ok_and(f64::is_finite) | ||
| } | ||
|
|
||
| fn quote(text: &str) -> String { | ||
| format!("\"{}\"", text.replace('"', "\"\"")) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "csv_tests.rs"] | ||
| mod tests; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| use super::{FORMULA_STARTS, NEEDS_QUOTES, field, quoted, unguard}; | ||
|
|
||
| #[test] | ||
| fn a_field_a_spreadsheet_would_run_gets_an_apostrophe() { | ||
| for (text, written) in [ | ||
| ("=1+1", "'=1+1"), | ||
| ("+2 for the fit", "'+2 for the fit"), | ||
| ("-5 mm shim", "'-5 mm shim"), | ||
| ("@SUM(1,1)", "\"'@SUM(1,1)\""), | ||
| ("=1+1", "'=1+1"), | ||
| ("+2", "'+2"), | ||
| ("-5", "'-5"), | ||
| ("@x", "'@x"), | ||
| ("\tx", "\"'\tx\""), | ||
| ("\rx", "\"'\rx\""), | ||
| ("\nx", "\"'\nx\""), | ||
| // Already an apostrophe, then a formula: one more, so the import gives back the original. | ||
| ("'=x", "''=x"), | ||
| ("''-x", "'''-x"), | ||
| // Spaces before a formula count: a spreadsheet may take them off. | ||
| (" =x", "' =x"), | ||
| (" -5", "' -5"), | ||
| ("' @x", "'' @x"), | ||
| ] { | ||
| assert_eq!(field(text), written, "{text:?}"); | ||
| assert_eq!(unguard(written.trim_matches('"')), text, "{written:?}"); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_whole_plain_number_stays_a_number() { | ||
| for number in ["-5", "+5", "-0", "0", "1e-9", "-1.5E+3", ".5", "-.5", "5.", "+1e5", "-12.000000000"] { | ||
| assert_eq!(field(number), number, "{number:?}"); | ||
| } | ||
| // Not plain numbers: Rust's parse takes the words, spaces aren't a number's, and one too large isn't finite. | ||
| for text in ["-inf", "+inf", "-infinity", "-NaN", "+nan", "-", "+", "--5", "-5 mm", "-5 ", "-1e400", "-0x10", "-5,5"] { | ||
| assert!(field(text).trim_start_matches('"').starts_with('\''), "{text:?}: {}", field(text)); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn other_fields_are_left_as_they_are() { | ||
| for text in ["", "Plate", "PL-100", "a=b", "x+1", "'quoted' word", "'", "''", "5 mm", " 5", "é=", "μ-5"] { | ||
| assert_eq!(field(text), text, "{text:?}"); | ||
| assert_eq!(unguard(text), text, "{text:?}"); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_field_with_a_separator_a_quote_or_a_break_is_quoted() { | ||
| assert_eq!(field("Plate, 3 mm"), "\"Plate, 3 mm\""); | ||
| assert_eq!(field("one; two"), "\"one; two\""); | ||
| assert_eq!(field("Pin \"short\""), "\"Pin \"\"short\"\"\""); | ||
| assert_eq!(field("a\tb"), "\"a\tb\""); | ||
| assert_eq!(field("line one\r\nline two"), "\"line one\r\nline two\""); | ||
| assert_eq!(quoted("Plate"), "\"Plate\""); | ||
| assert_eq!(quoted("=A1"), "\"'=A1\""); | ||
| assert_eq!(quoted("-5"), "\"-5\""); | ||
| } | ||
|
|
||
| /// Random fields from an alphabet heavy in what matters: every formula start, apostrophes, quotes, | ||
| /// separators, spaces, digits and the letters of `inf` and `NaN`. Each one reads back exactly, never starts | ||
| /// a formula once written unless it is a whole number, and is quoted whenever it holds a separator. | ||
| #[test] | ||
| fn fuzz_every_field_reads_back_and_never_starts_a_formula() { | ||
| let mut alphabet: Vec<char> = "'''\"\";,.eE0123456789 infaNxé".chars().collect(); | ||
| alphabet.extend(FORMULA_STARTS); | ||
| let mut seed: u64 = 0x9e37_79b9_7f4a_7c15; | ||
| let mut rnd = move || { | ||
| seed ^= seed << 13; | ||
| seed ^= seed >> 7; | ||
| seed ^= seed << 17; | ||
| seed | ||
| }; | ||
| for _ in 0..50_000 { | ||
| let n = (rnd() % 12) as usize; | ||
| let text: String = (0..n).filter_map(|_| alphabet.get((rnd() % alphabet.len() as u64) as usize)).collect(); | ||
| let written = field(&text); | ||
| let inner = match written.strip_prefix('"').and_then(|w| w.strip_suffix('"')) { | ||
| Some(inner) => inner.replace("\"\"", "\""), | ||
| None => written.clone(), | ||
| }; | ||
| assert_eq!(unguard(&inner), text, "{text:?} written as {written:?}"); | ||
| let bare = inner.trim_start_matches(' '); | ||
| assert!(!bare.starts_with(FORMULA_STARTS) || text.parse::<f64>().is_ok_and(f64::is_finite), "{text:?} written as {written:?}"); | ||
| assert!(!text.contains(NEEDS_QUOTES) || written.starts_with('"'), "{text:?} written as {written:?}"); | ||
| assert_eq!(quoted(&text), format!("\"{}\"", inner.replace('"', "\"\"")), "{text:?}"); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -880,7 +880,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> { | |
| c += &format!( | ||
| "{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n", | ||
| Value::from(r.step), | ||
| at.occurrence.replace(',', " "), | ||
| solidcraft_doc::csv::field(&at.occurrence), | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changes a default: Preserve a choice for legacy motion CSV names. Before this change, the usual motion CSV export turned an occurrence named As per path instructions: “Flag any change to something a user already relies on: a default setting or preference value, what a command or tool does when used the usual way.”
|
||
| o[0], | ||
| o[1], | ||
| o[2], | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -400,6 +400,27 @@ fn csv_and_json_round_trip() { | |
| let _ = std::fs::remove_dir_all(&dir); | ||
| } | ||
|
|
||
| /// A value a spreadsheet would run as a formula is exported as text, with a `'` first, and | ||
| /// imports back as it was (#12728). A plain number keeps its sign, and `;` makes a field quoted. | ||
| #[test] | ||
| fn csv_keeps_formulas_as_text_and_imports_them_back() { | ||
| let mut s = Session::default(); | ||
| let rows = [("d3", "4", "plain"), ("a", "=d3", "+2 for the fit"), ("b", "=5", "'=kept"), ("c", "-5 mm", "@x"), ("e", "6", "one; two")]; | ||
| for (name, expression, comment) in rows { | ||
| run(&mut s, "parameters.add", json!({"name": name, "expression": expression, "comment": comment})); | ||
| } | ||
| let csv = run(&mut s, "parameters.export", json!({"format": "csv"}))["text"].as_str().unwrap_or_default().to_string(); | ||
| for written in [",'=d3,", ",'+2 for the fit,", ",'=5,", ",''=kept,", ",'-5 mm,-5,'@x,", ",\"one; two\","] { | ||
| assert!(csv.contains(written), "{written}: {csv}"); | ||
|
Comment on lines
+412
to
+414
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changes a default: Do not silently change the existing parameter CSV result. Before this change, the usual As per path instructions: “Flag any change to something a user already relies on: a default setting or preference value, what a command or tool does when used the usual way.”
|
||
| } | ||
| let mut t = Session::default(); | ||
| run(&mut t, "parameters.import", json!({"text": csv})); | ||
| for (name, _, comment) in rows { | ||
| let (before, after) = (s.doc.param(name), t.doc.param(name)); | ||
| assert_eq!(after.map(|p| (p.expr.as_str(), p.comment.as_str())), before.map(|p| (p.expr.as_str(), comment)), "{name}: {csv}"); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn csv_round_trips_comments_with_line_breaks() { | ||
| for comment in ["line one\nline two", "\r\nfirst, \"quoted\"\r\n\r\nlast\r\n", "one\rtwo"] { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -102,6 +102,13 @@ an unchanged field cannot reinterpret it. Computed sizes and tolerances keep the | |
| precision when written back into editable fields, independently of display precision. | ||
|
|
||
| Parameters export to and import from CSV or JSON (`parameters.export`, `parameters.import`). | ||
| In a CSV, a value that a spreadsheet would run as a formula is written with a `'` before it, so the | ||
| spreadsheet shows it as text. That is a value that starts with `=`, `+`, `-` or `@`, their full-width | ||
| forms, a tab or a line break, after any spaces and `'`; a plain number such as `-5` is left as it is. | ||
| The import takes the `'` off again. A spreadsheet that saves the file again as CSV can drop the `'` | ||
| (Excel does), so export again from SolidCraft instead of passing that file on. Earlier versions of | ||
| SolidCraft wrote every value unchanged, so in a CSV from one of them, a value whose first character | ||
| really was a `'` typed before a formula character (`'=x`) now imports without it (`=x`). | ||
|
Comment on lines
+108
to
+111
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Changes a default: Preserve literal apostrophes in older CSV imports. Before this change, importing an older CSV field containing As per path instructions: “Flag any change to something a user already relies on: a default setting or preference value, what a command or tool does when used the usual way.”
|
||
| **Configurations** (`config.*`) keep a table of rows, each with its own parameter values and | ||
| suppressed features, physical materials and body appearances, switched with `config.activate`. | ||
| The table's Library picker selects material or appearance values. Choose **Follow material** | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changes a default: Account for changed BOM CSV field values.
Before this change, the usual BOM CSV export wrote a part number
=1+1as"=1+1".solidcraft_doc::csv::quotednow writes it as"'=1+1". No setting preserves the old CSV value for BOM consumers; JSON is a different format. The PR description saysChanges a default: no. Provide a compatible CSV choice, or identify this as a default change and address affected integrations. (raw.githubusercontent.com)As per path instructions: “Flag any change to something a user already relies on: a default setting or preference value, what a command or tool does when used the usual way.”
Source: Path instructions