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
use std::{
    convert::TryFrom,
    fmt,
    fmt::{Display, Formatter},
    slice::Iter,
    vec::IntoIter,
};

use crate::{body::Body, fragment::Fragment, trailer::Trailer};

/// A collection of user input `CommitMessage` text
///
/// # Examples
///
/// ```
/// use mit_commit::{Bodies, Body, Subject};
///
/// let bodies: Vec<Body> = Vec::default();
/// assert_eq!(None, Bodies::from(bodies).first());
///
/// let bodies: Vec<Body> = vec![
///     Body::from("First"),
///     Body::from("Second"),
///     Body::from("Third"),
/// ];
/// assert_eq!(Some(Body::from("First")), Bodies::from(bodies).first());
/// ```
#[derive(Debug, PartialEq, Clone)]
pub struct Bodies {
    bodies: Vec<Body>,
}

impl Bodies {
    /// Get the first `Body` in this list of `Bodies`
    ///
    /// # Examples
    ///
    /// ```
    /// use mit_commit::{Bodies, Body, Subject};
    ///
    /// let bodies: Vec<Body> = Vec::default();
    /// assert_eq!(None, Bodies::from(bodies).first());
    ///
    /// let bodies: Vec<Body> = vec![
    ///     Body::from("First"),
    ///     Body::from("Second"),
    ///     Body::from("Third"),
    /// ];
    /// assert_eq!(Some(Body::from("First")), Bodies::from(bodies).first());
    /// ```
    #[must_use]
    pub fn first(&self) -> Option<Body> {
        self.bodies.first().cloned()
    }

    /// Iterate over the `Body` in the `Bodies`
    ///
    /// # Examples
    ///
    /// ```
    /// use mit_commit::{Bodies, Body};
    /// let bodies = Bodies::from(vec![
    ///     Body::from("Body 1"),
    ///     Body::from("Body 2"),
    ///     Body::from("Body 3"),
    /// ]);
    /// let mut iterator = bodies.iter();
    ///
    /// assert_eq!(iterator.next(), Some(&Body::from("Body 1")));
    /// assert_eq!(iterator.next(), Some(&Body::from("Body 2")));
    /// assert_eq!(iterator.next(), Some(&Body::from("Body 3")));
    /// assert_eq!(iterator.next(), None);
    /// ```
    #[must_use]
    pub fn iter(&self) -> Iter<'_, Body> {
        self.bodies.iter()
    }
}

impl IntoIterator for Bodies {
    type IntoIter = IntoIter<Body>;
    type Item = Body;

    /// Iterate over the `Body` in the `Bodies`
    ///
    /// # Examples
    ///
    /// ```
    /// use mit_commit::{Bodies, Body};
    /// let bodies = Bodies::from(vec![
    ///     Body::from("Body 1"),
    ///     Body::from("Body 2"),
    ///     Body::from("Body 3"),
    /// ]);
    /// let mut iterator = bodies.into_iter();
    ///
    /// assert_eq!(iterator.next(), Some(Body::from("Body 1")));
    /// assert_eq!(iterator.next(), Some(Body::from("Body 2")));
    /// assert_eq!(iterator.next(), Some(Body::from("Body 3")));
    /// assert_eq!(iterator.next(), None);
    /// ```
    fn into_iter(self) -> Self::IntoIter {
        self.bodies.into_iter()
    }
}

impl Display for Bodies {
    /// Render the bodies as text
    ///
    /// # Examples
    ///
    /// ```
    /// use mit_commit::{Bodies, Body};
    /// let bodies = Bodies::from(vec![
    ///     Body::from("Body 1"),
    ///     Body::from("Body 2"),
    ///     Body::from("Body 3"),
    /// ]);
    ///
    /// assert_eq!(format!("{}", bodies), "Body 1\n\nBody 2\n\nBody 3");
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", String::from(self.clone()))
    }
}

impl From<Vec<Body>> for Bodies {
    /// Render the bodies as text
    ///
    /// # Examples
    ///
    /// ```
    /// use mit_commit::{Bodies, Body};
    /// let bodies = Bodies::from(vec![
    ///     Body::from("Body 1"),
    ///     Body::from("Body 2"),
    ///     Body::from("Body 3"),
    /// ]);
    /// let mut iterator = bodies.into_iter();
    ///
    /// assert_eq!(iterator.next(), Some(Body::from("Body 1")));
    /// assert_eq!(iterator.next(), Some(Body::from("Body 2")));
    /// assert_eq!(iterator.next(), Some(Body::from("Body 3")));
    /// assert_eq!(iterator.next(), None);
    /// ```
    fn from(bodies: Vec<Body>) -> Self {
        Bodies { bodies }
    }
}

impl From<Bodies> for String {
    fn from(bodies: Bodies) -> Self {
        bodies
            .bodies
            .into_iter()
            .map(String::from)
            .collect::<Vec<_>>()
            .join("\n\n")
    }
}

impl From<Vec<Fragment>> for Bodies {
    fn from(bodies: Vec<Fragment>) -> Self {
        let raw_body = bodies
            .iter()
            .filter_map(|values| {
                if let Fragment::Body(body) = values {
                    Some(body.clone())
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        let trailer_count = raw_body
            .clone()
            .into_iter()
            .rev()
            .take_while(|body| body.is_empty() || Trailer::try_from(body.clone()).is_ok())
            .count();
        let mut non_trailer_item_count = raw_body.len() - trailer_count;
        non_trailer_item_count = non_trailer_item_count.saturating_sub(1);

        raw_body
            .into_iter()
            .enumerate()
            .skip(1)
            .take(non_trailer_item_count)
            .map(|(_, body)| body)
            .collect::<Vec<Body>>()
            .into()
    }
}

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

    use super::Bodies;
    use crate::{body::Body, fragment::Fragment};

    #[test]
    fn implements_iterator() {
        let trailers = Bodies::from(vec![
            Body::from("Body 1"),
            Body::from("Body 2"),
            Body::from("Body 3"),
        ]);
        let mut iterator = trailers.iter();

        assert_eq!(iterator.next(), Some(&Body::from("Body 1")));
        assert_eq!(iterator.next(), Some(&Body::from("Body 2")));
        assert_eq!(iterator.next(), Some(&Body::from("Body 3")));
        assert_eq!(iterator.next(), None);
    }

    #[test]
    fn it_can_give_me_it_as_a_string() {
        let bodies = Bodies::from(vec![
            Body::from("Message Body"),
            Body::from("Another Message Body"),
        ]);

        assert_eq!(
            String::from(bodies),
            String::from(indoc!(
                "
                Message Body

                Another Message Body"
            ))
        );
    }

    #[test]
    fn it_can_be_formatted() {
        let bodies = Bodies::from(vec![
            Body::from("Message Body"),
            Body::from("Another Message Body"),
        ]);

        assert_eq!(
            format!("{}", bodies),
            String::from(indoc!(
                "
                Message Body

                Another Message Body"
            ))
        );
    }

    #[test]
    fn get_first() {
        let bodies = Bodies::from(vec![
            Body::from("Message Body"),
            Body::from("Another Message Body"),
        ]);

        assert_eq!(bodies.first(), Some(Body::from("Message Body")));
    }

    #[test]
    fn it_can_parse_itself_from_an_ast() {
        let bodies = Bodies::from(vec![
            Fragment::Body(Body::from("Subject Line")),
            Fragment::Body(Body::default()),
            Fragment::Body(Body::from("Some content in the body of the message")),
            Fragment::Body(Body::default()),
            Fragment::Body(Body::from(indoc!(
                "
                Co-authored-by: Billie Thomposon <billie@example.com>
                Co-authored-by: Someone Else <someone@example.com>
                "
            ))),
        ]);

        assert_eq!(
            bodies,
            Bodies::from(vec![
                Body::default(),
                Body::from("Some content in the body of the message"),
            ])
        );
    }
}