mit_commit/
body.rs

1use std::{
2    borrow::Cow,
3    fmt,
4    fmt::{Display, Formatter},
5};
6
7/// A single contiguous block of [`CommitMessage`] text
8#[derive(Debug, PartialEq, Eq, Clone, Default)]
9pub struct Body<'a> {
10    text: Cow<'a, str>,
11}
12
13impl Body<'_> {
14    /// Append one [`Body`] onto another
15    ///
16    /// This is for concatenating multiple [`Bodies`] together
17    ///
18    /// # Example
19    ///
20    /// ```
21    /// use indoc::indoc;
22    /// use mit_commit::Body;
23    ///
24    /// assert_eq!(
25    ///     Body::from(indoc!(
26    ///         "
27    ///         Example 1
28    ///         Example 2"
29    ///     )),
30    ///     Body::from("Example 1").append(&Body::from("Example 2"))
31    /// )
32    /// ```
33    #[must_use]
34    pub fn append(&self, additional: &Self) -> Self {
35        Self::from(format!("{}\n{}", self.text, additional.text))
36    }
37
38    /// Is this [`Body`] empty
39    ///
40    /// An empty [`Body`] usually indicate a paragraph break in a
41    /// [`CommitMessage`] so it's handy to be able to see them.
42    ///
43    /// # Example
44    ///
45    /// ```
46    /// use indoc::indoc;
47    /// use mit_commit::Body;
48    ///
49    /// assert_eq!(Body::from("").is_empty(), true)
50    /// ```
51    #[must_use]
52    pub fn is_empty(&self) -> bool {
53        self.text.is_empty()
54    }
55}
56
57impl<'a> From<Cow<'a, str>> for Body<'a> {
58    /// Create from a Cow<_, str>
59    ///
60    /// # Example
61    ///
62    /// ```
63    /// use std::borrow::Cow;
64    ///
65    /// use mit_commit::Body;
66    ///
67    /// let expected = "a string";
68    /// let input = Cow::from(expected);
69    /// assert_eq!(Body::from(input).to_string(), expected)
70    /// ```
71    fn from(body: Cow<'a, str>) -> Self {
72        Self { text: body }
73    }
74}
75impl<'a> From<&'a str> for Body<'a> {
76    fn from(body: &'a str) -> Self {
77        Self::from(Cow::Borrowed(body))
78    }
79}
80
81impl From<String> for Body<'_> {
82    fn from(body: String) -> Self {
83        Self::from(Cow::from(body))
84    }
85}
86
87impl From<Body<'_>> for String {
88    fn from(body: Body<'_>) -> Self {
89        body.text.into()
90    }
91}
92
93impl<'a> From<Body<'a>> for Cow<'a, str> {
94    /// Convert to a Cow<_, str>
95    ///
96    /// # Example
97    ///
98    /// ```
99    /// use std::borrow::Cow;
100    ///
101    /// use mit_commit::Body;
102    ///
103    /// let expected = Cow::from("a string");
104    /// let input = Body::from(expected.clone());
105    /// assert_eq!(Cow::from(input), expected)
106    /// ```
107    fn from(body: Body<'a>) -> Self {
108        body.text
109    }
110}
111
112impl Display for Body<'_> {
113    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
114        write!(f, "{}", String::from(self.clone()))
115    }
116}