summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: bf60e85c7ba55451f02a2f5c438e7ab714549ef5 (plain)
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
//   amt - accumulate mail trailers
//   Copyright (C) 2018 Matthias Beyer <mail@beyermatthias.de>
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 2 as
//   published by the Free Software Foundation.
//

extern crate walkdir;
extern crate mailparse;
extern crate clap;
extern crate regex;
extern crate itertools;

use std::path::PathBuf;
use std::process::exit as exit;

use clap::{Arg, App};
use walkdir::WalkDir;
use regex::RegexBuilder;
use itertools::Itertools;

fn main() {
    let matches = App::new("amt")
        .version("0.1")
        .author("Matthias Beyer <mail@beyermatthias.de>")
        .about("Accumulate git trailers from email threads")
        .arg(Arg::with_name("maildirpath")
             .index(1)
             .value_name("MAILDIR")
             .required(true)
             .multiple(false)
             .takes_value(true)
             .help("The path of the maildir to fetch mail from"))
        .arg(Arg::with_name("msgid")
             .index(2)
             .value_name("MESSAGE-ID")
             .required(true)
             .multiple(false)
             .takes_value(true)
             .help("A message ID of any mail in the thread to fetch the trailers from"))
        .arg(Arg::with_name("subject-replace-regex")
             .long("subj-replace")
             .short("S")
             .value_name("PATTERN")
             .required(false)
             .multiple(false)
             .takes_value(true)
             .default_value("^\\[PATCH.*\\] ")
             .help("A regex which is used to replace '[PATCH] '-prefixes in a message subjects. The used regex engine suports unicode and runs in case-insensitive mode."))

        .get_matches();

    let maildir = matches
        .value_of("maildirpath")
        .map(String::from)
        .map(PathBuf::from)
        .unwrap(); // unwrap safe by clap

    let msgid = matches
        .value_of("msgid")
        .unwrap(); // unwrap safe by clap

    let subject_replace_regex = RegexBuilder::new(matches.value_of("subject-replace-regex").unwrap()) // safe by clap
        .multi_line(false)
        .dot_matches_new_line(false)
        .ignore_whitespace(false)
        .unicode(true)
        .case_insensitive(true)
        .build()
        .unwrap_or_else(|e| {
            eprintln!("Error building Regex: {:?}", e);
            exit(1)
        });

    WalkDir::new(maildir)
        .max_depth(usize::max_value())
        .follow_links(false)
        .max_open(50)
        .into_iter()
        .map(|entry| entry.unwrap_or_else(|e| {
            eprintln!("IO Error: {:?}", e);
            exit(1)
        }))
        .filter_map(|entry| if entry.file_type().is_file() {
            Some(entry.into_path())
        } else {
            None
        })
        .filter_map(|path| {
            let plain = ::std::fs::read_to_string(path.clone()).unwrap_or_else(|e| {
                eprintln!("Failed to read file: {} - {:?}", path.display(), e);
                exit(1)
            });

            let (related, stripped_subject) = {
                let headers = ::mailparse::parse_mail(plain.as_bytes())
                    .unwrap_or_else(|e| {
                        eprintln!("Failed to parse mail: {} - {:?}", path.display(), e);
                        exit(1)
                    })
                    .headers;

                let related = headers
                    .iter()
                    .any(|hdr| {
                        let key = hdr
                            .get_key()
                            .unwrap_or_else(|e| {
                                eprintln!("Failed to get mail header key: {} - {:?}", path.display(), e);
                                exit(1)
                            });

                        if key == "Message-ID"
                            || key == "Message-Id"
                            || key == "References"
                        {
                            hdr.get_value()
                                .unwrap_or_else(|e| {
                                    eprintln!("Failed to get mail header value: {} - {:?}", path.display(), e);
                                    exit(1)
                                })
                                .contains(msgid)
                        } else {
                            false
                        }
                    });

                if related {
                    let subj = headers
                        .iter()
                        .filter_map(|hdr| if hdr
                            .get_key()
                            .unwrap_or_else(|e| {
                                eprintln!("Failed to get mail header key: {} - {:?}", path.display(), e);
                                exit(1)
                            }) == "Subject" {
                                Some(hdr.get_value().unwrap_or_else(|e| {
                                    eprintln!("Failed to get mail header value: {} - {:?}", path.display(), e);
                                    exit(1)
                                }))
                            } else {
                                None
                            }
                        )
                        .next();
                    (true, subj)
                } else {
                    (false, None)
                }
            };

            if related {
                Some((plain, stripped_subject.unwrap()))
            } else {
                None
            }
        })
        .map(|(plain, subj)| {
            (plain, subject_replace_regex.replace(&subj, "").to_string())
        })
        .group_by(|tpl| tpl.1.clone())
        .into_iter()
        .map(|(key, group)| {
            (key, Iterator::flatten(group.map(|tpl| get_trailers(&tpl.0))).collect::<Vec<String>>())
        })
        .for_each(|(subject, trailers)| {
            trailers.iter().for_each(|trailer| {
                println!("{} - {}", subject, trailer);
            })
        })
}

fn get_trailers(message: &String) -> Vec<String> {
    use std::process::Command;
    use std::process::Stdio;
    use std::io::Write;

    let mut sub = Command::new("git")
        .args(&["interpret-trailers", "--only-trailers"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("Failed to start git-interpret-trailers as subprocess");

    {
        sub.stdin
            .as_mut()
            .expect("Failed to open stdin of child process")
            .write_all(message.as_bytes())
            .expect("Failed to write message to git-interpret-trailers");
    }

    let output = sub
        .wait_with_output()
        .expect("Failed to read from child process");

    String::from_utf8(output.stdout)
        .expect("Failed converting child process output to String object. Not UTF8?")
        .lines()
        .map(String::from)
        .collect()
}