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
use git_conventional::{Commit, Footer, Type};
use tracing::debug;

use super::{Change, ChangeSource, ChangeType};
use crate::release_notes::Sections;

/// Try to parse each commit message as a [conventional commit](https://www.conventionalcommits.org/).
///
/// # Filtering
///
/// 1. If the commit message doesn't follow the conventional commit format, it is ignored.
/// 2. For non-standard change types, only those included will be considered.
/// 3. For non-standard footers, only those included will be considered.
pub(crate) fn changes_from_commit_messages<'a, Message: AsRef<str>>(
    commit_messages: &'a [Message],
    scopes: Option<&'a Vec<String>>,
    changelog_sections: &'a Sections,
) -> impl Iterator<Item = Change> + 'a {
    if let Some(scopes) = scopes {
        debug!("Only checking commits with scopes: {scopes:?}");
    }
    commit_messages.iter().flat_map(move |message| {
        changes_from_commit_message(message.as_ref(), scopes, changelog_sections).into_iter()
    })
}

fn changes_from_commit_message(
    commit_message: &str,
    scopes: Option<&Vec<String>>,
    changelog_sections: &Sections,
) -> Vec<Change> {
    let Some(commit) = Commit::parse(commit_message.trim()).ok() else {
        return Vec::new();
    };
    let mut has_breaking_footer = false;
    let commit_summary = format_commit_summary(&commit);

    if let Some(commit_scope) = commit.scope() {
        if let Some(scopes) = scopes {
            if !scopes
                .iter()
                .any(|s| s.eq_ignore_ascii_case(commit_scope.as_str()))
            {
                return Vec::new();
            }
        }
    }

    let mut changes = Vec::new();
    for footer in commit.footers() {
        if footer.breaking() {
            has_breaking_footer = true;
        } else if !changelog_sections.contains_footer(footer) {
            continue;
        }
        changes.push(Change {
            change_type: footer.token().into(),
            description: footer.value().into(),
            original_source: ChangeSource::ConventionalCommit(format_commit_footer(
                &commit_summary,
                footer,
            )),
        });
    }

    let commit_description_change_type = if commit.breaking() && !has_breaking_footer {
        ChangeType::Breaking
    } else if commit.type_() == Type::FEAT {
        ChangeType::Feature
    } else if commit.type_() == Type::FIX {
        ChangeType::Fix
    } else {
        return changes; // The commit description isn't a change itself, only (maybe) footers were.
    };

    changes.push(Change {
        change_type: commit_description_change_type,
        description: commit.description().into(),
        original_source: ChangeSource::ConventionalCommit(commit_summary),
    });

    changes
}

fn format_commit_summary(commit: &Commit) -> String {
    let commit_scope = commit
        .scope()
        .map(|s| s.to_string())
        .map(|it| format!("({it})"))
        .unwrap_or_default();
    let bang = if commit.breaking() {
        commit
            .footers()
            .iter()
            .find(|it| it.breaking())
            .map_or_else(|| "!", |_| "")
    } else {
        ""
    };
    format!(
        "{commit_type}{commit_scope}{bang}: {summary}",
        commit_type = commit.type_(),
        summary = commit.description()
    )
}

fn format_commit_footer(commit_summary: &str, footer: &Footer) -> String {
    format!(
        "{commit_summary}\n\tContaining footer {}{} {}",
        footer.token(),
        footer.separator(),
        footer.value()
    )
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use itertools::Itertools;
    use pretty_assertions::assert_eq;

    use super::*;
    use crate::{
        changes::ChangeSource,
        release_notes::{SectionSource, Sections},
    };

    #[test]
    fn commit_types() {
        let commits = &[
            "fix: a bug",
            "fix!: a breaking bug fix",
            "feat!: add a feature",
            "feat: add another feature",
        ];
        let changes =
            changes_from_commit_messages(commits, None, &Sections::default()).collect_vec();
        assert_eq!(
            changes,
            vec![
                Change {
                    change_type: ChangeType::Fix,
                    description: "a bug".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from("fix: a bug")),
                },
                Change {
                    change_type: ChangeType::Breaking,
                    description: "a breaking bug fix".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "fix!: a breaking bug fix"
                    )),
                },
                Change {
                    change_type: ChangeType::Breaking,
                    description: "add a feature".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "feat!: add a feature"
                    )),
                },
                Change {
                    change_type: ChangeType::Feature,
                    description: "add another feature".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "feat: add another feature"
                    )),
                }
            ]
        );
    }

    #[test]
    fn separate_breaking_messages() {
        let commits = [
            "fix: a bug\n\nBREAKING CHANGE: something broke",
            "feat: a features\n\nBREAKING CHANGE: something else broke",
        ];
        let changes =
            changes_from_commit_messages(&commits, None, &Sections::default()).collect_vec();
        assert_eq!(
            changes,
            vec![
                Change {
                    change_type: ChangeType::Breaking,
                    description: "something broke".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from("fix: a bug\n\tContaining footer BREAKING CHANGE: something broke")),
                },
                Change {
                    change_type: ChangeType::Fix,
                    description: "a bug".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from("fix: a bug")),
                },
                Change {
                    change_type: ChangeType::Breaking,
                    description: "something else broke".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from("feat: a features\n\tContaining footer BREAKING CHANGE: something else broke")),
                },
                Change {
                    change_type: ChangeType::Feature,
                    description: "a features".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from("feat: a features")),
                },
            ]
        );
    }

    #[test]
    fn scopes_used_but_none_defined() {
        let commits = [
            "feat(scope)!: Wrong scope breaking change!",
            "fix: No scope",
        ];
        let changes =
            changes_from_commit_messages(&commits, None, &Sections::default()).collect_vec();
        assert_eq!(
            changes,
            vec![
                Change {
                    change_type: ChangeType::Breaking,
                    description: "Wrong scope breaking change!".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "feat(scope)!: Wrong scope breaking change!"
                    )),
                },
                Change {
                    change_type: ChangeType::Fix,
                    description: "No scope".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "fix: No scope"
                    )),
                }
            ]
        );
    }

    #[test]
    fn filter_scopes() {
        let commits = [
            "feat(wrong_scope)!: Wrong scope breaking change!",
            "feat(scope): Scoped feature",
            "fix: No scope",
        ];

        let changes = changes_from_commit_messages(
            &commits,
            Some(&vec![String::from("scope")]),
            &Sections::default(),
        )
        .collect_vec();
        assert_eq!(
            changes,
            vec![
                Change {
                    change_type: ChangeType::Feature,
                    description: "Scoped feature".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "feat(scope): Scoped feature"
                    )),
                },
                Change {
                    change_type: ChangeType::Fix,
                    description: "No scope".into(),
                    original_source: ChangeSource::ConventionalCommit(String::from(
                        "fix: No scope"
                    )),
                },
            ]
        );
    }

    #[test]
    fn custom_footers() {
        let commits = ["chore: ignored type\n\nignored-footer: ignored\ncustom-footer: hello"];
        let changelog_sections = Sections(vec![(
            "custom section".into(),
            vec![ChangeType::Custom(SectionSource::CommitFooter(
                "custom-footer".into(),
            ))],
        )]);
        let changes =
            changes_from_commit_messages(&commits, None, &changelog_sections).collect_vec();
        assert_eq!(
            changes,
            vec![Change {
                change_type: ChangeType::Custom(SectionSource::CommitFooter(
                    "custom-footer".into()
                )),
                description: "hello".into(),
                original_source: ChangeSource::ConventionalCommit(String::from(
                    "chore: ignored type\n\tContaining footer custom-footer: hello"
                )),
            }]
        );
    }
}