slashmail 0.1.0

CLI for searching, managing, and bulk-operating on emails via IMAP
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
mod connection;
mod delete;
mod display;
mod search;

use anyhow::{bail, Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use comfy_table::{presets::UTF8_FULL_CONDENSED, Cell, Color, Table};
use indicatif::{ProgressBar, ProgressStyle};
use regex::Regex;
use std::path::PathBuf;
use std::time::Duration;
use zeroize::Zeroize;

fn spinner(msg: &str) -> ProgressBar {
    let pb = ProgressBar::new_spinner();
    pb.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.cyan} {msg}")
            .unwrap(),
    );
    pb.set_message(msg.to_string());
    pb.enable_steady_tick(Duration::from_millis(80));
    pb
}

#[derive(Parser)]
#[command(
    name = "slashmail",
    about = "IMAP CLI for searching, managing, and inspecting email"
)]
struct Cli {
    /// IMAP host
    #[arg(long, default_value = "127.0.0.1", global = true)]
    host: String,

    /// IMAP port (default: 1143 plain, 993 TLS)
    #[arg(long, global = true)]
    port: Option<u16>,

    /// Use TLS (required for remote IMAP servers)
    #[arg(long, global = true)]
    tls: bool,

    /// IMAP username
    #[arg(short, long, env = "SLASHMAIL_USER", global = true)]
    user: Option<String>,

    /// IMAP password (or SLASHMAIL_PASS env; prompts if missing)
    #[arg(skip)]
    _pass_placeholder: (),

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Search messages by criteria
    Search(SearchArgs),
    /// Search + delete matching messages (move to Trash)
    Delete(DeleteArgs),
    /// Search + move matching messages to a folder
    Move(MoveArgs),
    /// Search + export matching messages as .eml files
    Export(ExportArgs),
    /// Search + set/unset flags on matching messages
    Mark(MarkArgs),
    /// Count matching messages (no FETCH)
    Count(CountArgs),
    /// Show mailbox quota usage
    Quota,
    /// Show per-folder message statistics
    Status,
    /// Generate shell completions
    Completions {
        /// Shell to generate for (bash, zsh, fish, powershell, elvish)
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
    /// Generate man page
    #[command(hide = true)]
    Manpage,
}

#[derive(Parser)]
struct FilterArgs {
    /// Folder to search
    #[arg(short, long, default_value = "INBOX")]
    folder: String,

    /// Search across all folders (excludes Trash, Spam)
    #[arg(long)]
    all_folders: bool,

    /// Subject contains
    #[arg(long)]
    subject: Option<String>,

    /// From address contains
    #[arg(long)]
    from: Option<String>,

    /// Messages since date (YYYY-MM-DD)
    #[arg(long)]
    since: Option<String>,

    /// Messages before date (YYYY-MM-DD)
    #[arg(long)]
    before: Option<String>,

    /// Messages larger than N bytes (supports K/M suffix)
    #[arg(long)]
    larger: Option<String>,
}

#[derive(Parser)]
struct SearchArgs {
    #[command(flatten)]
    filter: FilterArgs,

    /// Limit number of results
    #[arg(short = 'n', long)]
    limit: Option<usize>,
}

#[derive(Parser)]
struct DeleteArgs {
    #[command(flatten)]
    filter: FilterArgs,

    /// Limit number of messages to act on
    #[arg(short = 'n', long)]
    limit: Option<usize>,

    /// Skip confirmation (batch mode)
    #[arg(long)]
    yes: bool,

    /// Show what would be deleted without acting
    #[arg(long)]
    dry_run: bool,
}

#[derive(Parser)]
struct MoveArgs {
    #[command(flatten)]
    filter: FilterArgs,

    /// Destination folder
    #[arg(long)]
    to: String,

    /// Limit number of messages to act on
    #[arg(short = 'n', long)]
    limit: Option<usize>,

    /// Skip confirmation
    #[arg(long)]
    yes: bool,

    /// Show what would be moved without acting
    #[arg(long)]
    dry_run: bool,
}

#[derive(Parser)]
struct ExportArgs {
    #[command(flatten)]
    filter: FilterArgs,

    /// Limit number of results
    #[arg(short = 'n', long)]
    limit: Option<usize>,

    /// Output directory for .eml files (default: current directory)
    #[arg(short, long)]
    output_dir: Option<PathBuf>,

    /// Skip confirmation
    #[arg(long)]
    yes: bool,

    /// Overwrite existing .eml files
    #[arg(long)]
    force: bool,
}

#[derive(Parser)]
struct MarkArgs {
    #[command(flatten)]
    filter: FilterArgs,

    /// Mark as read (\Seen)
    #[arg(long)]
    read: bool,

    /// Mark as unread (remove \Seen)
    #[arg(long)]
    unread: bool,

    /// Set \Flagged
    #[arg(long)]
    flagged: bool,

    /// Remove \Flagged
    #[arg(long)]
    unflagged: bool,

    /// Limit number of messages to act on
    #[arg(short = 'n', long)]
    limit: Option<usize>,

    /// Skip confirmation
    #[arg(long)]
    yes: bool,

    /// Show what would be changed without acting
    #[arg(long)]
    dry_run: bool,
}

#[derive(Parser)]
struct CountArgs {
    #[command(flatten)]
    filter: FilterArgs,
}

impl FilterArgs {
    fn to_criteria(&self, limit: Option<usize>) -> search::SearchCriteria {
        search::SearchCriteria {
            folder: self.folder.clone(),
            all_folders: self.all_folders,
            subject: self.subject.clone(),
            from: self.from.clone(),
            since: self.since.clone(),
            before: self.before.clone(),
            larger: self.larger.clone(),
            limit,
        }
    }
}

fn get_password() -> Result<String> {
    if let Ok(p) = std::env::var("SLASHMAIL_PASS") {
        if !p.is_empty() {
            return Ok(p);
        }
    }
    inquire::Password::new("IMAP password:")
        .without_confirmation()
        .prompt()
        .context("Password prompt failed")
}

fn cmd_quota(session: &mut connection::ImapSession) -> Result<()> {
    if !session.has_capability("QUOTA") {
        bail!("Server does not support QUOTA extension (RFC 2087)");
    }

    let sp = spinner("Fetching quota...");
    let response = session
        .run_command_and_read_response("GETQUOTAROOT INBOX")
        .context("GETQUOTAROOT failed")?;
    sp.finish_and_clear();

    let text = String::from_utf8_lossy(&response);

    // Parse: * QUOTA "root" (STORAGE used limit) (MESSAGE used limit) ...
    let re = Regex::new(r"(?i)\*\s+QUOTA\s+.*?\(([^)]+)\)").unwrap();
    let resource_re = Regex::new(r"(\w+)\s+(\d+)\s+(\d+)").unwrap();

    let mut rows: Vec<(String, u64, u64)> = Vec::new();
    for cap in re.captures_iter(&text) {
        let inner = &cap[1];
        if let Some(m) = resource_re.captures(inner) {
            let name = m[1].to_string();
            let used: u64 = m[2].parse().unwrap_or(0);
            let limit: u64 = m[3].parse().unwrap_or(0);
            rows.push((name, used, limit));
        }
    }

    if rows.is_empty() {
        println!("No quota information available.");
        return Ok(());
    }

    let mut table = Table::new();
    table.load_preset(UTF8_FULL_CONDENSED);
    table.set_header(vec!["Resource", "Used", "Limit", "Usage"]);

    for (name, used, limit) in &rows {
        let (used_str, limit_str) = if name.eq_ignore_ascii_case("STORAGE") {
            // STORAGE values are in KB
            (
                display::format_size(used * 1024),
                display::format_size(limit * 1024),
            )
        } else {
            (used.to_string(), limit.to_string())
        };

        let pct = if *limit > 0 {
            *used as f64 / *limit as f64 * 100.0
        } else {
            0.0
        };
        let pct_str = format!("{pct:.1}%");

        let mut row = vec![Cell::new(name), Cell::new(&used_str), Cell::new(&limit_str)];
        let pct_cell = if pct >= 90.0 {
            Cell::new(&pct_str).fg(Color::Red)
        } else if pct >= 75.0 {
            Cell::new(&pct_str).fg(Color::Yellow)
        } else {
            Cell::new(&pct_str)
        };
        row.push(pct_cell);
        table.add_row(row);
    }

    println!("{table}");
    Ok(())
}

fn cmd_status(session: &mut connection::ImapSession) -> Result<()> {
    let sp = spinner("Fetching folder status...");
    let folders = session
        .list(Some(""), Some("*"))
        .context("Failed to list folders")?;
    let folder_names: Vec<String> = folders.iter().map(|f| f.name().to_string()).collect();

    let mut table = Table::new();
    table.load_preset(UTF8_FULL_CONDENSED);
    table.set_header(vec!["Folder", "Messages", "Unseen", "Recent"]);

    let mut total_messages: u32 = 0;
    let mut total_unseen: u32 = 0;
    let mut total_recent: u32 = 0;

    let re = Regex::new(r"(?i)\*\s+STATUS\s+.*?\(([^)]*)\)").unwrap();

    for name in &folder_names {
        let quoted = search::imap_quote(name);
        let cmd = format!("STATUS {quoted} (MESSAGES UNSEEN RECENT)");
        let response = match session.run_command_and_read_response(&cmd) {
            Ok(r) => r,
            Err(_) => {
                table.add_row(vec![name.as_str(), "?", "?", "?"]);
                continue;
            }
        };

        let text = String::from_utf8_lossy(&response);
        let mut messages: u32 = 0;
        let mut unseen: u32 = 0;
        let mut recent: u32 = 0;

        if let Some(cap) = re.captures(&text) {
            let attrs = &cap[1];
            // Parse key-value pairs: MESSAGES 142 UNSEEN 12 RECENT 3
            let tokens: Vec<&str> = attrs.split_whitespace().collect();
            for pair in tokens.chunks(2) {
                if pair.len() == 2 {
                    let val: u32 = pair[1].parse().unwrap_or(0);
                    match pair[0].to_uppercase().as_str() {
                        "MESSAGES" => messages = val,
                        "UNSEEN" => unseen = val,
                        "RECENT" => recent = val,
                        _ => {}
                    }
                }
            }
        }

        total_messages += messages;
        total_unseen += unseen;
        total_recent += recent;

        table.add_row(vec![
            name.as_str(),
            &messages.to_string(),
            &unseen.to_string(),
            &recent.to_string(),
        ]);
    }

    sp.finish_and_clear();

    // Total row
    table.add_row(vec![
        Cell::new("Total").fg(Color::Cyan),
        Cell::new(total_messages).fg(Color::Cyan),
        Cell::new(total_unseen).fg(Color::Cyan),
        Cell::new(total_recent).fg(Color::Cyan),
    ]);

    println!("{table}");
    Ok(())
}

fn cmd_export(session: &mut connection::ImapSession, args: &ExportArgs) -> Result<()> {
    let criteria = args.filter.to_criteria(args.limit);
    let sp = spinner("Searching...");
    let messages = search::search(session, &criteria)?;
    sp.finish_and_clear();

    if messages.is_empty() {
        println!("No messages found.");
        return Ok(());
    }

    display::display_messages(&messages);

    let out_dir = args
        .output_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from("."));

    if !args.yes {
        let confirm = inquire::Confirm::new(&format!(
            "Export {} message(s) to {}?",
            messages.len(),
            out_dir.display()
        ))
        .with_default(false)
        .prompt()
        .context("Prompt failed")?;

        if !confirm {
            println!("Aborted.");
            return Ok(());
        }
    }

    std::fs::create_dir_all(&out_dir)
        .with_context(|| format!("Failed to create directory '{}'", out_dir.display()))?;

    // Group by folder
    let mut by_folder: std::collections::HashMap<String, Vec<u32>> =
        std::collections::HashMap::new();
    for msg in &messages {
        let folder = msg
            .folder
            .clone()
            .unwrap_or_else(|| criteria.folder.clone());
        by_folder.entry(folder).or_default().push(msg.uid);
    }

    let sp = spinner("Exporting...");
    let mut exported = 0usize;
    let mut skipped = 0usize;

    for (folder, uids) in &by_folder {
        session
            .select(folder)
            .with_context(|| format!("Failed to select '{folder}'"))?;

        for chunk in &search::build_uid_set(uids) {
            let fetches = session
                .uid_fetch(chunk, "BODY.PEEK[]")
                .with_context(|| format!("Failed to fetch messages from '{folder}'"))?;

            for fetch in fetches.iter() {
                let uid = match fetch.uid {
                    Some(u) => u,
                    None => continue,
                };
                if let Some(body) = fetch.body() {
                    let path = out_dir.join(format!("{uid}.eml"));
                    if path.exists() && !args.force {
                        skipped += 1;
                        continue;
                    }
                    std::fs::write(&path, body)
                        .with_context(|| format!("Failed to write '{}'", path.display()))?;
                    exported += 1;
                }
            }
        }
    }

    sp.finish_and_clear();
    print!("Exported {exported} message(s) to {}", out_dir.display());
    if skipped > 0 {
        print!(" ({skipped} skipped, already exist)");
    }
    println!();
    Ok(())
}

fn validate_mark_flags(read: bool, unread: bool, flagged: bool, unflagged: bool) -> Result<()> {
    if !read && !unread && !flagged && !unflagged {
        bail!("Specify at least one flag: --read, --unread, --flagged, --unflagged");
    }
    if read && unread {
        bail!("Cannot use --read and --unread together");
    }
    if flagged && unflagged {
        bail!("Cannot use --flagged and --unflagged together");
    }
    Ok(())
}

fn mark_store_ops(read: bool, unread: bool, flagged: bool, unflagged: bool) -> Vec<String> {
    let mut ops = Vec::new();
    if read {
        ops.push("+FLAGS (\\Seen)".to_string());
    }
    if unread {
        ops.push("-FLAGS (\\Seen)".to_string());
    }
    if flagged {
        ops.push("+FLAGS (\\Flagged)".to_string());
    }
    if unflagged {
        ops.push("-FLAGS (\\Flagged)".to_string());
    }
    ops
}

fn mark_action_desc(read: bool, unread: bool, flagged: bool, unflagged: bool) -> String {
    let mut actions = Vec::new();
    if read {
        actions.push("mark read");
    }
    if unread {
        actions.push("mark unread");
    }
    if flagged {
        actions.push("flag");
    }
    if unflagged {
        actions.push("unflag");
    }
    actions.join(" + ")
}

fn cmd_mark(session: &mut connection::ImapSession, args: &MarkArgs) -> Result<()> {
    validate_mark_flags(args.read, args.unread, args.flagged, args.unflagged)?;

    let criteria = args.filter.to_criteria(args.limit);
    let sp = spinner("Searching...");
    let messages = search::search(session, &criteria)?;
    sp.finish_and_clear();

    if messages.is_empty() {
        println!("No messages match the criteria.");
        return Ok(());
    }

    display::display_messages(&messages);

    let action_desc = mark_action_desc(args.read, args.unread, args.flagged, args.unflagged);

    if args.dry_run {
        println!(
            "Dry run: would {action_desc} {} message(s).",
            messages.len()
        );
        return Ok(());
    }

    if !args.yes {
        let confirm =
            inquire::Confirm::new(&format!("{action_desc} {} message(s)?", messages.len()))
                .with_default(false)
                .prompt()
                .context("Prompt failed")?;

        if !confirm {
            println!("Aborted.");
            return Ok(());
        }
    }

    let store_ops = mark_store_ops(args.read, args.unread, args.flagged, args.unflagged);

    let sp = spinner("Updating flags...");

    // Group by folder
    let mut by_folder: std::collections::HashMap<String, Vec<u32>> =
        std::collections::HashMap::new();
    for msg in &messages {
        let folder = msg
            .folder
            .clone()
            .unwrap_or_else(|| criteria.folder.clone());
        by_folder.entry(folder).or_default().push(msg.uid);
    }

    let mut total = 0usize;
    for (folder, uids) in &by_folder {
        session
            .select(folder)
            .with_context(|| format!("Failed to select '{folder}'"))?;

        for chunk in &search::build_uid_set(uids) {
            for op in &store_ops {
                session
                    .uid_store(chunk, op)
                    .with_context(|| format!("Failed to store flags in '{folder}'"))?;
            }
        }

        total += uids.len();
    }

    sp.finish_and_clear();
    println!("Updated {total} message(s).");
    Ok(())
}

fn cmd_count(session: &mut connection::ImapSession, args: &CountArgs) -> Result<()> {
    let criteria = args.filter.to_criteria(None);
    let query = search::build_query(&criteria)?;

    let sp = spinner("Counting...");

    if criteria.all_folders {
        let folders = session
            .list(Some(""), Some("*"))
            .context("Failed to list folders")?;
        let folder_names: Vec<String> = folders
            .iter()
            .map(|f| f.name().to_string())
            .filter(|n| !search::folders_to_skip(n))
            .collect();

        let mut grand_total = 0usize;
        let mut results: Vec<(String, usize)> = Vec::new();

        for folder in &folder_names {
            match session.select(folder) {
                Ok(_) => {}
                Err(e) => {
                    eprintln!("Warning: skipping folder '{folder}': {e}");
                    continue;
                }
            }
            match session.uid_search(&query) {
                Ok(uids) => {
                    let count = uids.len();
                    if count > 0 {
                        results.push((folder.clone(), count));
                        grand_total += count;
                    }
                }
                Err(e) => {
                    eprintln!("Warning: search failed in '{folder}': {e}");
                }
            }
        }

        sp.finish_and_clear();

        if results.is_empty() {
            println!("0 message(s) match.");
        } else {
            for (folder, count) in &results {
                println!("{count} message(s) in {folder}");
            }
            if results.len() > 1 {
                println!("{grand_total} message(s) total");
            }
        }
    } else {
        session
            .select(&criteria.folder)
            .with_context(|| format!("Failed to select '{}'", criteria.folder))?;

        let uids = session.uid_search(&query).context("IMAP SEARCH failed")?;
        sp.finish_and_clear();
        println!("{} message(s) in {}", uids.len(), criteria.folder);
    }

    Ok(())
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Handle commands that don't need an IMAP connection
    match &cli.command {
        Commands::Completions { shell } => {
            clap_complete::generate(
                *shell,
                &mut Cli::command(),
                "slashmail",
                &mut std::io::stdout(),
            );
            return Ok(());
        }
        Commands::Manpage => {
            clap_mangen::Man::new(Cli::command()).render(&mut std::io::stdout())?;
            return Ok(());
        }
        _ => {}
    }

    let port = cli.port.unwrap_or(if cli.tls { 993 } else { 1143 });
    let user = cli.user.ok_or_else(|| {
        anyhow::anyhow!("IMAP username required (use -u/--user or SLASHMAIL_USER env)")
    })?;
    let mut pass = get_password()?;

    let sp = spinner("Connecting...");
    let mut session = connection::connect(&cli.host, port, cli.tls, &user, &pass)?;
    sp.finish_and_clear();

    // Clear password from memory
    pass.zeroize();

    let result = match &cli.command {
        Commands::Search(args) => {
            let criteria = args.filter.to_criteria(args.limit);
            let sp = spinner("Searching...");
            let messages = search::search(&mut session, &criteria)?;
            sp.finish_and_clear();
            display::display_messages(&messages);
            Ok(())
        }
        Commands::Delete(args) => {
            let criteria = args.filter.to_criteria(args.limit);
            delete::delete(&mut session, &criteria, args.yes, args.dry_run)
        }
        Commands::Move(args) => {
            let criteria = args.filter.to_criteria(args.limit);
            delete::search_and_move(&mut session, &criteria, &args.to, args.yes, args.dry_run)
        }
        Commands::Export(args) => cmd_export(&mut session, args),
        Commands::Mark(args) => cmd_mark(&mut session, args),
        Commands::Count(args) => cmd_count(&mut session, args),
        Commands::Quota => cmd_quota(&mut session),
        Commands::Status => cmd_status(&mut session),
        Commands::Completions { .. } | Commands::Manpage => unreachable!(),
    };

    let _ = session.logout();
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn validate_mark_flags_no_flags() {
        assert!(validate_mark_flags(false, false, false, false).is_err());
    }

    #[test]
    fn validate_mark_flags_read_and_unread() {
        assert!(validate_mark_flags(true, true, false, false).is_err());
    }

    #[test]
    fn validate_mark_flags_flagged_and_unflagged() {
        assert!(validate_mark_flags(false, false, true, true).is_err());
    }

    #[test]
    fn validate_mark_flags_single_flag() {
        assert!(validate_mark_flags(true, false, false, false).is_ok());
        assert!(validate_mark_flags(false, true, false, false).is_ok());
        assert!(validate_mark_flags(false, false, true, false).is_ok());
        assert!(validate_mark_flags(false, false, false, true).is_ok());
    }

    #[test]
    fn validate_mark_flags_valid_combo() {
        assert!(validate_mark_flags(true, false, true, false).is_ok());
        assert!(validate_mark_flags(false, true, false, true).is_ok());
        assert!(validate_mark_flags(true, false, false, true).is_ok());
    }

    #[test]
    fn mark_store_ops_read() {
        assert_eq!(
            mark_store_ops(true, false, false, false),
            vec!["+FLAGS (\\Seen)"]
        );
    }

    #[test]
    fn mark_store_ops_unread() {
        assert_eq!(
            mark_store_ops(false, true, false, false),
            vec!["-FLAGS (\\Seen)"]
        );
    }

    #[test]
    fn mark_store_ops_flagged() {
        assert_eq!(
            mark_store_ops(false, false, true, false),
            vec!["+FLAGS (\\Flagged)"]
        );
    }

    #[test]
    fn mark_store_ops_unflagged() {
        assert_eq!(
            mark_store_ops(false, false, false, true),
            vec!["-FLAGS (\\Flagged)"]
        );
    }

    #[test]
    fn mark_store_ops_combo() {
        let ops = mark_store_ops(true, false, true, false);
        assert_eq!(ops, vec!["+FLAGS (\\Seen)", "+FLAGS (\\Flagged)"]);
    }

    #[test]
    fn mark_action_desc_single() {
        assert_eq!(mark_action_desc(true, false, false, false), "mark read");
        assert_eq!(mark_action_desc(false, true, false, false), "mark unread");
        assert_eq!(mark_action_desc(false, false, true, false), "flag");
        assert_eq!(mark_action_desc(false, false, false, true), "unflag");
    }

    #[test]
    fn mark_action_desc_combo() {
        assert_eq!(
            mark_action_desc(true, false, true, false),
            "mark read + flag"
        );
    }
}