himalaya 2.0.0

CLI to manage emails
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
//! Shared MIME-building helpers for the built-in `compose`, `reply`
//! and `forward` subcommands.
//!
//! Each subcommand has its own clap struct (different positional /
//! optional args), but they all collapse into the same set of fields
//! once the source message — if any — is fetched. The helpers here
//! accept those fields and assemble an RFC 5322 message with
//! `mail_builder` (plus reply/forward header derivation via
//! `mail_parser`).
//!
//! The `-with` subcommands delegate composition entirely to an
//! external command and never go through this module.

use std::{
    io::{IsTerminal, Read as _, stdin},
    path::{Path, PathBuf},
};

use anyhow::{Result, anyhow};
use clap::ValueEnum;
use mail_builder::{
    MessageBuilder,
    headers::{address::Address, raw::Raw},
};
use mail_parser::{HeaderValue, MessageParser};

/// How a quoted source body is laid out relative to the user's body
/// when replying or forwarding.
#[derive(Clone, Copy, Debug, ValueEnum)]
#[clap(rename_all = "kebab-case")]
pub enum PostingStyle {
    /// User body above the quoted source body.
    Top,
    /// Quoted source body above the user body.
    Bottom,
}

/// All the fields the built-in MIME assembler needs. Each subcommand
/// populates these from its own clap struct.
pub struct BuilderArgs<'a> {
    pub from: Option<&'a str>,
    pub to: &'a [String],
    pub cc: &'a [String],
    pub bcc: &'a [String],
    pub subject: Option<&'a str>,
    pub body: Option<&'a str>,
    pub body_file: Option<&'a Path>,
    pub attach: &'a [PathBuf],
    pub signature: Option<&'a str>,
    pub signature_file: Option<&'a Path>,
}

/// Source-message metadata, populated for reply/forward subcommands.
pub struct SourceArgs<'a> {
    pub raw: &'a [u8],
    pub mode: SourceMode,
    pub posting_style: PostingStyle,
    pub quote_headline: &'a str,
}

/// Whether the source message is being replied to or forwarded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMode {
    Reply,
    Forward,
}

/// Assembles a MIME message from `args` and an optional reply/forward
/// `source`. Returns the raw RFC 5322 bytes.
pub fn build(args: BuilderArgs<'_>, source: Option<SourceArgs<'_>>) -> Result<Vec<u8>> {
    let mut builder = MessageBuilder::new();

    if let Some(from) = args.from {
        builder = builder.from(from);
    }
    if !args.to.is_empty() {
        builder = builder.to(addresses(args.to));
    }
    if !args.cc.is_empty() {
        builder = builder.cc(addresses(args.cc));
    }
    if !args.bcc.is_empty() {
        builder = builder.bcc(addresses(args.bcc));
    }

    let parsed_source = source
        .as_ref()
        .and_then(|s| MessageParser::new().parse(s.raw));

    let mut subject = args.subject.map(str::to_owned);
    let mut source_text = String::new();

    if let (Some(source), Some(parsed)) = (source.as_ref(), parsed_source.as_ref()) {
        let prefix = match source.mode {
            SourceMode::Reply => "Re: ",
            SourceMode::Forward => "Fwd: ",
        };
        let src_subject = parsed.subject().unwrap_or("");
        if subject.is_none() {
            subject = Some(if has_prefix(src_subject, prefix) {
                src_subject.to_string()
            } else {
                format!("{prefix}{src_subject}")
            });
        }

        if source.mode == SourceMode::Reply
            && args.to.is_empty()
            && let Some(addrs) = reply_recipients(parsed)
        {
            builder = builder.to(addrs);
        }

        if let Some(message_id) = parsed.message_id() {
            if source.mode == SourceMode::Reply {
                builder = builder.in_reply_to(vec![message_id.to_string()]);
            }
            let refs = compute_references(parsed, message_id);
            if !refs.is_empty() {
                builder = builder.header("References", Raw::new(refs));
            }
        }

        source_text = parsed
            .body_text(0)
            .map(|c| c.into_owned())
            .unwrap_or_default();
    }

    if let Some(s) = subject {
        builder = builder.subject(s);
    }

    let user_body = read_body(args.body, args.body_file)?;
    let signature = read_signature(args.signature, args.signature_file)?;
    let (style, headline) = match source.as_ref() {
        Some(s) => (s.posting_style, s.quote_headline),
        None => (PostingStyle::Top, ""),
    };
    let body = compose_body(
        &user_body,
        &source_text,
        headline,
        signature.as_deref().unwrap_or(""),
        style,
    );
    builder = builder.text_body(body);

    for path in args.attach {
        let bytes = std::fs::read(path)
            .map_err(|err| anyhow!("read attachment {}: {err}", path.display()))?;
        let file_name = path
            .file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "attachment".to_string());
        let mime = mime_for(path);
        builder = builder.attachment(mime, file_name, bytes);
    }

    builder
        .write_to_vec()
        .map_err(|err| anyhow!("serialize composed message: {err}"))
}

fn addresses(values: &[String]) -> Address<'static> {
    Address::new_list(
        values
            .iter()
            .map(|s| Address::new_address(None::<&str>, s.clone()))
            .collect(),
    )
}

fn read_body(body: Option<&str>, body_file: Option<&Path>) -> Result<String> {
    if let Some(body) = body {
        return Ok(body.to_owned());
    }

    if let Some(path) = body_file {
        return std::fs::read_to_string(path)
            .map_err(|err| anyhow!("read body file {}: {err}", path.display()));
    }

    if !stdin().is_terminal() {
        let mut buf = String::new();
        stdin().read_to_string(&mut buf)?;
        return Ok(buf);
    }

    Ok(String::new())
}

fn read_signature(
    signature: Option<&str>,
    signature_file: Option<&Path>,
) -> Result<Option<String>> {
    if let Some(sig) = signature {
        return Ok(Some(sig.to_owned()));
    }

    if let Some(path) = signature_file {
        let s = std::fs::read_to_string(path)
            .map_err(|err| anyhow!("read signature file {}: {err}", path.display()))?;
        return Ok(Some(s));
    }

    Ok(None)
}

/// Builds the final text body from user input, optional quoted
/// source text, an optional headline, an optional signature, and the
/// requested posting style.
fn compose_body(
    user_body: &str,
    source_text: &str,
    headline: &str,
    signature: &str,
    style: PostingStyle,
) -> String {
    let user_body = user_body.trim_end_matches('\n');
    let source_text = source_text.trim();

    let quote = if source_text.is_empty() {
        String::new()
    } else {
        let mut buf = String::new();
        if !headline.is_empty() {
            buf.push_str(headline.trim_end_matches('\n'));
            buf.push('\n');
        }
        for line in source_text.lines() {
            buf.push('>');
            if !line.starts_with('>') {
                buf.push(' ');
            }
            buf.push_str(line);
            buf.push('\n');
        }
        buf.pop();
        buf
    };

    let mut body = match (style, quote.is_empty()) {
        (_, true) => user_body.to_string(),
        (PostingStyle::Top, false) => {
            if user_body.is_empty() {
                quote
            } else {
                format!("{user_body}\n\n{quote}")
            }
        }
        (PostingStyle::Bottom, false) => {
            if user_body.is_empty() {
                quote
            } else {
                format!("{quote}\n\n{user_body}")
            }
        }
    };

    if !signature.trim().is_empty() {
        let sig = signature.trim_end_matches('\n');
        body.push_str("\n\n-- \n");
        body.push_str(sig);
    }

    body
}

fn has_prefix(subject: &str, prefix: &str) -> bool {
    let s = subject.trim_start();
    // Keep the colon: comparing only the letters would treat a subject
    // like "Ready to ship" as already carrying a "Re:" prefix and drop
    // the real one.
    let p = prefix.trim();
    s.len() >= p.len() && s.get(..p.len()).map(|h| h.eq_ignore_ascii_case(p)) == Some(true)
}

fn reply_recipients(msg: &mail_parser::Message<'_>) -> Option<Address<'static>> {
    use mail_parser::Address as ParserAddress;

    let header = msg
        .header("Reply-To")
        .or_else(|| msg.header("From"))
        .cloned();

    let HeaderValue::Address(addr) = header? else {
        return None;
    };

    let collected: Vec<Address<'static>> = match addr {
        ParserAddress::List(list) => list
            .into_iter()
            .filter_map(|a| {
                let email = a.address?.into_owned();
                let name = a.name.map(|s| s.into_owned());
                Some(Address::new_address(name, email))
            })
            .collect(),
        ParserAddress::Group(groups) => groups
            .into_iter()
            .flat_map(|g| g.addresses.into_iter())
            .filter_map(|a| {
                let email = a.address?.into_owned();
                let name = a.name.map(|s| s.into_owned());
                Some(Address::new_address(name, email))
            })
            .collect(),
    };

    if collected.is_empty() {
        None
    } else {
        Some(Address::new_list(collected))
    }
}

fn compute_references(msg: &mail_parser::Message<'_>, source_message_id: &str) -> String {
    let mut out = String::new();

    if let Some(header) = msg.header("References") {
        if let HeaderValue::TextList(items) = header {
            for r in items {
                push_msg_id(&mut out, r);
            }
        } else if let HeaderValue::Text(s) = header {
            for r in s.split_whitespace() {
                push_msg_id(&mut out, r);
            }
        }
    } else if let Some(header) = msg.header("In-Reply-To") {
        if let HeaderValue::TextList(items) = header {
            for r in items {
                push_msg_id(&mut out, r);
            }
        } else if let HeaderValue::Text(s) = header {
            for r in s.split_whitespace() {
                push_msg_id(&mut out, r);
            }
        }
    }

    push_msg_id(&mut out, source_message_id);
    out
}

fn push_msg_id(out: &mut String, id: &str) {
    let id = id.trim();
    if id.is_empty() {
        return;
    }
    if !out.is_empty() {
        out.push(' ');
    }
    if id.starts_with('<') {
        out.push_str(id);
    } else {
        out.push('<');
        out.push_str(id);
        out.push('>');
    }
}

fn mime_for(path: &Path) -> String {
    mime_guess::from_path(path)
        .first_or_octet_stream()
        .essence_str()
        .to_owned()
}

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

    /// A raw source message used by the reply/forward tests. It already
    /// carries a `References` header so threading can be asserted.
    const SOURCE: &[u8] = b"From: Alice <alice@example.com>\r\n\
To: Bob <bob@example.com>\r\n\
Subject: Project update\r\n\
Message-ID: <orig-2@example.com>\r\n\
References: <orig-0@example.com> <orig-1@example.com>\r\n\
\r\n\
Original body line.\r\n";

    fn parse(raw: &[u8]) -> mail_parser::Message<'_> {
        MessageParser::new()
            .parse(raw)
            .expect("parse built message")
    }

    fn source(mode: SourceMode) -> SourceArgs<'static> {
        SourceArgs {
            raw: SOURCE,
            mode,
            posting_style: PostingStyle::Top,
            quote_headline: "On a day, Alice wrote:",
        }
    }

    fn args<'a>(
        from: &'a str,
        to: &'a [String],
        subject: Option<&'a str>,
        body: &'a str,
    ) -> BuilderArgs<'a> {
        BuilderArgs {
            from: Some(from),
            to,
            cc: &[],
            bcc: &[],
            subject,
            body: Some(body),
            body_file: None,
            attach: &[],
            signature: None,
            signature_file: None,
        }
    }

    #[test]
    fn compose_populates_headers_and_body() {
        let to = vec!["bob@example.com".to_string()];
        let cc = vec!["carol@example.com".to_string()];
        let mut a = args("alice@example.com", &to, Some("Hello"), "Hi Bob");
        a.cc = &cc;

        let raw = build(a, None).unwrap();
        let msg = parse(&raw);
        let text = String::from_utf8(raw.clone()).unwrap();

        assert_eq!(msg.subject(), Some("Hello"));
        assert!(msg.body_text(0).unwrap().contains("Hi Bob"));
        assert!(text.contains("alice@example.com"));
        assert!(text.contains("bob@example.com"));
        assert!(text.contains("carol@example.com"));
        assert!(!text.contains("In-Reply-To"));
    }

    #[test]
    fn reply_sets_subject_recipients_and_threading() {
        let empty: Vec<String> = Vec::new();
        let a = args("bob@example.com", &empty, None, "My reply");

        let raw = build(a, Some(source(SourceMode::Reply))).unwrap();
        let msg = parse(&raw);
        let text = String::from_utf8(raw.clone()).unwrap();

        // subject gains a single "Re:" prefix
        assert_eq!(msg.subject(), Some("Re: Project update"));
        // with no explicit --to, the reply goes to the source's From
        assert!(text.contains("alice@example.com"));
        // threading: In-Reply-To is the source id, References appends it
        assert!(text.contains("In-Reply-To:"));
        assert!(text.contains("orig-2@example.com"));
        // body: user text above the quoted source, with a headline
        let body = msg.body_text(0).unwrap();
        assert!(body.contains("My reply"));
        assert!(body.contains("On a day, Alice wrote:"));
        assert!(body.contains("> Original body line."));
    }

    #[test]
    fn reply_keeps_existing_re_prefix() {
        let raw = b"Subject: Re: Already replied\r\nMessage-ID: <x@e>\r\n\r\nbody";
        let src = SourceArgs {
            raw,
            mode: SourceMode::Reply,
            posting_style: PostingStyle::Top,
            quote_headline: "",
        };
        let empty: Vec<String> = Vec::new();
        let built = build(args("b@e", &empty, None, "r"), Some(src)).unwrap();
        assert_eq!(parse(&built).subject(), Some("Re: Already replied"));
    }

    #[test]
    fn reply_prefixes_subject_that_merely_starts_with_re_letters() {
        // regression: "Ready…" starts with "Re" but is not "Re:"-prefixed
        let raw = b"Subject: Ready to ship\r\nMessage-ID: <x@e>\r\n\r\nbody";
        let src = SourceArgs {
            raw,
            mode: SourceMode::Reply,
            posting_style: PostingStyle::Top,
            quote_headline: "",
        };
        let empty: Vec<String> = Vec::new();
        let built = build(args("b@e", &empty, None, "r"), Some(src)).unwrap();
        assert_eq!(parse(&built).subject(), Some("Re: Ready to ship"));
    }

    #[test]
    fn reply_explicit_to_overrides_source_from() {
        let to = vec!["dave@example.com".to_string()];
        let raw = build(
            args("bob@example.com", &to, None, "r"),
            Some(source(SourceMode::Reply)),
        )
        .unwrap();
        let text = String::from_utf8(raw).unwrap();
        assert!(text.contains("dave@example.com"));
        assert!(!text.contains("alice@example.com"));
    }

    #[test]
    fn forward_prefixes_subject_and_omits_in_reply_to() {
        let to = vec!["dave@example.com".to_string()];
        let raw = build(
            args("bob@example.com", &to, None, "FYI"),
            Some(source(SourceMode::Forward)),
        )
        .unwrap();
        let msg = parse(&raw);
        let text = String::from_utf8(raw.clone()).unwrap();

        assert_eq!(msg.subject(), Some("Fwd: Project update"));
        assert!(!text.contains("In-Reply-To"));
        assert!(msg.body_text(0).unwrap().contains("> Original body line."));
    }

    #[test]
    fn has_prefix_requires_the_colon_case_insensitively() {
        assert!(has_prefix("Re: x", "Re: "));
        assert!(has_prefix("re:x", "Re: "));
        assert!(has_prefix("RE: x", "Re: "));
        assert!(has_prefix("Fwd: x", "Fwd: "));
        assert!(!has_prefix("Ready to ship", "Re: "));
        assert!(!has_prefix("Review", "Re: "));
        assert!(!has_prefix("Forwarding note", "Fwd: "));
    }

    #[test]
    fn compute_references_appends_source_id() {
        // existing References win and the source id is appended
        let msg = parse(SOURCE);
        assert_eq!(
            compute_references(&msg, "orig-2@example.com"),
            "<orig-0@example.com> <orig-1@example.com> <orig-2@example.com>",
        );

        // falls back to In-Reply-To when there is no References header
        let raw = b"In-Reply-To: <a@e>\r\nMessage-ID: <b@e>\r\n\r\nx";
        let msg = parse(raw);
        assert_eq!(compute_references(&msg, "b@e"), "<a@e> <b@e>");

        // neither header: just the source id, wrapped
        let raw = b"Message-ID: <b@e>\r\n\r\nx";
        let msg = parse(raw);
        assert_eq!(compute_references(&msg, "b@e"), "<b@e>");
    }

    #[test]
    fn push_msg_id_wraps_and_separates() {
        let mut out = String::new();
        push_msg_id(&mut out, "a@e");
        push_msg_id(&mut out, "<b@e>");
        push_msg_id(&mut out, "  ");
        push_msg_id(&mut out, "c@e");
        assert_eq!(out, "<a@e> <b@e> <c@e>");
    }

    #[test]
    fn compose_body_honours_posting_style_and_signature() {
        let top = compose_body("mine", "theirs", "wrote:", "", PostingStyle::Top);
        assert_eq!(top, "mine\n\nwrote:\n> theirs");

        let bottom = compose_body("mine", "theirs", "wrote:", "", PostingStyle::Bottom);
        assert_eq!(bottom, "wrote:\n> theirs\n\nmine");

        let signed = compose_body("mine", "", "", "Alice", PostingStyle::Top);
        assert_eq!(signed, "mine\n\n-- \nAlice");
    }
}