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
use conventional_commit_parser::commit::{CommitType, ConventionalCommit};
use regex::Regex;
use semver::Version;

use crate::{NextVersion, VersionUpdater};

#[derive(Debug, PartialEq, Eq)]
pub enum VersionIncrement {
    Major,
    Minor,
    Patch,
    Prerelease,
}

fn is_there_a_custom_match(regex_option: Option<&Regex>, commits: &[ConventionalCommit]) -> bool {
    if let Some(regex) = regex_option {
        commits
            .iter()
            .any(|commit| custom_commit_matches_regex(regex, commit))
    } else {
        false
    }
}

fn custom_commit_matches_regex(regex: &Regex, commit: &ConventionalCommit) -> bool {
    if let CommitType::Custom(custom_type) = &commit.commit_type {
        regex.is_match(custom_type)
    } else {
        false
    }
}

impl VersionIncrement {
    /// Analyze commits and determine which part of version to increment based on
    /// [conventional commits](https://www.conventionalcommits.org/) and
    /// [Semantic versioning](https://semver.org/).
    /// - If no commits are present, [`Option::None`] is returned, because the version should not be incremented.
    /// - If some commits are present and [`semver::Prerelease`] is not empty, the version increment is
    ///   [`VersionIncrement::Prerelease`].
    /// - If some commits are present, but none of them match conventional commits specification,
    ///   the version increment is [`VersionIncrement::Patch`].
    /// - If some commits match conventional commits, then the next version is calculated by using
    ///   [these](https://www.conventionalcommits.org/en/v1.0.0/#how-does-this-relate-to-semverare) rules.
    pub fn from_commits<I>(current_version: &Version, commits: I) -> Option<Self>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        let updater = VersionUpdater::default();
        Self::from_commits_with_updater(&updater, current_version, commits)
    }

    pub(crate) fn from_commits_with_updater<I>(
        updater: &VersionUpdater,
        current_version: &Version,
        commits: I,
    ) -> Option<Self>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        let mut commits = commits.into_iter().peekable();
        let are_commits_present = commits.peek().is_some();
        if are_commits_present {
            if !current_version.pre.is_empty() {
                return Some(VersionIncrement::Prerelease);
            }
            // Parse commits and keep only the ones that follow conventional commits specification.
            let commits: Vec<ConventionalCommit> = commits
                .filter_map(|c| conventional_commit_parser::parse(c.as_ref()).ok())
                .collect();

            Some(Self::from_conventional_commits(
                current_version,
                &commits,
                updater,
            ))
        } else {
            None
        }
    }

    /// Increments the version to take into account breaking changes.
    /// ```rust
    /// use next_version::VersionIncrement;
    /// use semver::Version;
    ///
    /// let increment = VersionIncrement::breaking(&Version::new(0, 3, 3));
    /// assert_eq!(increment, VersionIncrement::Minor);
    ///
    /// let increment = VersionIncrement::breaking(&Version::new(1, 3, 3));
    /// assert_eq!(increment, VersionIncrement::Major);
    ///
    /// let increment = VersionIncrement::breaking(&Version::parse("1.3.3-alpha.1").unwrap());
    /// assert_eq!(increment, VersionIncrement::Prerelease);
    /// ```
    pub fn breaking(current_version: &Version) -> Self {
        if !current_version.pre.is_empty() {
            Self::Prerelease
        } else if current_version.major == 0 && current_version.minor == 0 {
            Self::Patch
        } else if current_version.major == 0 {
            Self::Minor
        } else {
            Self::Major
        }
    }

    /// If no conventional commits are present, the version is incremented as a Patch
    fn from_conventional_commits(
        current: &Version,
        commits: &[ConventionalCommit],
        updater: &VersionUpdater,
    ) -> Self {
        let is_there_a_feature = || {
            commits
                .iter()
                .any(|commit| commit.commit_type == CommitType::Feature)
        };

        let is_there_a_breaking_change = commits.iter().any(|commit| commit.is_breaking_change);

        let is_major_bump = || {
            (is_there_a_breaking_change
                || is_there_a_custom_match(updater.custom_major_increment_regex.as_ref(), commits))
                && (current.major != 0 || updater.breaking_always_increment_major)
        };

        let is_minor_bump = || {
            let is_feat_bump = || {
                is_there_a_feature()
                    && (current.major != 0 || updater.features_always_increment_minor)
            };
            let is_breaking_bump =
                || current.major == 0 && current.minor != 0 && is_there_a_breaking_change;
            is_feat_bump()
                || is_breaking_bump()
                || is_there_a_custom_match(updater.custom_minor_increment_regex.as_ref(), commits)
        };

        if is_major_bump() {
            Self::Major
        } else if is_minor_bump() {
            Self::Minor
        } else {
            Self::Patch
        }
    }
}

impl VersionIncrement {
    pub fn bump(&self, version: &Version) -> Version {
        match self {
            Self::Major => version.increment_major(),
            Self::Minor => version.increment_minor(),
            Self::Patch => version.increment_patch(),
            Self::Prerelease => version.increment_prerelease(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use conventional_commit_parser::commit::{CommitType, ConventionalCommit};
    use regex::Regex;
    #[test]
    fn returns_true_for_matching_custom_type() {
        let regex = Regex::new(r"custom").unwrap();
        let commits = vec![ConventionalCommit {
            commit_type: CommitType::Custom("custom".to_string()),
            is_breaking_change: false,
            summary: "A custom commit".to_string(),
            body: None,
            scope: None,
            footers: vec![],
        }];

        assert!(is_there_a_custom_match(Some(&regex), &commits));
    }

    #[test]
    fn returns_false_for_non_custom_commit_types() {
        let regex = Regex::new(r"custom").unwrap();
        let commits = vec![ConventionalCommit {
            commit_type: CommitType::Feature,
            is_breaking_change: false,
            summary: "A feature commit".to_string(),
            body: None,
            scope: None,
            footers: vec![],
        }];

        assert!(!is_there_a_custom_match(Some(&regex), &commits));
    }

    #[test]
    fn returns_false_for_empty_commits_list() {
        let regex = Regex::new(r"custom").unwrap();
        let commits: Vec<ConventionalCommit> = Vec::new();

        assert!(!is_there_a_custom_match(Some(&regex), &commits));
    }

    #[test]
    fn handles_commits_with_empty_custom_types() {
        let regex = Regex::new(r"custom").unwrap();
        let commits = vec![ConventionalCommit {
            commit_type: CommitType::Custom("".to_string()),
            is_breaking_change: false,
            summary: "A custom commit".to_string(),
            body: None,
            scope: None,
            footers: vec![],
        }];

        assert!(!is_there_a_custom_match(Some(&regex), &commits));
    }
}