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
use std::borrow::Cow;

const SCISSORS_MARKER: &str = "------------------------ >8 ------------------------";

/// The [`Scissors`] from a [`CommitMessage`]
#[derive(Debug, PartialEq, Clone)]
pub struct Scissors<'a> {
    scissors: Cow<'a, str>,
}

impl<'a> Scissors<'a> {
    pub(crate) fn parse_sections(message: &str) -> (Cow<'a, str>, Option<Scissors<'a>>) {
        message
            .lines()
            .position(|line| line.ends_with(SCISSORS_MARKER))
            .map_or_else(
                || (message.to_string().into(), None),
                |scissors_position| {
                    let lines = message.lines().collect::<Vec<_>>();
                    let body = lines
                        .clone()
                        .into_iter()
                        .take(scissors_position)
                        .collect::<Vec<_>>()
                        .join("\n");
                    let scissors_string = &lines
                        .into_iter()
                        .skip(scissors_position)
                        .collect::<Vec<_>>()
                        .join("\n");

                    let scissors = if message.ends_with('\n') {
                        Self::from(format!("{}\n", scissors_string))
                    } else {
                        Self::from(scissors_string.clone())
                    };

                    (body.into(), Some(scissors))
                },
            )
    }
}

impl<'a> From<Cow<'a, str>> for Scissors<'a> {
    fn from(scissors: Cow<'a, str>) -> Self {
        Self { scissors }
    }
}

impl<'a> From<&'a str> for Scissors<'a> {
    fn from(scissors: &'a str) -> Self {
        Self {
            scissors: scissors.into(),
        }
    }
}

impl<'a> From<String> for Scissors<'a> {
    fn from(scissors: String) -> Self {
        Self {
            scissors: scissors.into(),
        }
    }
}

impl<'a> From<Scissors<'a>> for String {
    fn from(scissors: Scissors<'a>) -> Self {
        scissors.scissors.into()
    }
}