omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
//! A1-notation-within-one-sheet → numeric [`GridRange`] conversion (issue
//! #1643).
//!
//! `a1.rs` deliberately never parses A1 grammar: every existing verb passes
//! an A1 *string* straight to the `values.*` endpoints, which resolve it
//! server-side, so a client-side parser could only ever reject something
//! the server would have accepted. The formatting, validation and
//! protection verbs are different: `repeatCell`, `updateBorders`,
//! `mergeCells`, `unmergeCells`, `setDataValidation` and
//! `addProtectedRange` all address a [`GridRange`] — a numeric,
//! zero-based, half-open rectangle — because that is the wire shape, not a
//! preference. Parsing is required here, not optional, exactly as
//! `structure.rs::dimension_range`'s 1-based-to-0-based conversion is
//! required for `insertDimension`. The same rule applies: one pure,
//! independently-tested conversion, never inlined at a call site.
//!
//! **A deliberately bounded grammar**, matching this feature's general
//! stance of a curated surface over full API coverage: a single cell
//! (`A1`), a bounded rectangle (`A1:D20`), a whole column or column span
//! (`A:A`, `A:D`), a whole row or row span (`5:5`, `5:20`), and a
//! column open-ended downward from a starting cell (`A5:A`). Anything else
//! — mixed forms Sheets itself may accept, like a row open-ended
//! rightward — is refused with a message naming the supported forms,
//! rather than guessed at.
//!
//! Takes the sheet's numeric id separately, like every other structural
//! verb's `--sheet` flag: the range string itself never carries a sheet
//! prefix here.

use crate::drive::sheets::a1;
use crate::drive::sheets::types::{GridRange, Sheet, Spreadsheet, ValueRange};

/// What one `:`-delimited token names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CellRef {
    /// A full cell reference (`A1`): zero-based column, zero-based row.
    Cell(i64, i64),
    /// A bare column letter (`A`, `AA`): zero-based column.
    Column(i64),
    /// A bare row number (`5`): zero-based row.
    Row(i64),
}

/// Converts `A`, `B`, … `Z`, `AA`, … into a zero-based column index.
///
/// Base-26 with no zero digit — `Z` is 25, `AA` is 26, not 0 — which is why
/// this can't be a direct radix conversion.
fn column_letters_to_index(letters: &str) -> Option<i64> {
    if letters.is_empty() || !letters.bytes().all(|b| b.is_ascii_alphabetic()) {
        return None;
    }
    let mut index: i64 = 0;
    for b in letters.bytes() {
        let digit = i64::from(b.to_ascii_uppercase() - b'A' + 1);
        index = index.checked_mul(26)?.checked_add(digit)?;
    }
    Some(index - 1)
}

/// Zero-based column index → A1 letters (`0` → `"A"`, `26` → `"AA"`) — the
/// inverse of [`column_letters_to_index`], colocated with it so both
/// directions of the conversion share one tested implementation.
pub(crate) fn column_index_to_letters(mut index: i64) -> String {
    let mut letters = Vec::new();
    loop {
        letters.push((b'A' + (index % 26) as u8) as char);
        index = index / 26 - 1;
        if index < 0 {
            break;
        }
    }
    letters.iter().rev().collect()
}

/// Every non-blank cell within a `values.get` read, as its A1 address —
/// **never its value** (ADR-0083 §6: "counts and A1 locations, never
/// contents"). `row_offset`/`col_offset` are the read range's own start
/// row/column, since the API indexes a read relative to the range it was
/// asked for, not the sheet.
///
/// Shared by `paste.rs` and `auto_fill.rs` (previously two independent
/// copies) and `text_to_columns.rs`; a third private copy would let
/// ADR-0083 §6's "never a value" rule drift into a per-file convention
/// instead of one tested implementation. Whether the top-left/anchor cell
/// is included in the result is the caller's own decision — every existing
/// caller's written extent covers its whole read, so this function makes
/// no exception for it.
pub(crate) fn non_blank_locations(
    values: &ValueRange,
    row_offset: i64,
    col_offset: i64,
) -> Vec<String> {
    let mut locations = Vec::new();
    for (row_idx, row) in values.values.iter().enumerate() {
        for (col_idx, cell) in row.iter().enumerate() {
            let is_blank = cell.is_null() || cell.as_str().is_some_and(str::is_empty);
            if is_blank {
                continue;
            }
            locations.push(format!(
                "{}{}",
                column_index_to_letters(col_idx as i64 + col_offset),
                row_idx as i64 + row_offset + 1
            ));
        }
    }
    locations
}

/// Warns when a selected column span is narrower than the sheet's
/// allocated width — reordering (`sort-range`/`randomize-range`) only part
/// of a wider table can detach a record's other columns from the row it
/// moves with. `verb` names the operation in the warning text (`"sorting"`,
/// `"randomizing"`); `start`/`end` are the selected range's zero-based,
/// end-exclusive column bounds; `allocated` is the sheet's own
/// `gridProperties.columnCount`, when the workbook metadata carried one.
///
/// Shared by `sort_range.rs` and `randomize_range.rs` (previously a private
/// copy in the former) — the same "one tested implementation, not a
/// per-file convention" reasoning [`non_blank_locations`]'s doc comment
/// gives.
pub(crate) fn width_warning(
    verb: &str,
    start: i64,
    end: i64,
    allocated: Option<i64>,
) -> Option<String> {
    match allocated {
        Some(columns) if start == 0 && end >= columns => None,
        Some(columns) => Some(format!(
            "selected columns {start}..{end} of the sheet's {columns} allocated columns; if data exists outside the selection, {verb} can separate records from their other columns"
        )),
        None => Some(format!(
            "the selected range may be narrower than its rows; {verb} can separate records from columns outside the selection"
        )),
    }
}

/// Renders a physical-row-reorder's warning/summary/reference-caveat lines
/// — the width warning first, when there is one, then the summary, then an
/// optional operation-specific caveat, then the out-of-range-references line
/// (ADR-0083 §6). `verb` is the same gerund [`width_warning`] takes
/// (`"sorting"`, `"randomizing"`) and only appears in the reference-caveat
/// line's *not-yet-changed* tense (`"... after {verb}"`); `order_caveat`,
/// when present, is inserted between the summary and that line
/// (`randomize-range`'s the-order-can't-be-known caveat has no analog for a
/// deterministic sort).
///
/// Shared by `sort_range.rs`, `randomize_range.rs`, and `filter.rs`'s
/// `set-basic-filter --sort-by` caveat (issue #1996) — the same "one tested
/// implementation, not a per-file convention" reasoning [`width_warning`]'s
/// doc comment gives.
pub(crate) fn reorder_caveat_lines(
    verb: &str,
    summary: String,
    width_warning: Option<&str>,
    changed: bool,
    order_caveat: Option<&str>,
) -> Vec<String> {
    let mut lines = Vec::new();
    if let Some(warning) = width_warning {
        lines.push(format!("Warning: {warning}"));
    }
    lines.push(summary);
    if let Some(caveat) = order_caveat {
        lines.push(format!("  {caveat}"));
    }
    lines.push(if changed {
        "  references outside the range may now observe values from a different row".to_string()
    } else {
        format!(
            "  references outside the range may observe values from a different row after {verb}"
        )
    });
    lines
}

/// The default number of A1 addresses [`truncate_locations`] renders
/// before eliding the rest.
pub(crate) const RENDERED_LOCATION_LIMIT: usize = 50;

/// Joins `items` for a *rendered* line with `separator`, eliding past
/// `limit` (`"{items}{separator}… and N more"`).
///
/// `trim-whitespace --whole-sheet` names every non-blank cell in a tab, so
/// joining its whole list into one line (as every preview did before issue
/// #1844) produces a multi-kilobyte line. Only the rendered line is
/// elided: the structured outcome and the `drivemutation` record keep the
/// full list, so nothing a machine reads is lost.
pub(crate) fn truncate_joined(items: &[String], limit: usize, separator: &str) -> String {
    if items.len() <= limit {
        return items.join(separator);
    }
    format!(
        "{}{separator}… and {} more",
        items[..limit].join(separator),
        items.len() - limit
    )
}

/// [`truncate_joined`] with `", "` as the separator — every bare-address
/// preview's shape.
pub(crate) fn truncate_locations(locations: &[String], limit: usize) -> String {
    truncate_joined(locations, limit, ", ")
}

/// [`truncate_locations`] at [`RENDERED_LOCATION_LIMIT`] — the one
/// rendering path for every address-list preview. #1844 introduced
/// `truncate_locations` for `trim-whitespace`; #1880 adopted this wrapper
/// at every other address-only preview (`auto-fill`, `text-to-columns`,
/// `paste`/`cut-paste`, `delete-named-range`'s referencing-formula list),
/// so a caller never repeats the limit constant. `format.rs`'s
/// `MergeCells` discard list calls [`truncate_joined`] directly with its
/// own separator (`"; "`) and limit (`MERGE_DISCARD_RENDER_LIMIT`, #1999),
/// since each entry there carries a value, not just an address.
pub(crate) fn render_locations(locations: &[String]) -> String {
    truncate_locations(locations, RENDERED_LOCATION_LIMIT)
}

/// Whether every bound of `grid` is set — i.e. it names a fixed rectangle
/// rather than an open-ended column/row span (`A:A`, `5:5`).
pub(crate) fn is_bounded(grid: &GridRange) -> bool {
    grid.start_row_index.is_some()
        && grid.end_row_index.is_some()
        && grid.start_column_index.is_some()
        && grid.end_column_index.is_some()
}

/// The number of cells `grid` covers, or `None` when it is open-ended (see
/// [`is_bounded`]). Saturates rather than overflowing, so a pathological
/// range still compares as "too big" against a cell budget. The one shared
/// count behind `read-cell-format`'s and `merge-cells`' cell budgets, so
/// the two cannot drift in how they measure a range (#2025).
pub(crate) fn cell_count(grid: &GridRange) -> Option<i64> {
    match (
        grid.start_row_index,
        grid.end_row_index,
        grid.start_column_index,
        grid.end_column_index,
    ) {
        (Some(start_row), Some(end_row), Some(start_col), Some(end_col)) => {
            Some((end_row - start_row).saturating_mul(end_col - start_col))
        }
        _ => None,
    }
}

/// A column index that falls outside a [`GridRange`]'s column span, as
/// returned by [`check_column_in_range`]. Carries enough structured data
/// (the offending column plus the range's bounds) for each call site to
/// format its own verb-specific error text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ColumnOutOfRange {
    pub(crate) column: i64,
    pub(crate) start: i64,
    pub(crate) end: Option<i64>,
}

/// Checks whether `column` (an absolute, zero-based sheet column index — 0
/// = column A) falls inside `grid`'s half-open column span `start..end`.
/// An unset `start_column_index` is treated as 0; an unset
/// `end_column_index` is treated as unbounded, so whole-row ranges (e.g.
/// `2:5`) admit any column at or after `start`. The single shared home for
/// the bounds check `sort-range --sort-by`, `delete-duplicates
/// --comparison-column` and the slicer `--column` (#1945) each re-derived
/// independently (#1989).
pub(crate) fn check_column_in_range(column: i64, grid: &GridRange) -> Result<(), ColumnOutOfRange> {
    let start = grid.start_column_index.unwrap_or(0);
    let end = grid.end_column_index;
    let inside = column >= start && end.is_none_or(|end| column < end);
    if inside {
        Ok(())
    } else {
        Err(ColumnOutOfRange { column, start, end })
    }
}

/// Finds a sheet's numeric id by title. Shared by every verb that resolves
/// a `--sheet` name (or a range's sheet prefix) against a freshly-fetched
/// workbook — `not_found` builds the caller's own "sheet not found" error
/// variant.
pub(crate) fn find_sheet_id<E>(
    workbook: &Spreadsheet,
    title: &str,
    not_found: impl FnOnce(String, Vec<String>) -> E,
) -> Result<i64, E> {
    workbook
        .sheets
        .iter()
        .filter_map(|sheet| sheet.properties.as_ref())
        .find(|props| props.title == title)
        .and_then(|props| props.sheet_id)
        .ok_or_else(|| not_found(title.to_string(), workbook.sheet_titles()))
}

/// Prefixes an update verb's `--range` with the sheet the object being
/// updated already sits on, when the range names no sheet of its own and
/// no `--sheet` was given — `update-filter-view`/`update-banding` know that
/// sheet from the object they fetched, so refusing for the want of a
/// `--sheet` would only make the caller repeat it (#1941).
///
/// Returns `composed` unchanged when it already names a sheet, when there
/// is no current sheet, or when that sheet's title can't be found.
pub(crate) fn default_sheet_prefix(
    workbook: &Spreadsheet,
    composed: String,
    current_sheet_id: Option<i64>,
) -> String {
    if a1::split_sheet_prefix(&composed).is_some() || a1::is_whole_sheet_reference(&composed) {
        return composed;
    }
    current_sheet_id
        .and_then(|id| sheet_title_by_id(workbook, id))
        .and_then(|title| a1::compose(Some(&title), Some(&composed)).ok())
        .unwrap_or(composed)
}

/// The one rendering of a [`find_sheet_id`] miss, shared by every verb so
/// the refusal reads the same everywhere: `book` is the caller's display
/// name for the spreadsheet (already quoted), and each available title is
/// quoted, or the list reads `none` for a workbook with no sheets.
pub(crate) fn no_sheet_refusal(book: &str, title: &str, available: &[String]) -> String {
    format!(
        "Refused: {book} has no sheet titled '{title}'. Available: {}",
        available_sheets(available)
    )
}

/// The `Available: …` list of [`no_sheet_refusal`], for the one caller
/// (`search-developer-metadata`) that phrases the rest of the message
/// itself.
pub(crate) fn available_sheets(available: &[String]) -> String {
    if available.is_empty() {
        "none".to_string()
    } else {
        available
            .iter()
            .map(|title| format!("'{title}'"))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

/// The reverse of [`find_sheet_id`]: a sheet's title by its numeric id, or
/// `None` if the workbook carries no sheet with that id. Needed by any
/// list verb (e.g. `list-named-ranges`) that renders a workbook-scoped
/// object's `sheetId` back into a human-readable title.
pub(crate) fn sheet_title_by_id(workbook: &Spreadsheet, sheet_id: i64) -> Option<String> {
    find_sheet_by_id(workbook, sheet_id).map(|sheet| sheet.title().to_string())
}

/// A workbook's sheet by its numeric id, or `None` if it carries none with
/// that id. The `&Sheet` counterpart to [`sheet_title_by_id`], for a caller
/// that needs more than the title (e.g. `embedded_object.rs`'s `move-chart`/
/// `move-slicer`, which renders a destination anchor via
/// `describe_overlay_position(sheet, ..)`, issue #1837).
pub(crate) fn find_sheet_by_id(workbook: &Spreadsheet, sheet_id: i64) -> Option<&Sheet> {
    workbook
        .sheets
        .iter()
        .find(|sheet| sheet.sheet_id() == Some(sheet_id))
}

/// Whether `grid` names exactly one cell.
///
/// Shared by every verb whose API request takes a `GridCoordinate` rather
/// than a `GridRange` — `add-pivot-table`'s anchor, `cut-paste`'s and
/// `paste-data`'s destination — so the refusal they make of a multi-cell
/// argument rests on one tested definition.
pub(crate) fn is_single_cell(grid: &GridRange) -> bool {
    is_bounded(grid)
        && grid.end_row_index.unwrap_or(0) - grid.start_row_index.unwrap_or(0) == 1
        && grid.end_column_index.unwrap_or(0) - grid.start_column_index.unwrap_or(0) == 1
}

/// Renders a fully-bounded, non-empty [`GridRange`] back to an A1 string
/// for a `values.get` read, e.g. `'Q1'!A1:B2`.
///
/// `None` for a range that isn't fully bounded, or that is empty on either
/// axis (`end <= start`): neither names a rectangle a read could describe,
/// and the 1-based inclusive end this has to render would run *before* the
/// start — `column_index_to_letters(-1)` for a zero-column range, which is
/// not a column at all. Returning `None` rather than a bad string keeps
/// that case a caller's decision instead of an invalid range on the wire
/// (issue #1839).
pub(crate) fn bounded_range_to_a1(sheet_title: &str, grid: &GridRange) -> Option<String> {
    let (Some(r0), Some(r1), Some(c0), Some(c1)) = (
        grid.start_row_index,
        grid.end_row_index,
        grid.start_column_index,
        grid.end_column_index,
    ) else {
        return None;
    };
    if r1 <= r0 || c1 <= c0 {
        return None;
    }
    let start = format!("{}{}", column_index_to_letters(c0), r0 + 1);
    let end = format!("{}{}", column_index_to_letters(c1 - 1), r1);
    a1::compose(Some(sheet_title), Some(&format!("{start}:{end}"))).ok()
}

/// Clips `grid` to the rows and columns its sheet currently has, or `None`
/// when nothing of it lies inside them.
///
/// A `values.get` over a range past the grid's edge is refused by the API
/// ("exceeds grid limits"), so a preview that computes an extent reaching
/// beyond the sheet — which `paste.rs` deliberately can, since the written
/// extent is a property of the request, not of the sheet — must read the
/// part that exists rather than ask for the part that doesn't (issue
/// #1839). An axis the API reports no count for is left as-is: there's
/// nothing to clip against.
pub(crate) fn clamp_to_sheet(workbook: &Spreadsheet, grid: &GridRange) -> Option<GridRange> {
    let sheet = find_sheet_by_id(workbook, grid.sheet_id)?;
    let props = sheet
        .properties
        .as_ref()
        .and_then(|p| p.grid_properties.as_ref());
    let clip = |end: Option<i64>, count: Option<i64>| match (end, count) {
        (Some(end), Some(count)) => Some(end.min(count)),
        (end, _) => end,
    };
    let clamped = GridRange {
        sheet_id: grid.sheet_id,
        start_row_index: grid.start_row_index,
        end_row_index: clip(grid.end_row_index, props.and_then(|g| g.row_count)),
        start_column_index: grid.start_column_index,
        end_column_index: clip(grid.end_column_index, props.and_then(|g| g.column_count)),
    };
    let empty = |start: Option<i64>, end: Option<i64>| matches!((start, end), (Some(start), Some(end)) if end <= start);
    if empty(clamped.start_row_index, clamped.end_row_index)
        || empty(clamped.start_column_index, clamped.end_column_index)
    {
        return None;
    }
    Some(clamped)
}

/// Whether `grid` starts at or past its sheet's last row or column, so no
/// cell of it lies inside the current grid. Catches the open-ended case
/// [`clamp_to_sheet`] cannot: `A2000:A` on a 1000-row sheet has no end to
/// clip, so it clamps to itself rather than to nothing. An axis whose count
/// the workbook does not report is never past it.
pub(crate) fn starts_past_grid(workbook: &Spreadsheet, grid: &GridRange) -> bool {
    let Some(props) = find_sheet_by_id(workbook, grid.sheet_id)
        .and_then(|sheet| sheet.properties.as_ref())
        .and_then(|p| p.grid_properties.as_ref())
    else {
        return false;
    };
    let past = |start: Option<i64>, count: Option<i64>| matches!((start, count), (Some(start), Some(count)) if start >= count);
    past(grid.start_row_index, props.row_count) || past(grid.start_column_index, props.column_count)
}

/// Renders a numeric [`GridRange`] as a compact 1-based description for a
/// list verb's human-readable output — e.g. `"sheetId 0, rows 1-5, cols
/// 1-2"`, `"sheetId 0, rows 5+"` for a bound left open at one end (the
/// `A5:A` grammar `parse_grid_range` accepts), or `"sheetId 0 (whole
/// sheet)"` when every bound is `None`. Shared by `list-protections`/
/// `list-named-ranges`, which were previously two independent copies of
/// this function — one of which silently dropped an open-ended bound
/// instead of showing it, rather than falling back to "whole sheet".
pub(crate) fn render_grid_range(range: &GridRange) -> String {
    let rows = describe_bound(range.start_row_index, range.end_row_index, "rows");
    let cols = describe_bound(range.start_column_index, range.end_column_index, "cols");
    if rows.is_empty() && cols.is_empty() {
        format!("sheetId {} (whole sheet)", range.sheet_id)
    } else {
        format!("sheetId {}{rows}{cols}", range.sheet_id)
    }
}

/// One axis of [`render_grid_range`]: `start`/`end` are zero-based,
/// `end` exclusive, exactly like [`GridRange`]'s own fields.
fn describe_bound(start: Option<i64>, end: Option<i64>, label: &str) -> String {
    match (start, end) {
        (Some(start), Some(end)) => format!(", {label} {}-{end}", start + 1),
        (Some(start), None) => format!(", {label} {}+", start + 1),
        (None, Some(end)) => format!(", {label} 1-{end}"),
        (None, None) => String::new(),
    }
}

/// Resolves an already-composed `--sheet`/`--range` string into a numeric
/// [`GridRange`]: the shared "split off the sheet prefix, find its id,
/// parse the bare range" pipeline every range-targeted verb in
/// `format.rs`/`protection.rs`/`validation.rs`/`named_range.rs` needs.
/// `invalid_range` and `not_found` build the caller's own error variants,
/// so this stays usable across their differently-shaped result enums.
///
/// Returns the sheet's title alongside the range, since some callers (e.g.
/// `format.rs`'s merge-cells preview) need it again afterward.
pub(crate) fn resolve_grid_range<E>(
    workbook: &Spreadsheet,
    composed: &str,
    invalid_range: impl Fn(String) -> E,
    not_found: impl FnOnce(String, Vec<String>) -> E,
) -> Result<(String, GridRange), E> {
    let Some((title, bare_range)) = a1::split_sheet_prefix(composed) else {
        // `--sheet` alone (with no `--range`) composes to a bare quoted
        // sheet name with no `!` — a distinct, common mistake from a
        // genuinely malformed range, and one `--whole-sheet` names the fix
        // for directly, so it earns its own message rather than the
        // generic one below (which would otherwise tell a `--sheet` caller
        // to "pass --sheet" when they already did).
        let detail = if a1::is_whole_sheet_reference(composed) {
            format!(
                "{composed} names a sheet but not a range within it; pass --whole-sheet to \
                 target the whole sheet, or add --range to name a range inside it"
            )
        } else {
            format!(
                "{composed} does not name a sheet; pass --sheet, or a --range carrying its \
                 own 'Sheet!' prefix"
            )
        };
        return Err(invalid_range(detail));
    };
    let sheet_id = find_sheet_id(workbook, &title, not_found)?;
    let grid = parse_grid_range(sheet_id, bare_range).map_err(invalid_range)?;
    Ok((title, grid))
}

/// Parses one token (one side of a `:`, or a whole single-cell range) into
/// a [`CellRef`].
fn parse_cell_ref(token: &str) -> Option<CellRef> {
    let split_at = token.find(|c: char| c.is_ascii_digit());
    match split_at {
        None => column_letters_to_index(token).map(CellRef::Column),
        Some(0) => {
            let row: i64 = token.parse().ok()?;
            (row >= 1).then_some(CellRef::Row(row - 1))
        }
        Some(at) => {
            let (letters, digits) = token.split_at(at);
            let column = column_letters_to_index(letters)?;
            let row: i64 = digits.parse().ok()?;
            (row >= 1).then_some(CellRef::Cell(column, row - 1))
        }
    }
}

/// The forms [`parse_grid_range`] understands, for its error message.
const SUPPORTED_FORMS: &str = "a cell (A1), a bounded range (A1:D20), a whole column or \
    column span (A:A, A:D), a whole row or row span (5:5, 5:20), or a column open-ended \
    downward from a cell (A5:A)";

/// Parses a bare (no sheet prefix) A1 range into a numeric [`GridRange`] on
/// `sheet_id`.
///
/// See the module docs for exactly which forms are accepted. Every rejected
/// input gets a message naming what *is* supported, matching `a1.rs`'s own
/// stance of never silently guessing.
pub(crate) fn parse_grid_range(sheet_id: i64, range: &str) -> Result<GridRange, String> {
    let range = range.trim();
    let bare = || GridRange {
        sheet_id,
        ..Default::default()
    };
    let mut parts = range.splitn(2, ':');
    let first = parts.next().unwrap_or_default();
    match parts.next() {
        None => match parse_cell_ref(first) {
            Some(CellRef::Cell(col, row)) => Ok(GridRange {
                start_row_index: Some(row),
                end_row_index: Some(row + 1),
                start_column_index: Some(col),
                end_column_index: Some(col + 1),
                ..bare()
            }),
            Some(CellRef::Column(col)) => Ok(GridRange {
                start_column_index: Some(col),
                end_column_index: Some(col + 1),
                ..bare()
            }),
            Some(CellRef::Row(row)) => Ok(GridRange {
                start_row_index: Some(row),
                end_row_index: Some(row + 1),
                ..bare()
            }),
            None => Err(format!(
                "'{range}' is not a recognised A1 range; expected {SUPPORTED_FORMS}"
            )),
        },
        Some(second) => {
            let (Some(start), Some(end)) = (parse_cell_ref(first), parse_cell_ref(second)) else {
                return Err(format!(
                    "'{range}' is not a recognised A1 range; expected {SUPPORTED_FORMS}"
                ));
            };
            match (start, end) {
                (CellRef::Cell(c1, r1), CellRef::Cell(c2, r2)) => Ok(GridRange {
                    start_row_index: Some(r1.min(r2)),
                    end_row_index: Some(r1.max(r2) + 1),
                    start_column_index: Some(c1.min(c2)),
                    end_column_index: Some(c1.max(c2) + 1),
                    ..bare()
                }),
                (CellRef::Column(c1), CellRef::Column(c2)) => Ok(GridRange {
                    start_column_index: Some(c1.min(c2)),
                    end_column_index: Some(c1.max(c2) + 1),
                    ..bare()
                }),
                (CellRef::Row(r1), CellRef::Row(r2)) => Ok(GridRange {
                    start_row_index: Some(r1.min(r2)),
                    end_row_index: Some(r1.max(r2) + 1),
                    ..bare()
                }),
                (CellRef::Cell(c1, r1), CellRef::Column(c2)) if c1 == c2 => Ok(GridRange {
                    start_row_index: Some(r1),
                    end_row_index: None,
                    start_column_index: Some(c1),
                    end_column_index: Some(c1 + 1),
                    ..bare()
                }),
                _ => Err(format!(
                    "'{range}' is not a recognised A1 range; expected {SUPPORTED_FORMS}"
                )),
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn no_sheet_refusal_quotes_every_available_title() {
        assert_eq!(
            no_sheet_refusal("'Budget'", "Q9", &["Q1".to_string(), "Q2".to_string()]),
            "Refused: 'Budget' has no sheet titled 'Q9'. Available: 'Q1', 'Q2'"
        );
    }

    #[test]
    fn no_sheet_refusal_says_none_for_a_sheetless_workbook() {
        assert_eq!(
            no_sheet_refusal("'Budget'", "Q9", &[]),
            "Refused: 'Budget' has no sheet titled 'Q9'. Available: none"
        );
    }
    use crate::drive::sheets::types::{GridProperties, Sheet, SheetProperties};

    #[test]
    fn non_blank_locations_skips_blanks_and_offsets_addresses() {
        let values: ValueRange = serde_json::from_value(serde_json::json!({
            "values": [["a", "", "c"], [null, "d2"]]
        }))
        .unwrap();
        let locations = non_blank_locations(&values, 4, 2);
        assert_eq!(locations, vec!["C5", "E5", "D6"]);
    }

    #[test]
    fn non_blank_locations_includes_the_top_left_cell() {
        // Unlike `format.rs::discarded_from_values`, the anchor is not
        // skipped: every caller's written extent covers its whole read,
        // so the top-left cell is overwritten like any other. Moved here
        // with the function it pins, from `paste.rs`.
        let values: ValueRange = serde_json::from_value(serde_json::json!({
            "values": [["kept"]]
        }))
        .unwrap();
        assert_eq!(non_blank_locations(&values, 0, 0), vec!["A1"]);
    }

    #[test]
    fn truncate_locations_joins_everything_under_the_limit() {
        let cells = vec!["A1".to_string(), "B2".to_string()];
        assert_eq!(truncate_locations(&cells, 50), "A1, B2");
        // Exactly at the limit still renders in full.
        assert_eq!(truncate_locations(&cells, 2), "A1, B2");
        assert_eq!(truncate_locations(&[], 50), "");
    }

    #[test]
    fn truncate_locations_elides_past_the_limit_and_counts_the_remainder() {
        let cells: Vec<String> = (1..=5).map(|row| format!("A{row}")).collect();
        assert_eq!(truncate_locations(&cells, 2), "A1, A2, … and 3 more");
    }

    #[test]
    fn truncate_joined_uses_the_given_separator_in_the_body_and_the_suffix() {
        let items: Vec<String> = (1..=5).map(|row| format!("A{row}")).collect();
        assert_eq!(truncate_joined(&items, 2, "; "), "A1; A2; … and 3 more");
    }

    #[test]
    fn render_locations_elides_at_fifty_one_but_not_fifty() {
        let fifty: Vec<String> = (1..=50).map(|row| format!("A{row}")).collect();
        let rendered_fifty = render_locations(&fifty);
        assert!(!rendered_fifty.contains('…'));
        assert_eq!(rendered_fifty, fifty.join(", "));

        let fifty_one: Vec<String> = (1..=51).map(|row| format!("A{row}")).collect();
        let rendered_fifty_one = render_locations(&fifty_one);
        assert!(rendered_fifty_one.ends_with("… and 1 more"));
    }

    #[test]
    fn non_blank_locations_never_carries_a_value() {
        let values: ValueRange = serde_json::from_value(serde_json::json!({
            "values": [["a-secret-value"]]
        }))
        .unwrap();
        let locations = non_blank_locations(&values, 0, 0);
        assert_eq!(locations, vec!["A1"]);
        assert!(!locations.iter().any(|loc| loc.contains("secret")));
    }

    #[test]
    fn column_letters_to_index_single_and_double_letters() {
        assert_eq!(column_letters_to_index("A"), Some(0));
        assert_eq!(column_letters_to_index("Z"), Some(25));
        assert_eq!(column_letters_to_index("AA"), Some(26));
        assert_eq!(column_letters_to_index("AZ"), Some(51));
        assert_eq!(column_letters_to_index("BA"), Some(52));
    }

    #[test]
    fn column_letters_to_index_rejects_non_letters() {
        assert_eq!(column_letters_to_index(""), None);
        assert_eq!(column_letters_to_index("1"), None);
        assert_eq!(column_letters_to_index("A1"), None);
    }

    #[test]
    fn a_single_cell() {
        let g = parse_grid_range(7, "B3").unwrap();
        assert_eq!(g.sheet_id, 7);
        assert_eq!(g.start_row_index, Some(2));
        assert_eq!(g.end_row_index, Some(3));
        assert_eq!(g.start_column_index, Some(1));
        assert_eq!(g.end_column_index, Some(2));
    }

    #[test]
    fn a_bounded_range() {
        let g = parse_grid_range(1, "A1:D20").unwrap();
        assert_eq!(g.start_row_index, Some(0));
        assert_eq!(g.end_row_index, Some(20));
        assert_eq!(g.start_column_index, Some(0));
        assert_eq!(g.end_column_index, Some(4));
    }

    #[test]
    fn a_bounded_range_normalises_a_reversed_pair() {
        let g = parse_grid_range(1, "D20:A1").unwrap();
        assert_eq!(g.start_row_index, Some(0));
        assert_eq!(g.end_row_index, Some(20));
        assert_eq!(g.start_column_index, Some(0));
        assert_eq!(g.end_column_index, Some(4));
    }

    #[test]
    fn a_whole_column() {
        let g = parse_grid_range(1, "C:C").unwrap();
        assert_eq!(g.start_row_index, None);
        assert_eq!(g.end_row_index, None);
        assert_eq!(g.start_column_index, Some(2));
        assert_eq!(g.end_column_index, Some(3));
    }

    #[test]
    fn a_column_span() {
        let g = parse_grid_range(1, "A:C").unwrap();
        assert_eq!(g.start_column_index, Some(0));
        assert_eq!(g.end_column_index, Some(3));
        assert_eq!(g.start_row_index, None);
    }

    #[test]
    fn a_whole_row() {
        let g = parse_grid_range(1, "5:5").unwrap();
        assert_eq!(g.start_row_index, Some(4));
        assert_eq!(g.end_row_index, Some(5));
        assert_eq!(g.start_column_index, None);
        assert_eq!(g.end_column_index, None);
    }

    #[test]
    fn a_row_span() {
        let g = parse_grid_range(1, "5:20").unwrap();
        assert_eq!(g.start_row_index, Some(4));
        assert_eq!(g.end_row_index, Some(20));
    }

    #[test]
    fn a_column_open_ended_downward_from_a_cell() {
        let g = parse_grid_range(1, "A5:A").unwrap();
        assert_eq!(g.start_row_index, Some(4));
        assert_eq!(g.end_row_index, None);
        assert_eq!(g.start_column_index, Some(0));
        assert_eq!(g.end_column_index, Some(1));
    }

    #[test]
    fn mismatched_column_open_end_is_rejected() {
        let err = parse_grid_range(1, "A5:B").unwrap_err();
        assert!(err.contains("not a recognised A1 range"), "{err}");
    }

    #[test]
    fn a_row_open_ended_rightward_is_out_of_the_supported_grammar() {
        let err = parse_grid_range(1, "A5:5").unwrap_err();
        assert!(err.contains("expected"), "{err}");
    }

    #[test]
    fn garbage_is_rejected_with_a_message_naming_supported_forms() {
        let err = parse_grid_range(1, "!!!").unwrap_err();
        assert!(err.contains("column span"), "{err}");
    }

    #[test]
    fn empty_string_is_rejected() {
        assert!(parse_grid_range(1, "").is_err());
    }

    #[test]
    fn whitespace_is_trimmed() {
        let g = parse_grid_range(1, "  A1:B2  ").unwrap();
        assert_eq!(g.start_row_index, Some(0));
    }

    #[test]
    fn column_index_to_letters_round_trips_column_letters_to_index() {
        for (index, letters) in [(0, "A"), (25, "Z"), (26, "AA"), (51, "AZ"), (52, "BA")] {
            assert_eq!(column_index_to_letters(index), letters);
            assert_eq!(column_letters_to_index(letters), Some(index));
        }
    }

    #[test]
    fn check_column_in_range_accepts_start_and_last_column_of_a_bounded_range() {
        let grid = parse_grid_range(1, "C1:F2").unwrap();
        assert!(check_column_in_range(2, &grid).is_ok());
        assert!(check_column_in_range(5, &grid).is_ok());
    }

    #[test]
    fn check_column_in_range_rejects_below_start_and_at_exclusive_end() {
        let grid = parse_grid_range(1, "C1:F2").unwrap();
        assert_eq!(
            check_column_in_range(1, &grid),
            Err(ColumnOutOfRange {
                column: 1,
                start: 2,
                end: Some(6),
            })
        );
        assert_eq!(
            check_column_in_range(6, &grid),
            Err(ColumnOutOfRange {
                column: 6,
                start: 2,
                end: Some(6),
            })
        );
    }

    #[test]
    fn check_column_in_range_treats_an_unset_end_as_unbounded() {
        let whole_rows = parse_grid_range(1, "2:5").unwrap();
        assert!(check_column_in_range(0, &whole_rows).is_ok());
        assert!(check_column_in_range(700, &whole_rows).is_ok());
    }

    #[test]
    fn check_column_in_range_treats_an_unset_start_as_zero() {
        let whole_column = parse_grid_range(1, "A:A").unwrap();
        assert!(check_column_in_range(0, &whole_column).is_ok());
        assert!(check_column_in_range(-1, &whole_column).is_err());
    }

    #[test]
    fn check_column_in_range_rejects_everything_in_an_empty_range() {
        let empty = GridRange {
            sheet_id: 1,
            start_row_index: Some(0),
            end_row_index: Some(1),
            start_column_index: Some(2),
            end_column_index: Some(2),
        };
        assert!(check_column_in_range(2, &empty).is_err());
    }

    #[test]
    fn check_column_in_range_rejects_a_negative_column() {
        let grid = parse_grid_range(1, "A1:F2").unwrap();
        assert!(check_column_in_range(-1, &grid).is_err());
    }

    #[test]
    fn is_bounded_requires_all_four_indices() {
        let bounded = parse_grid_range(1, "A1:B2").unwrap();
        assert!(is_bounded(&bounded));
        let open_column = parse_grid_range(1, "A:A").unwrap();
        assert!(!is_bounded(&open_column));
    }

    #[test]
    fn cell_count_multiplies_rows_by_columns_for_a_bounded_range() {
        assert_eq!(
            cell_count(&parse_grid_range(1, "A1:D20").unwrap()),
            Some(80)
        );
        assert_eq!(cell_count(&parse_grid_range(1, "C3").unwrap()), Some(1));
    }

    #[test]
    fn cell_count_is_none_for_an_open_ended_range() {
        assert_eq!(cell_count(&parse_grid_range(1, "A:A").unwrap()), None);
        assert_eq!(cell_count(&parse_grid_range(1, "5:5").unwrap()), None);
        assert_eq!(cell_count(&parse_grid_range(1, "A1:A").unwrap()), None);
    }

    #[test]
    fn cell_count_handles_a_huge_range_and_saturates_instead_of_overflowing() {
        assert_eq!(
            cell_count(&parse_grid_range(1, "A1:ZZZ10000000").unwrap()),
            Some(18_278 * 10_000_000)
        );
        let extreme = GridRange {
            sheet_id: 1,
            start_row_index: Some(0),
            end_row_index: Some(i64::MAX),
            start_column_index: Some(0),
            end_column_index: Some(i64::MAX),
        };
        assert_eq!(cell_count(&extreme), Some(i64::MAX));
    }

    #[test]
    fn a_bare_column_letter_with_no_colon() {
        let g = parse_grid_range(1, "C").unwrap();
        assert_eq!(g.start_column_index, Some(2));
        assert_eq!(g.end_column_index, Some(3));
        assert_eq!(g.start_row_index, None);
        assert_eq!(g.end_row_index, None);
    }

    #[test]
    fn a_bare_row_number_with_no_colon() {
        let g = parse_grid_range(1, "5").unwrap();
        assert_eq!(g.start_row_index, Some(4));
        assert_eq!(g.end_row_index, Some(5));
        assert_eq!(g.start_column_index, None);
        assert_eq!(g.end_column_index, None);
    }

    #[test]
    fn a_range_with_one_unparseable_side_is_rejected() {
        let err = parse_grid_range(1, "A1:!!!").unwrap_err();
        assert!(err.contains("not a recognised A1 range"), "{err}");
    }

    #[test]
    fn is_single_cell_accepts_one_cell_and_refuses_a_range_or_an_open_end() {
        assert!(is_single_cell(&parse_grid_range(1, "A1").unwrap()));
        assert!(!is_single_cell(&parse_grid_range(1, "A1:A2").unwrap()));
        assert!(!is_single_cell(&parse_grid_range(1, "A1:B1").unwrap()));
        assert!(!is_single_cell(&parse_grid_range(1, "A:A").unwrap()));
    }

    #[test]
    fn bounded_range_to_a1_round_trips_a_rectangle() {
        let grid = parse_grid_range(7, "B2:D5").unwrap();
        assert_eq!(
            bounded_range_to_a1("Q1", &grid).as_deref(),
            Some("'Q1'!B2:D5")
        );
    }

    #[test]
    fn bounded_range_to_a1_refuses_an_open_ended_or_empty_range() {
        assert_eq!(
            bounded_range_to_a1("Q1", &parse_grid_range(1, "A:A").unwrap()),
            None
        );
        // The zero-by-zero case: rendering it would ask
        // `column_index_to_letters` for column -1.
        let empty = GridRange {
            sheet_id: 1,
            start_row_index: Some(0),
            end_row_index: Some(0),
            start_column_index: Some(0),
            end_column_index: Some(0),
        };
        assert_eq!(bounded_range_to_a1("Q1", &empty), None);
    }

    fn workbook_with_grid(sheet_id: i64, rows: i64, columns: i64) -> Spreadsheet {
        Spreadsheet {
            sheets: vec![Sheet {
                properties: Some(SheetProperties {
                    sheet_id: Some(sheet_id),
                    title: "Q1".to_string(),
                    grid_properties: Some(GridProperties {
                        row_count: Some(rows),
                        column_count: Some(columns),
                        ..Default::default()
                    }),
                    ..Default::default()
                }),
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[test]
    fn clamp_to_sheet_clips_an_extent_past_the_grids_edge() {
        let workbook = workbook_with_grid(1, 10, 5);
        let clamped = clamp_to_sheet(&workbook, &parse_grid_range(1, "A1:Z100").unwrap()).unwrap();
        assert_eq!(clamped.end_row_index, Some(10));
        assert_eq!(clamped.end_column_index, Some(5));
    }

    #[test]
    fn clamp_to_sheet_leaves_an_extent_inside_the_grid_alone() {
        let workbook = workbook_with_grid(1, 10, 5);
        let grid = parse_grid_range(1, "A1:B2").unwrap();
        assert_eq!(clamp_to_sheet(&workbook, &grid), Some(grid));
    }

    #[test]
    fn clamp_to_sheet_is_none_when_nothing_of_the_range_exists() {
        let workbook = workbook_with_grid(1, 10, 5);
        // Starts past the last row: clipping leaves an empty rectangle,
        // which is no range at all rather than a zero-height one.
        assert_eq!(
            clamp_to_sheet(&workbook, &parse_grid_range(1, "A20:B30").unwrap()),
            None
        );
    }

    #[test]
    fn clamp_to_sheet_leaves_an_axis_with_no_reported_count_alone() {
        let workbook = workbook_with_sheet(1, "Q1");
        let grid = parse_grid_range(1, "A1:Z100").unwrap();
        assert_eq!(clamp_to_sheet(&workbook, &grid), Some(grid));
    }

    #[test]
    fn clamp_to_sheet_is_none_for_a_sheet_the_workbook_does_not_carry() {
        let workbook = workbook_with_grid(1, 10, 5);
        assert_eq!(
            clamp_to_sheet(&workbook, &parse_grid_range(99, "A1:B2").unwrap()),
            None
        );
    }

    fn workbook_with_sheet(sheet_id: i64, title: &str) -> Spreadsheet {
        Spreadsheet {
            sheets: vec![Sheet {
                properties: Some(SheetProperties {
                    sheet_id: Some(sheet_id),
                    title: title.to_string(),
                    ..Default::default()
                }),
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[test]
    fn default_sheet_prefix_supplies_the_current_sheet_only_when_none_is_named() {
        let workbook = workbook_with_sheet(5, "Q 2");
        assert_eq!(
            default_sheet_prefix(&workbook, "A1:B2".to_string(), Some(5)),
            "'Q 2'!A1:B2"
        );
        // A range naming its own sheet, or a whole-sheet reference, is kept.
        assert_eq!(
            default_sheet_prefix(&workbook, "Q1!A1:B2".to_string(), Some(5)),
            "Q1!A1:B2"
        );
        assert_eq!(
            default_sheet_prefix(&workbook, "'Q1'".to_string(), Some(5)),
            "'Q1'"
        );
        // No current sheet, or one the workbook doesn't have: unchanged, so
        // the usual "does not name a sheet" refusal still explains it.
        assert_eq!(
            default_sheet_prefix(&workbook, "A1:B2".to_string(), None),
            "A1:B2"
        );
        assert_eq!(
            default_sheet_prefix(&workbook, "A1:B2".to_string(), Some(9)),
            "A1:B2"
        );
    }

    #[test]
    fn resolve_grid_range_rejects_a_range_with_no_sheet_prefix() {
        let workbook = workbook_with_sheet(0, "Q1");
        let err = resolve_grid_range(
            &workbook,
            "A1:B2",
            |detail| detail,
            |t, a| format!("{t} {a:?}"),
        )
        .unwrap_err();
        assert!(err.contains("does not name a sheet"), "{err}");
    }

    #[test]
    fn resolve_grid_range_points_a_sheet_only_composition_at_whole_sheet() {
        // `--sheet Q1` alone composes to `'Q1'` (a1::compose's
        // sheet-only arm) — a distinct mistake from a malformed range,
        // deserving its own message rather than "pass --sheet" when the
        // caller already did.
        let workbook = workbook_with_sheet(0, "Q1");
        let err = resolve_grid_range(
            &workbook,
            "'Q1'",
            |detail| detail,
            |t, a| format!("{t} {a:?}"), // omni-dev: coverage ignore-line reason="a sheet-only composition always fails at the split_sheet_prefix check above; not_found is never reached in this test"
        )
        .unwrap_err();
        assert!(err.contains("--whole-sheet"), "{err}");
    }

    #[test]
    fn sheet_title_by_id_finds_the_matching_sheet() {
        let workbook = workbook_with_sheet(3, "Q1");
        assert_eq!(sheet_title_by_id(&workbook, 3), Some("Q1".to_string()));
        assert_eq!(sheet_title_by_id(&workbook, 99), None);
    }

    #[test]
    fn find_sheet_by_id_finds_the_matching_sheet() {
        let workbook = workbook_with_sheet(3, "Q1");
        assert_eq!(find_sheet_by_id(&workbook, 3).map(Sheet::title), Some("Q1"));
        assert!(find_sheet_by_id(&workbook, 99).is_none());
    }

    #[test]
    fn render_grid_range_whole_sheet_when_all_bounds_none() {
        let range = GridRange {
            sheet_id: 0,
            ..Default::default()
        };
        assert_eq!(render_grid_range(&range), "sheetId 0 (whole sheet)");
    }

    #[test]
    fn render_grid_range_rows_and_cols() {
        let range = GridRange {
            sheet_id: 3,
            start_row_index: Some(0),
            end_row_index: Some(5),
            start_column_index: Some(0),
            end_column_index: Some(2),
        };
        assert_eq!(render_grid_range(&range), "sheetId 3, rows 1-5, cols 1-2");
    }

    #[test]
    fn render_grid_range_shows_an_open_ended_bound_rather_than_dropping_it() {
        // The `A5:A` grammar: bounded start, open end. Regression test for
        // the bug where this silently rendered as if unbounded.
        let range = GridRange {
            sheet_id: 0,
            start_row_index: Some(4),
            end_row_index: None,
            start_column_index: Some(0),
            end_column_index: Some(1),
        };
        assert_eq!(render_grid_range(&range), "sheetId 0, rows 5+, cols 1-1");
    }

    #[test]
    fn render_grid_range_shows_an_open_start_bound() {
        let range = GridRange {
            sheet_id: 0,
            start_row_index: None,
            end_row_index: Some(5),
            ..Default::default()
        };
        assert_eq!(render_grid_range(&range), "sheetId 0, rows 1-5");
    }

    #[test]
    fn reorder_caveat_lines_would_change_has_no_warning_and_names_the_verb() {
        let lines =
            reorder_caveat_lines("sorting", "Would sort A1:B2".to_string(), None, false, None);
        assert_eq!(
            lines,
            vec![
                "Would sort A1:B2".to_string(),
                "  references outside the range may observe values from a different row after sorting"
                    .to_string(),
            ]
        );
    }

    #[test]
    fn reorder_caveat_lines_changed_drops_the_verb_and_switches_to_now() {
        let lines = reorder_caveat_lines(
            "randomizing",
            "Randomized A1:B2".to_string(),
            None,
            true,
            None,
        );
        assert_eq!(
            lines,
            vec![
                "Randomized A1:B2".to_string(),
                "  references outside the range may now observe values from a different row"
                    .to_string(),
            ]
        );
    }

    #[test]
    fn reorder_caveat_lines_prepends_the_width_warning_when_present() {
        let lines = reorder_caveat_lines(
            "sorting",
            "Applied sort of A1:B2".to_string(),
            Some("selected columns 0..2 of the sheet's 5 allocated columns"),
            true,
            None,
        );
        assert_eq!(
            lines,
            vec![
                "Warning: selected columns 0..2 of the sheet's 5 allocated columns".to_string(),
                "Applied sort of A1:B2".to_string(),
                "  references outside the range may now observe values from a different row"
                    .to_string(),
            ]
        );
    }

    #[test]
    fn reorder_caveat_lines_inserts_the_order_caveat_between_summary_and_reference_line() {
        let lines = reorder_caveat_lines(
            "randomizing",
            "Would randomize the row order of A1:B2".to_string(),
            None,
            false,
            Some("the resulting order is chosen by the server and cannot be previewed"),
        );
        assert_eq!(
            lines,
            vec![
                "Would randomize the row order of A1:B2".to_string(),
                "  the resulting order is chosen by the server and cannot be previewed"
                    .to_string(),
                "  references outside the range may observe values from a different row after randomizing"
                    .to_string(),
            ]
        );
    }
}