omni-dev 0.41.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
//! CLI command for `omni-dev drive read`.

use anyhow::{Context, Result};
use clap::Parser;
use sha2::{Digest, Sha256};

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::drive::client::DriveClient;
use crate::drive::files_api::FilesApi;
use crate::drive::types::DriveFile;

const GOOGLE_DOC: &str = "application/vnd.google-apps.document";
const GOOGLE_SHEET: &str = "application/vnd.google-apps.spreadsheet";
const GOOGLE_SLIDES: &str = "application/vnd.google-apps.presentation";
/// Reused by the `drive_file_read` MCP tool's content-mode folder rejection.
pub(crate) const GOOGLE_FOLDER: &str = "application/vnd.google-apps.folder";
/// Reused by the `drive_file_read` MCP tool's content-mode shortcut rejection.
pub(crate) const GOOGLE_SHORTCUT: &str = "application/vnd.google-apps.shortcut";

/// Reads a single Drive file's metadata or content.
#[derive(Parser)]
pub struct ReadCommand {
    /// Drive file id (from `drive search`, or the `id` segment of a Drive
    /// URL).
    pub file_id: String,

    /// Fetches the file's actual content instead of its metadata.
    /// Google-native files (Docs/Sheets/Slides/...) are exported (see
    /// `--export-mime-type`); every other file is downloaded as-is.
    #[arg(long)]
    pub content: bool,

    /// Export MIME type for a Google-native file's content (only relevant
    /// with `--content`; ignored for non-Google-native files, which are
    /// downloaded as-is regardless). Defaults: Google Docs -> text/markdown,
    /// Google Sheets -> text/csv (first sheet only — Drive's export API has
    /// no multi-sheet CSV format), Google Slides -> text/plain. Required for
    /// every other Google-native type (Forms, Drawings, Apps Script, Sites,
    /// ...); the error names the file's actually supported export MIME
    /// types.
    #[arg(long = "export-mime-type", value_name = "MIME_TYPE")]
    pub export_mime_type: Option<String>,

    /// Writes fetched content to this path instead of stdout. Only valid
    /// with `--content` — metadata always renders via `-o/--output`.
    #[arg(long = "out-file", value_name = "PATH")]
    pub out_file: Option<String>,

    /// Locally recomputes the SHA-256 checksum of the downloaded bytes and
    /// checks it against Drive's reported `sha256Checksum`. Only valid with
    /// `--content`, and only for non-Google-native files — Drive never
    /// returns a checksum for exported content, so this errors immediately
    /// on a Google-native file rather than exporting first. Prints a
    /// one-line confirmation on success; fails with a clear error on a
    /// mismatch or a missing checksum.
    #[arg(long)]
    pub verify: bool,

    /// Output format (metadata only).
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl ReadCommand {
    /// Runs the command against the shared client resolved by the parent
    /// `DriveCommand::execute`.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        run_read(
            client,
            &self.file_id,
            self.content,
            self.export_mime_type.as_deref(),
            self.out_file.as_deref(),
            self.verify,
            &self.output,
        )
        .await
    }
}

/// Fetches the file (metadata or content) and emits it in the requested
/// format.
///
/// Split from [`ReadCommand::execute`] so tests can inject a wiremock
/// client without going through the credential-loading path.
async fn run_read(
    client: &DriveClient,
    file_id: &str,
    content: bool,
    export_mime_type: Option<&str>,
    out_file: Option<&str>,
    verify: bool,
    output: &OutputFormat,
) -> Result<()> {
    if content {
        run_read_content(client, file_id, export_mime_type, out_file, verify).await
    } else {
        anyhow::ensure!(
            out_file.is_none(),
            "--out-file requires --content; `drive read` without --content always renders \
             metadata via -o/--output"
        );
        anyhow::ensure!(
            !verify,
            "--verify requires --content; `drive read` without --content always renders \
             metadata via -o/--output"
        );
        run_read_metadata(client, file_id, output).await
    }
}

async fn run_read_metadata(
    client: &DriveClient,
    file_id: &str,
    output: &OutputFormat,
) -> Result<()> {
    let meta = FilesApi::new(client).get_metadata(file_id).await?;
    if output_as(&meta, output)? {
        return Ok(());
    }
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    render_metadata_table(&meta, &mut handle)
}

/// Renders a single file's metadata as a bespoke header block — a "table"
/// in the sense of "one command, one rendering," not a literal grid,
/// matching `crate::cli::gmail::read::render_read_table`'s precedent.
fn render_metadata_table(file: &DriveFile, out: &mut dyn std::io::Write) -> Result<()> {
    writeln!(out, "Id: {}", sanitize_for_terminal(&file.id)).context("Failed to write read row")?;
    writeln!(out, "Name: {}", sanitize_for_terminal(&file.name))
        .context("Failed to write read row")?;
    writeln!(out, "MimeType: {}", sanitize_for_terminal(&file.mime_type))
        .context("Failed to write read row")?;
    if let Some(size) = &file.size {
        writeln!(out, "Size: {}", sanitize_for_terminal(size))
            .context("Failed to write read row")?;
    }
    if let Some(modified) = &file.modified_time {
        writeln!(out, "Modified: {}", sanitize_for_terminal(modified))
            .context("Failed to write read row")?;
    }
    if !file.parents.is_empty() {
        let parents = file
            .parents
            .iter()
            .map(|p| sanitize_for_terminal(p))
            .collect::<Vec<_>>()
            .join(", ");
        writeln!(out, "Parents: {parents}").context("Failed to write read row")?;
    }
    if let Some(link) = &file.web_view_link {
        writeln!(out, "WebViewLink: {}", sanitize_for_terminal(link))
            .context("Failed to write read row")?;
    }
    if let Some(md5) = &file.md5_checksum {
        writeln!(out, "Md5Checksum: {}", sanitize_for_terminal(md5))
            .context("Failed to write read row")?;
    }
    if let Some(sha1) = &file.sha1_checksum {
        writeln!(out, "Sha1Checksum: {}", sanitize_for_terminal(sha1))
            .context("Failed to write read row")?;
    }
    if let Some(sha256) = &file.sha256_checksum {
        writeln!(out, "Sha256Checksum: {}", sanitize_for_terminal(sha256))
            .context("Failed to write read row")?;
    }
    Ok(())
}

/// Content path: always fetches metadata first (to learn `mimeType` and
/// `exportLinks`), then either exports (Google-native) or downloads
/// (everything else).
async fn run_read_content(
    client: &DriveClient,
    file_id: &str,
    export_mime_type: Option<&str>,
    out_file: Option<&str>,
    verify: bool,
) -> Result<()> {
    let api = FilesApi::new(client);
    let meta = api.get_metadata(file_id).await?;

    if meta.mime_type == GOOGLE_FOLDER {
        anyhow::bail!(
            "'{}' is a folder; folders have no content to read — use `drive search` to list \
             what it contains",
            meta.name
        );
    }
    if meta.mime_type == GOOGLE_SHORTCUT {
        anyhow::bail!(
            "'{}' is a shortcut; `drive read --content` doesn't follow shortcuts to their \
             target file — resolve the target file's id and read that instead",
            meta.name
        );
    }
    if verify && meta.is_google_native() {
        anyhow::bail!(
            "--verify is not supported for Google-native files: Drive does not return a \
             checksum for exported content"
        );
    }

    let (bytes, content_mime_type) = if meta.is_google_native() {
        let export_mime = resolve_export_mime_type(&meta, export_mime_type)?;
        let bytes = api.export(file_id, &export_mime).await?;
        (bytes, export_mime)
    } else {
        let bytes = api.download(file_id).await?;
        (bytes, meta.mime_type.clone())
    };

    if verify {
        verify_sha256_checksum(&bytes, meta.sha256_checksum.as_deref())?;
        eprintln!("Verified sha256 checksum.");
    }

    if let Some(path) = out_file {
        std::fs::write(path, &bytes).with_context(|| format!("Failed to write to {path}"))?;
        println!(
            "Saved {} bytes to {path} (mimeType: {content_mime_type}).",
            bytes.len()
        );
        return Ok(());
    }

    // No --out-file: print texty content directly; refuse to garble the
    // terminal with binary content.
    if is_texty(&content_mime_type) {
        if let Ok(text) = String::from_utf8(bytes) {
            print!("{text}");
            return Ok(());
        }
        anyhow::bail!(
            "content (mimeType: {content_mime_type}) claims to be text but is not valid \
             UTF-8; use --out-file to save it"
        );
    }
    anyhow::bail!(
        "refusing to print binary content (mimeType: {content_mime_type}) to the terminal; \
         use --out-file <PATH> to save it"
    );
}

/// Resolves the export MIME type: an explicit MIME type always wins (never
/// validated against `exportLinks` client-side — the server is authoritative
/// and already returns a clear error for an unsupported value); otherwise
/// Docs/Sheets/Slides fall back to a documented default; every other
/// Google-native type has no safe default and requires one, so the error
/// lists the file's actually supported export MIME types from
/// `exportLinks`.
///
/// `pub(crate)`: also reused by the `drive_file_read` MCP tool
/// (`src/mcp/drive_tools.rs`, issue #1525) for its `format: "content"` path
/// — the "how to specify one" clause in the error below names both
/// surfaces' syntax accordingly, rather than assuming the CLI flag.
pub(crate) fn resolve_export_mime_type(meta: &DriveFile, explicit: Option<&str>) -> Result<String> {
    if let Some(mime) = explicit {
        return Ok(mime.to_string());
    }
    if let Some(default) = default_export_mime_type(&meta.mime_type) {
        return Ok(default.to_string());
    }
    let available = meta.export_links.as_ref().map_or_else(
        || "(none)".to_string(),
        |links| {
            let mut keys: Vec<&str> = links.keys().map(String::as_str).collect();
            keys.sort_unstable();
            keys.join(", ")
        },
    );
    Err(anyhow::anyhow!(
        "'{}' (mimeType: {}) has no default export format; pass an explicit export MIME type \
         (CLI: --export-mime-type, MCP drive_file_read: export_mime_type). Supported export \
         MIME types: {available}",
        meta.name,
        meta.mime_type,
    ))
}

/// The default export MIME type for a Google-native `mime_type`, or `None`
/// when there isn't a safe one (Forms, Drawings, Apps Script, Sites, ...).
fn default_export_mime_type(mime_type: &str) -> Option<&'static str> {
    match mime_type {
        GOOGLE_DOC => Some("text/markdown"),
        GOOGLE_SHEET => Some("text/csv"),
        GOOGLE_SLIDES => Some("text/plain"),
        _ => None,
    }
}

/// Whether `mime_type` is safe to print directly to a terminal (or return
/// inline from the `drive_file_read` MCP tool, its other `pub(crate)`
/// consumer — issue #1525).
pub(crate) fn is_texty(mime_type: &str) -> bool {
    mime_type.starts_with("text/") || mime_type == "application/json"
}

/// Encodes `bytes` as a lowercase hex string. No `hex` crate dependency
/// exists in this project — this is small enough not to need one.
pub(crate) fn to_hex_string(bytes: &[u8]) -> String {
    const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut hex = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        hex.push(HEX_DIGITS[(byte >> 4) as usize] as char);
        hex.push(HEX_DIGITS[(byte & 0x0f) as usize] as char);
    }
    hex
}

/// Recomputes the SHA-256 checksum of `bytes` and checks it case-
/// insensitively against `expected` (Drive's reported `sha256Checksum`).
///
/// `pub(crate)`: also reused by the `drive_file_read` MCP tool's `verify`
/// param (`src/mcp/drive_tools.rs`).
pub(crate) fn verify_sha256_checksum(bytes: &[u8], expected: Option<&str>) -> Result<()> {
    let expected = expected.context(
        "--verify requires this file to have a sha256Checksum, but Drive did not report one \
         for it",
    )?;
    let actual = to_hex_string(&Sha256::digest(bytes));
    anyhow::ensure!(
        actual.eq_ignore_ascii_case(expected),
        "sha256 checksum mismatch: expected {expected}, got {actual}"
    );
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveScope};
    use crate::utils::secret::Secret;

    fn test_credentials() -> DriveCredentials {
        DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveScope::ReadOnly,
        }
    }

    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> DriveClient {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token",
                    "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;

        let mut client = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    // ── render_metadata_table ────────────────────────────────────────

    #[test]
    fn render_metadata_table_writes_all_present_fields() {
        let file = DriveFile {
            id: "f1".to_string(),
            name: "report.pdf".to_string(),
            mime_type: "application/pdf".to_string(),
            size: Some("1024".to_string()),
            modified_time: Some("2026-01-01T00:00:00.000Z".to_string()),
            parents: vec!["folder1".to_string()],
            web_view_link: Some("https://drive.google.com/file/d/f1/view".to_string()),
            md5_checksum: Some("5d41402abc4b2a76b9719d911017c592".to_string()),
            sha1_checksum: Some("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d".to_string()),
            sha256_checksum: Some(
                "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08".to_string(),
            ),
            ..Default::default()
        };
        let mut buf = Vec::new();
        render_metadata_table(&file, &mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert!(text.contains("Id: f1"));
        assert!(text.contains("Name: report.pdf"));
        assert!(text.contains("MimeType: application/pdf"));
        assert!(text.contains("Size: 1024"));
        assert!(text.contains("Modified: 2026-01-01T00:00:00.000Z"));
        assert!(text.contains("Parents: folder1"));
        assert!(text.contains("WebViewLink: https://drive.google.com/file/d/f1/view"));
        assert!(text.contains("Md5Checksum: 5d41402abc4b2a76b9719d911017c592"));
        assert!(text.contains("Sha1Checksum: aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"));
        assert!(text.contains(
            "Sha256Checksum: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
        ));
    }

    #[test]
    fn render_metadata_table_omits_absent_fields() {
        let file = DriveFile {
            id: "f1".to_string(),
            name: "n".to_string(),
            ..Default::default()
        };
        let mut buf = Vec::new();
        render_metadata_table(&file, &mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert_eq!(text, "Id: f1\nName: n\nMimeType: \n");
    }

    #[test]
    fn render_metadata_table_strips_control_bytes_from_server_strings() {
        let file = DriveFile {
            id: "f1".to_string(),
            name: "evil\x1b[31mname".to_string(),
            mime_type: "text/plain\r\x07".to_string(),
            parents: vec!["fold\x1b[0mer".to_string()],
            web_view_link: Some("https://example.com/\u{9b}2J".to_string()),
            ..Default::default()
        };
        let mut buf = Vec::new();
        render_metadata_table(&file, &mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert!(
            !text.contains(|c: char| c.is_control() && c != '\n'),
            "{text:?}"
        );
        assert!(text.contains("evil[31mname"), "{text:?}");
    }

    // ── default_export_mime_type ──────────────────────────────────────

    #[test]
    fn default_export_mime_type_maps_docs_sheets_slides() {
        assert_eq!(default_export_mime_type(GOOGLE_DOC), Some("text/markdown"));
        assert_eq!(default_export_mime_type(GOOGLE_SHEET), Some("text/csv"));
        assert_eq!(default_export_mime_type(GOOGLE_SLIDES), Some("text/plain"));
    }

    #[test]
    fn default_export_mime_type_none_for_other_google_native_and_non_native() {
        assert_eq!(
            default_export_mime_type("application/vnd.google-apps.form"),
            None
        );
        assert_eq!(default_export_mime_type("application/pdf"), None);
    }

    // ── resolve_export_mime_type ───────────────────────────────────────

    #[test]
    fn resolve_export_mime_type_explicit_wins_over_default() {
        let meta = DriveFile {
            mime_type: GOOGLE_DOC.to_string(),
            ..Default::default()
        };
        let result = resolve_export_mime_type(&meta, Some("application/pdf")).unwrap();
        assert_eq!(result, "application/pdf");
    }

    #[test]
    fn resolve_export_mime_type_falls_back_to_doc_default() {
        let meta = DriveFile {
            mime_type: GOOGLE_DOC.to_string(),
            ..Default::default()
        };
        assert_eq!(
            resolve_export_mime_type(&meta, None).unwrap(),
            "text/markdown"
        );
    }

    #[test]
    fn resolve_export_mime_type_falls_back_to_sheet_default() {
        let meta = DriveFile {
            mime_type: GOOGLE_SHEET.to_string(),
            ..Default::default()
        };
        assert_eq!(resolve_export_mime_type(&meta, None).unwrap(), "text/csv");
    }

    #[test]
    fn resolve_export_mime_type_falls_back_to_slides_default() {
        let meta = DriveFile {
            mime_type: GOOGLE_SLIDES.to_string(),
            ..Default::default()
        };
        assert_eq!(resolve_export_mime_type(&meta, None).unwrap(), "text/plain");
    }

    #[test]
    fn resolve_export_mime_type_errors_listing_export_links_keys_for_unsupported_type() {
        let mut links = std::collections::HashMap::new();
        links.insert("application/pdf".to_string(), "url1".to_string());
        links.insert("text/plain".to_string(), "url2".to_string());
        let meta = DriveFile {
            name: "myform".to_string(),
            mime_type: "application/vnd.google-apps.form".to_string(),
            export_links: Some(links),
            ..Default::default()
        };
        let err = resolve_export_mime_type(&meta, None).unwrap_err();
        assert!(err.to_string().contains("--export-mime-type"));
        assert!(err.to_string().contains("application/pdf"));
        assert!(err.to_string().contains("text/plain"));
    }

    #[test]
    fn resolve_export_mime_type_errors_with_none_when_export_links_absent() {
        let meta = DriveFile {
            name: "myform".to_string(),
            mime_type: "application/vnd.google-apps.form".to_string(),
            ..Default::default()
        };
        let err = resolve_export_mime_type(&meta, None).unwrap_err();
        assert!(err.to_string().contains("(none)"));
    }

    // ── is_texty ────────────────────────────────────────────────────

    #[test]
    fn is_texty_true_for_text_star_and_json() {
        assert!(is_texty("text/plain"));
        assert!(is_texty("text/csv"));
        assert!(is_texty("application/json"));
    }

    #[test]
    fn is_texty_false_for_binary() {
        assert!(!is_texty("application/pdf"));
        assert!(!is_texty("image/png"));
    }

    // ── to_hex_string / verify_sha256_checksum ─────────────────────────

    #[test]
    fn to_hex_string_encodes_known_bytes_as_lowercase_hex() {
        assert_eq!(to_hex_string(&[0x00, 0x0f, 0xab, 0xff]), "000fabff");
    }

    #[test]
    fn to_hex_string_of_empty_input_is_empty() {
        assert_eq!(to_hex_string(&[]), "");
    }

    #[test]
    fn verify_sha256_checksum_succeeds_on_a_matching_digest() {
        // sha256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
        let expected = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824";
        verify_sha256_checksum(b"hello", Some(expected)).unwrap();
    }

    #[test]
    fn verify_sha256_checksum_is_case_insensitive() {
        let expected = "2CF24DBA5FB0A30E26E83B2AC5B9E29E1B161E5C1FA7425E73043362938B9824";
        verify_sha256_checksum(b"hello", Some(expected)).unwrap();
    }

    #[test]
    fn verify_sha256_checksum_fails_clearly_on_mismatch() {
        let err = verify_sha256_checksum(b"hello", Some("not-the-real-hash")).unwrap_err();
        assert!(err.to_string().contains("checksum mismatch"), "{err}");
    }

    #[test]
    fn verify_sha256_checksum_fails_clearly_when_absent() {
        let err = verify_sha256_checksum(b"hello", None).unwrap_err();
        assert!(err.to_string().contains("sha256Checksum"), "{err}");
    }

    // ── run_read (metadata) ────────────────────────────────────────

    #[tokio::test]
    async fn run_read_table_path_writes_to_stdout() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n",
                })),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "f1",
            false,
            None,
            None,
            false,
            &OutputFormat::Table,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_json_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n",
                })),
            )
            .mount(&server)
            .await;

        run_read(&client, "f1", false, None, None, false, &OutputFormat::Json)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_metadata_propagates_get_metadata_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/missing"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;

        let err = run_read(
            &client,
            "missing",
            false,
            None,
            None,
            false,
            &OutputFormat::Table,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    #[tokio::test]
    async fn run_read_rejects_out_file_without_content() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;

        let err = run_read(
            &client,
            "f1",
            false,
            None,
            Some("/tmp/out.txt"),
            false,
            &OutputFormat::Table,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("--out-file requires --content"));
    }

    #[tokio::test]
    async fn run_read_rejects_verify_without_content() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;

        let err = run_read(&client, "f1", false, None, None, true, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("--verify requires --content"));
    }

    // ── run_read (content) ─────────────────────────────────────────

    #[tokio::test]
    async fn run_read_content_non_google_native_downloads_via_alt_media() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"hello".to_vec()))
            .expect(1)
            .mount(&server)
            .await;

        run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_content_rejects_folder_with_actionable_error() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "My Folder", "mimeType": GOOGLE_FOLDER,
                })),
            )
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        let message = err.to_string();
        assert!(message.contains("'My Folder' is a folder"), "{message}");
        assert!(message.contains("drive search"), "{message}");
    }

    #[tokio::test]
    async fn run_read_content_rejects_shortcut_with_actionable_error() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "My Shortcut", "mimeType": GOOGLE_SHORTCUT,
                })),
            )
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        let message = err.to_string();
        assert!(message.contains("'My Shortcut' is a shortcut"), "{message}");
    }

    #[tokio::test]
    async fn run_read_content_google_doc_default_exports_text_markdown() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": GOOGLE_DOC,
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1/export"))
            .and(wiremock::matchers::query_param("mimeType", "text/markdown"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"# Title".to_vec()))
            .expect(1)
            .mount(&server)
            .await;

        run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_content_google_sheet_default_exports_text_csv() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": GOOGLE_SHEET,
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1/export"))
            .and(wiremock::matchers::query_param("mimeType", "text/csv"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"a,b\n1,2".to_vec()))
            .expect(1)
            .mount(&server)
            .await;

        run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_content_google_slides_default_exports_text_plain() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": GOOGLE_SLIDES,
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1/export"))
            .and(wiremock::matchers::query_param("mimeType", "text/plain"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_bytes(b"slide text".to_vec()),
            )
            .expect(1)
            .mount(&server)
            .await;

        run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_content_explicit_export_mime_type_overrides_default() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": GOOGLE_DOC,
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1/export"))
            .and(wiremock::matchers::query_param(
                "mimeType",
                "application/pdf",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"%PDF".to_vec()))
            .expect(1)
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("doc.pdf");
        run_read(
            &client,
            "f1",
            true,
            Some("application/pdf"),
            Some(path.to_str().unwrap()),
            false,
            &OutputFormat::Table,
        )
        .await
        .unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"%PDF");
    }

    #[tokio::test]
    async fn run_read_content_other_google_native_without_export_mime_type_errors_listing_export_links(
    ) {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1",
                    "name": "myform",
                    "mimeType": "application/vnd.google-apps.form",
                    "exportLinks": {"application/zip": "url"},
                })),
            )
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("--export-mime-type"));
        assert!(err.to_string().contains("application/zip"));
    }

    #[tokio::test]
    async fn run_read_content_writes_out_file_and_prints_summary_byte_exact() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "application/pdf",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"%PDF-1.4".to_vec()))
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("out.pdf");
        run_read(
            &client,
            "f1",
            true,
            None,
            Some(path.to_str().unwrap()),
            false,
            &OutputFormat::Table,
        )
        .await
        .unwrap();
        assert_eq!(std::fs::read(&path).unwrap(), b"%PDF-1.4");
    }

    #[tokio::test]
    async fn run_read_content_prints_texty_content_without_out_file() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"hello".to_vec()))
            .mount(&server)
            .await;

        run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_content_refuses_binary_content_without_out_file() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "application/pdf",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"%PDF".to_vec()))
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("refusing to print binary content"));
    }

    #[tokio::test]
    async fn run_read_content_invalid_utf8_texty_content_without_out_file_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_bytes(vec![0xff, 0xfe, 0xfd]),
            )
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not valid UTF-8"));
    }

    #[tokio::test]
    async fn run_read_content_propagates_export_api_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": GOOGLE_DOC,
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1/export"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("500"));
    }

    #[tokio::test]
    async fn run_read_content_propagates_download_api_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(500).set_body_string("boom"))
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, false, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("500"));
    }

    // ── run_read (content, --verify) ─────────────────────────────────

    #[tokio::test]
    async fn run_read_content_verify_succeeds_on_matching_checksum() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                    "sha256Checksum": "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"hello".to_vec()))
            .mount(&server)
            .await;

        run_read(&client, "f1", true, None, None, true, &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_read_content_verify_fails_clearly_on_mismatch() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                    "sha256Checksum": "not-the-real-hash",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"hello".to_vec()))
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, true, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("checksum mismatch"), "{err}");
    }

    #[tokio::test]
    async fn run_read_content_verify_fails_clearly_when_no_checksum_reported() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": "text/plain",
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param("alt", "media"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_bytes(b"hello".to_vec()))
            .mount(&server)
            .await;

        let err = run_read(&client, "f1", true, None, None, true, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("sha256Checksum"), "{err}");
    }

    #[tokio::test]
    async fn run_read_content_verify_rejects_google_native_file_before_exporting() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f1"))
            .and(wiremock::matchers::query_param_is_missing("alt"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "f1", "name": "n", "mimeType": GOOGLE_DOC,
                })),
            )
            .mount(&server)
            .await;
        // No mock for /drive/v3/files/f1/export — if --verify's Google-native
        // rejection didn't run before the export call, this test would 404
        // rather than surfacing the expected error.

        let err = run_read(&client, "f1", true, None, None, true, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("--verify is not supported for Google-native files"),
            "{err}"
        );
    }

    // ── ReadCommand::execute glue ────────────────────────────────────

    #[tokio::test]
    async fn execute_passes_file_id_through() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/f42"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "f42", "name": "n"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let cmd = ReadCommand {
            file_id: "f42".to_string(),
            content: false,
            export_mime_type: None,
            out_file: None,
            verify: false,
            output: OutputFormat::Json,
        };
        cmd.execute(&client).await.unwrap();
    }
}