spreadsheet-kit 0.11.1

Core spreadsheet automation primitives — shared types, edit normalization, and session traits for agent-facing surfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Unit and integration tests for the replace-in-formulas CLI command.

#![cfg(feature = "recalc")]

use anyhow::Result;
use serde_json::Value;
use spreadsheet_kit::model::FormulaParsePolicy;
use std::path::PathBuf;
use tempfile::tempdir;

mod support;

fn create_formula_workbook(workspace: &support::TestWorkspace, name: &str) -> PathBuf {
    workspace.create_workbook(name, |book| {
        let sheet = book.get_sheet_by_name_mut("Sheet1").unwrap();
        // Row 1: headers
        sheet.get_cell_mut("A1").set_value("Label");
        sheet.get_cell_mut("B1").set_value("Value");
        // Row 2: formula cells
        sheet.get_cell_mut("A2").set_value("Sum");
        sheet
            .get_cell_mut("B2")
            .set_formula("SUM(C2:C10)".to_string());
        // Row 3: another formula cell
        sheet.get_cell_mut("A3").set_value("Avg");
        sheet
            .get_cell_mut("B3")
            .set_formula("AVERAGE(C2:C10)".to_string());
        // Row 4: formula referencing Sheet1
        sheet.get_cell_mut("A4").set_value("Ref");
        sheet
            .get_cell_mut("B4")
            .set_formula("Sheet1!D5+Sheet1!D6".to_string());
        // Row 5: literal value (should NOT be touched)
        sheet.get_cell_mut("A5").set_value("Literal");
        sheet.get_cell_mut("B5").set_value("SUM(C2:C10)");
    })
}

// ── Core unit tests ──────────────────────────────────────────────────────────

#[test]
fn replace_plain_text_in_formula_body() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "plain.xlsx");

    // Copy to temp file for mutation
    let tmp = tempdir().unwrap();
    let work = tmp.path().join("plain.xlsx");
    std::fs::copy(&path, &work).unwrap();

    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: "C2:C10".to_string(),
        replace: "D2:D20".to_string(),
        range: None,
        regex: false,
        case_sensitive: true,
    };

    let result = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Off).unwrap();

    assert_eq!(
        result.formulas_changed, 2,
        "SUM and AVERAGE both reference C2:C10"
    );
    assert!(result.formulas_checked >= 3, "at least 3 formula cells");
    assert!(!result.samples.is_empty());

    // Verify the formulas were updated
    let book = umya_spreadsheet::reader::xlsx::read(&work).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();

    let b2 = sheet.get_cell("B2").unwrap();
    assert_eq!(b2.get_formula(), "SUM(D2:D20)");

    let b3 = sheet.get_cell("B3").unwrap();
    assert_eq!(b3.get_formula(), "AVERAGE(D2:D20)");

    // B5 is a literal value, should NOT be changed
    let b5 = sheet.get_cell("B5").unwrap();
    assert_eq!(b5.get_value(), "SUM(C2:C10)");
}

#[test]
fn replace_regex_mode() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "regex.xlsx");

    let tmp = tempdir().unwrap();
    let work = tmp.path().join("regex.xlsx");
    std::fs::copy(&path, &work).unwrap();

    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: r"Sheet1!D(\d+)".to_string(),
        replace: "Sheet2!E$1".to_string(),
        range: None,
        regex: true,
        case_sensitive: true,
    };

    let result = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Off).unwrap();

    assert_eq!(result.formulas_changed, 1, "only B4 references Sheet1!D");

    let book = umya_spreadsheet::reader::xlsx::read(&work).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    let b4 = sheet.get_cell("B4").unwrap();
    assert_eq!(b4.get_formula(), "Sheet2!E5+Sheet2!E6");
}

#[test]
fn no_op_when_pattern_absent() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "noop.xlsx");

    let tmp = tempdir().unwrap();
    let work = tmp.path().join("noop.xlsx");
    std::fs::copy(&path, &work).unwrap();

    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: "NONEXISTENT_FUNCTION".to_string(),
        replace: "REPLACEMENT".to_string(),
        range: None,
        regex: false,
        case_sensitive: true,
    };

    let result = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Off).unwrap();

    assert_eq!(result.formulas_changed, 0);
    assert!(
        result
            .warnings
            .iter()
            .any(|w: &String| w.contains("WARN_NO_MATCH"))
    );
}

#[test]
fn range_scoped_replace_touches_only_target_area() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "scoped.xlsx");

    let tmp = tempdir().unwrap();
    let work = tmp.path().join("scoped.xlsx");
    std::fs::copy(&path, &work).unwrap();

    // Only target B2 (not B3 or B4)
    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: "C2:C10".to_string(),
        replace: "X1:X5".to_string(),
        range: Some("B2:B2".to_string()),
        regex: false,
        case_sensitive: true,
    };

    let result = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Off).unwrap();

    assert_eq!(result.formulas_changed, 1, "only B2 is in the range");

    let book = umya_spreadsheet::reader::xlsx::read(&work).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();

    // B2 changed
    assert_eq!(sheet.get_cell("B2").unwrap().get_formula(), "SUM(X1:X5)");
    // B3 unchanged (outside range)
    assert_eq!(
        sheet.get_cell("B3").unwrap().get_formula(),
        "AVERAGE(C2:C10)"
    );
}

#[test]
fn case_insensitive_plain_text_replace() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "case.xlsx");

    let tmp = tempdir().unwrap();
    let work = tmp.path().join("case.xlsx");
    std::fs::copy(&path, &work).unwrap();

    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: "sum".to_string(),
        replace: "SUMPRODUCT".to_string(),
        range: None,
        regex: false,
        case_sensitive: false,
    };

    let result = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Off).unwrap();

    assert_eq!(
        result.formulas_changed, 1,
        "SUM matches 'sum' case-insensitively"
    );

    let book = umya_spreadsheet::reader::xlsx::read(&work).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    assert_eq!(
        sheet.get_cell("B2").unwrap().get_formula(),
        "SUMPRODUCT(C2:C10)"
    );
}

#[test]
fn parse_policy_fail_validates_all_replacements_not_just_samples() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = workspace.create_workbook("fail-all.xlsx", |book| {
        let sheet = book.get_sheet_by_name_mut("Sheet1").unwrap();
        for row in 1..=30 {
            sheet
                .get_cell_mut((2, row))
                .set_formula("SUM(C2:C10)".to_string());
        }
    });

    let tmp = tempdir().unwrap();
    let work = tmp.path().join("fail-all.xlsx");
    std::fs::copy(&path, &work).unwrap();

    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: "SUM(".to_string(),
        replace: "SUM((".to_string(),
        range: None,
        regex: false,
        case_sensitive: true,
    };

    let err = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Fail)
        .expect_err("invalid replacement formulas should fail under fail policy");
    assert!(
        err.to_string().contains("failed parse"),
        "unexpected error: {err}"
    );
}

#[test]
fn parse_policy_warn_skips_invalid_replacements_and_reports_diagnostics() {
    use spreadsheet_kit::tools::fork::{ReplaceInFormulasOp, apply_replace_in_formulas_to_file};

    let workspace = support::TestWorkspace::new();
    let path = workspace.create_workbook("warn-invalid.xlsx", |book| {
        let sheet = book.get_sheet_by_name_mut("Sheet1").unwrap();
        for row in 1..=30 {
            sheet
                .get_cell_mut((2, row))
                .set_formula("SUM(C2:C10)".to_string());
        }
    });

    let tmp = tempdir().unwrap();
    let work = tmp.path().join("warn-invalid.xlsx");
    std::fs::copy(&path, &work).unwrap();

    let op = ReplaceInFormulasOp {
        sheet_name: "Sheet1".to_string(),
        find: "SUM(".to_string(),
        replace: "SUM((".to_string(),
        range: None,
        regex: false,
        case_sensitive: true,
    };

    let result = apply_replace_in_formulas_to_file(&work, &op, FormulaParsePolicy::Warn)
        .expect("warn policy should not fail");

    assert_eq!(result.formulas_checked, 30);
    assert_eq!(
        result.formulas_changed, 0,
        "invalid replacements should be skipped"
    );
    let diagnostics = result
        .formula_parse_diagnostics
        .expect("warn policy should return diagnostics");
    assert!(diagnostics.total_errors >= 30);
}

// ── CLI integration tests ────────────────────────────────────────────────────

#[tokio::test(flavor = "current_thread")]
async fn cli_dry_run_preview_shows_expected_changes() -> Result<()> {
    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "dry_run.xlsx");

    let result = spreadsheet_kit::cli::commands::write::replace_in_formulas(
        path.clone(),
        "Sheet1".to_string(),
        "C2:C10".to_string(),
        "D2:D20".to_string(),
        None,
        false,
        true,
        true,  // dry_run
        false, // in_place
        None,  // output
        false, // force
        None,  // formula_parse_policy
    )
    .await?;

    let obj = result.as_object().unwrap();
    assert_eq!(obj.get("would_change").and_then(Value::as_bool), Some(true));
    assert!(obj.get("formulas_changed").and_then(Value::as_u64).unwrap() >= 2);

    let samples = obj.get("samples").and_then(Value::as_array).unwrap();
    assert!(!samples.is_empty());

    // Verify original file is NOT modified (dry run)
    let book = umya_spreadsheet::reader::xlsx::read(&path).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    assert_eq!(sheet.get_cell("B2").unwrap().get_formula(), "SUM(C2:C10)");

    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn cli_in_place_writes_expected_formulas() -> Result<()> {
    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "inplace.xlsx");

    let result = spreadsheet_kit::cli::commands::write::replace_in_formulas(
        path.clone(),
        "Sheet1".to_string(),
        "C2:C10".to_string(),
        "D2:D20".to_string(),
        None,
        false,
        true,
        false, // dry_run
        true,  // in_place
        None,
        false,
        None,
    )
    .await?;

    let obj = result.as_object().unwrap();
    assert_eq!(obj.get("changed").and_then(Value::as_bool), Some(true));
    assert!(obj.get("formulas_changed").and_then(Value::as_u64).unwrap() >= 2);

    // Verify source file IS modified
    let book = umya_spreadsheet::reader::xlsx::read(&path).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    assert_eq!(sheet.get_cell("B2").unwrap().get_formula(), "SUM(D2:D20)");
    assert_eq!(
        sheet.get_cell("B3").unwrap().get_formula(),
        "AVERAGE(D2:D20)"
    );

    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn cli_in_place_fail_policy_rejects_without_mutating_source() -> Result<()> {
    let workspace = support::TestWorkspace::new();
    let path = workspace.create_workbook("inplace-fail-policy.xlsx", |book| {
        let sheet = book.get_sheet_by_name_mut("Sheet1").unwrap();
        for row in 1..=30 {
            sheet
                .get_cell_mut((2, row))
                .set_formula("SUM(C2:C10)".to_string());
        }
    });

    let before = std::fs::read(&path)?;

    let err = spreadsheet_kit::cli::commands::write::replace_in_formulas(
        path.clone(),
        "Sheet1".to_string(),
        "SUM(".to_string(),
        "SUM((".to_string(),
        None,
        false,
        true,
        false,
        true,
        None,
        false,
        Some(FormulaParsePolicy::Fail),
    )
    .await
    .expect_err("fail policy should reject invalid replacement formulas");

    assert!(
        err.to_string().contains("failed parse"),
        "unexpected error: {err}"
    );

    let after = std::fs::read(&path)?;
    assert_eq!(
        before, after,
        "source workbook must remain unchanged on failure"
    );

    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn cli_output_mode_writes_to_target() -> Result<()> {
    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "output.xlsx");
    let target = workspace.path("output_result.xlsx");

    let result = spreadsheet_kit::cli::commands::write::replace_in_formulas(
        path.clone(),
        "Sheet1".to_string(),
        "Sheet1!".to_string(),
        "Sheet2!".to_string(),
        None,
        false,
        true,
        false,
        false,
        Some(target.clone()),
        false,
        None,
    )
    .await?;

    let obj = result.as_object().unwrap();
    assert_eq!(obj.get("changed").and_then(Value::as_bool), Some(true));

    // Source unchanged
    let book = umya_spreadsheet::reader::xlsx::read(&path).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    assert_eq!(
        sheet.get_cell("B4").unwrap().get_formula(),
        "Sheet1!D5+Sheet1!D6"
    );

    // Target has the change
    let book = umya_spreadsheet::reader::xlsx::read(&target).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    assert_eq!(
        sheet.get_cell("B4").unwrap().get_formula(),
        "Sheet2!D5+Sheet2!D6"
    );

    Ok(())
}

#[tokio::test(flavor = "current_thread")]
async fn cli_range_scoped_replace_only_modifies_target_area() -> Result<()> {
    let workspace = support::TestWorkspace::new();
    let path = create_formula_workbook(&workspace, "range_scope.xlsx");

    let result = spreadsheet_kit::cli::commands::write::replace_in_formulas(
        path.clone(),
        "Sheet1".to_string(),
        "C2:C10".to_string(),
        "X1:X5".to_string(),
        Some("B2:B2".to_string()),
        false,
        true,
        false,
        true,
        None,
        false,
        None,
    )
    .await?;

    let obj = result.as_object().unwrap();
    assert_eq!(obj.get("formulas_changed").and_then(Value::as_u64), Some(1));

    let book = umya_spreadsheet::reader::xlsx::read(&path).unwrap();
    let sheet = book.get_sheet_by_name("Sheet1").unwrap();
    assert_eq!(sheet.get_cell("B2").unwrap().get_formula(), "SUM(X1:X5)");
    assert_eq!(
        sheet.get_cell("B3").unwrap().get_formula(),
        "AVERAGE(C2:C10)"
    );

    Ok(())
}

// ── CLI parse tests ──────────────────────────────────────────────────────────

#[test]
fn parses_replace_in_formulas_arguments() {
    use clap::Parser;
    use spreadsheet_kit::cli::Cli;

    let cli = Cli::try_parse_from([
        "agent-spreadsheet",
        "replace-in-formulas",
        "data.xlsx",
        "Sheet1",
        "--find",
        "$64",
        "--replace",
        "$65",
        "--range",
        "A1:Z100",
        "--regex",
        "--dry-run",
    ])
    .expect("parse replace-in-formulas");

    match cli.command {
        spreadsheet_kit::cli::Commands::ReplaceInFormulas {
            file,
            sheet,
            find,
            replace,
            range,
            regex,
            case_sensitive,
            dry_run,
            in_place,
            output,
            force,
            formula_parse_policy,
        } => {
            assert_eq!(file, std::path::PathBuf::from("data.xlsx"));
            assert_eq!(sheet, "Sheet1");
            assert_eq!(find, "$64");
            assert_eq!(replace, "$65");
            assert_eq!(range, Some("A1:Z100".to_string()));
            assert!(regex);
            assert!(case_sensitive.is_none());
            assert!(dry_run);
            assert!(!in_place);
            assert!(output.is_none());
            assert!(!force);
            assert!(formula_parse_policy.is_none());
        }
        other => panic!("unexpected command: {other:?}"),
    }
}

#[test]
fn parses_replace_in_formulas_output_mode() {
    use clap::Parser;
    use spreadsheet_kit::cli::Cli;

    let cli = Cli::try_parse_from([
        "agent-spreadsheet",
        "replace-in-formulas",
        "data.xlsx",
        "Sheet1",
        "--find",
        "SUM",
        "--replace",
        "SUMIFS",
        "--output",
        "fixed.xlsx",
        "--force",
        "--formula-parse-policy",
        "warn",
    ])
    .expect("parse replace-in-formulas output mode");

    match cli.command {
        spreadsheet_kit::cli::Commands::ReplaceInFormulas {
            dry_run,
            in_place,
            output,
            force,
            formula_parse_policy,
            ..
        } => {
            assert!(!dry_run);
            assert!(!in_place);
            assert_eq!(output, Some(std::path::PathBuf::from("fixed.xlsx")));
            assert!(force);
            assert!(matches!(
                formula_parse_policy,
                Some(spreadsheet_kit::model::FormulaParsePolicy::Warn)
            ));
        }
        other => panic!("unexpected command: {other:?}"),
    }
}