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
//! A semantic tag
//!
//! # Example
//!
//!
//! # Panics
//!
//!

use crate::{ConventionalCommits, Error, Level, Semantic};
use git2::{Oid, Repository};

/// Describes a tag
#[derive(Debug, PartialEq, PartialOrd, Eq, Clone, Ord)]
pub struct VersionTag {
    name: Semantic,
    id: Oid,
    conventional: Option<ConventionalCommits>,
    bump_level: Option<Level>,
}

impl VersionTag {
    fn new(name: Semantic, id: Oid) -> Self {
        VersionTag {
            name,
            id,
            conventional: None,
            bump_level: None,
        }
    }

    /// The  name field
    pub fn name(&self) -> Semantic {
        self.name.clone()
    }

    /// The id field
    pub fn id(&self) -> Oid {
        self.id
    }

    /// The count of feature commits in the conventional commits field
    /// If the conventional commits field has not been set returns 0
    pub fn feat_commits(&self) -> u32 {
        if self.conventional.is_some() {
            self.conventional.as_ref().unwrap().feat_commits()
        } else {
            0
        }
    }

    /// The count of fix commits in the conventional commits field
    /// If the conventional commits field has not been set returns 0
    pub fn fix_commits(&self) -> u32 {
        if self.conventional.is_some() {
            self.conventional.as_ref().unwrap().fix_commits()
        } else {
            0
        }
    }

    /// The count of docs commits in the conventional commits field
    /// If the conventional commits field has not been set returns 0
    pub fn docs_commits(&self) -> u32 {
        if self.conventional.is_some() {
            self.conventional.as_ref().unwrap().docs_commits()
        } else {
            0
        }
    }

    /// The count of chore commits in the conventional commits field
    /// If the conventional commits field has not been set returns 0
    pub fn chore_commits(&self) -> u32 {
        if self.conventional.is_some() {
            self.conventional.as_ref().unwrap().chore_commits()
        } else {
            0
        }
    }

    /// The count of refactor commits in the conventional commits field
    /// If the conventional commits field has not been set returns 0
    pub fn refactor_commits(&self) -> u32 {
        if self.conventional.is_some() {
            self.conventional.as_ref().unwrap().refactor_commits()
        } else {
            0
        }
    }

    /// The breaking flag in the conventional commits field
    /// If the conventional commits field has not been set returns false
    pub fn breaking(&self) -> bool {
        if self.conventional.is_some() {
            self.conventional.as_ref().unwrap().breaking()
        } else {
            false
        }
    }

    /// The latest semantic version tag (vx.y.z)
    ///
    pub fn latest(version_prefix: &str) -> Result<Self, Error> {
        let repo = Repository::open(".")?;
        let mut versions = vec![];
        repo.tag_foreach(|id, name| {
            if let Ok(name) = String::from_utf8(name.to_owned()) {
                if let Some(name) = name.strip_prefix("refs/tags/") {
                    if name.starts_with(version_prefix) {
                        if let Ok(semantic_version) = Semantic::parse(name, version_prefix) {
                            versions.push(VersionTag::new(semantic_version, id));
                        }
                    }
                }
            }
            true
        })?;

        versions.sort();
        let last_version = versions.last().cloned();

        match last_version {
            Some(v) => Ok(v),
            None => Err(Error::NoVersionTag),
        }
    }

    /// Construct conventional commits that forces Major update
    ///
    pub fn force_major(&mut self) -> Self {
        let mut conventional_commits = ConventionalCommits::new();
        conventional_commits.set_breaking(true);
        self.conventional = Some(conventional_commits);
        self.clone()
    }

    /// Construct conventional commits that forces Minor update
    ///
    pub fn force_minor(&mut self) -> Self {
        let mut conventional_commits = ConventionalCommits::new();
        conventional_commits.set_one_feat();
        self.conventional = Some(conventional_commits);
        self.clone()
    }

    /// Construct conventional commits that forces Patch update
    ///
    pub fn force_patch(&mut self) -> Self {
        let mut conventional_commits = ConventionalCommits::new();
        conventional_commits.set_one_fix();
        self.conventional = Some(conventional_commits);
        self.clone()
    }

    /// Promote the first production version (1.0.0)
    ///
    pub fn promote_first(&mut self) -> Result<Self, Error> {
        self.name.first_production()?;
        Ok(self.clone())
    }

    /// The number of conventional commits created since the tag was created
    ///
    pub fn commits(mut self) -> Result<Self, Error> {
        let repo = git2::Repository::open(".")?;
        let mut revwalk = repo.revwalk()?;
        revwalk.set_sorting(git2::Sort::NONE)?;
        revwalk.push_head()?;
        let glob = format!("refs/tags/{}", self.name);
        revwalk.hide_ref(&glob)?;

        macro_rules! filter_try {
            ($e:expr) => {
                match $e {
                    Ok(t) => t,
                    Err(e) => return Some(Err(e)),
                }
            };
        }

        #[allow(clippy::unnecessary_filter_map)]
        let revwalk = revwalk.filter_map(|id| {
            let id = filter_try!(id);
            let commit = repo.find_commit(id);
            let commit = filter_try!(commit);
            Some(Ok(commit))
        });

        let mut conventional_commits = ConventionalCommits::new();

        for commit in revwalk {
            let commit = commit?;
            conventional_commits.push(&commit);
        }

        self.conventional = Some(conventional_commits);

        Ok(self)
    }

    #[cfg(feature = "version")]
    pub fn next_version(&mut self) -> Semantic {
        // clone the current version to mutate for the next version
        let mut next_version = self.name.clone();

        // check the conventional commits. No conventional commits; no change.
        if let Some(conventional) = self.conventional.clone() {
            // Breaking change found in commits
            if conventional.breaking() {
                next_version.breaking_increment();
                if self.name.major() == 0 {
                    self.bump_level = Some(Level::Minor);
                } else {
                    self.bump_level = Some(Level::Major);
                }
            } else if conventional.feat_commits() > 0 {
                next_version.increment_minor();
                self.bump_level = Some(Level::Minor);
            } else if conventional.total_commits() > 0 {
                next_version.increment_patch();
                self.bump_level = Some(Level::Patch);
            } else {
                self.bump_level = Some(Level::None);
            }
        }

        next_version
    }

    #[cfg(feature = "level")]
    pub fn next_level(&mut self) -> Result<Level, Error> {
        // check the conventional commits. No conventional commits; no change.
        if let Some(conventional) = self.conventional.clone() {
            // Breaking change found in commits
            // println!("Conventional: {:#?}", conventional);
            if conventional.breaking() {
                if self.name.major() == 0 {
                    Ok(Level::Minor)
                } else {
                    Ok(Level::Major)
                }
            } else if conventional.feat_commits() > 0 {
                Ok(Level::Minor)
            } else if conventional.total_commits() > 0 {
                Ok(Level::Patch)
            } else {
                // Ok(Level::None)
                Err(Error::NoLevelChange)
            }
        } else {
            Err(Error::NoConventionalCommits)
        }
    }

    pub fn bump_level(&self) -> Option<Level> {
        self.bump_level.clone()
    }
}