cargo_version/
bump_level.rs

1use std::fmt;
2use std::str::FromStr;
3
4extern crate semver;
5
6use self::semver::Version;
7
8#[derive(PartialEq, Debug)]
9pub enum BumpLevel {
10    Major,
11    Minor,
12    Patch,
13    Specific(Version),
14}
15
16#[derive(PartialEq, Debug)]
17pub enum BumpLevelError {
18    InvalidInput(String)
19}
20
21impl FromStr for BumpLevel {
22    type Err = BumpLevelError;
23
24    fn from_str(s: &str) -> Result<Self, Self::Err> {
25        match s {
26            "major" => return Ok(BumpLevel::Major),
27            "minor" => return Ok(BumpLevel::Minor),
28            "patch" => return Ok(BumpLevel::Patch),
29            _ => {}
30        }
31
32        match Version::parse(s) {
33            Ok(version) => return Ok(BumpLevel::Specific(version)),
34            _ => {}
35        }
36
37        return Err(BumpLevelError::InvalidInput(String::from(s)))
38    }
39}
40
41impl fmt::Display for BumpLevel {
42    fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result {
43        match *self {
44            BumpLevel::Major => write!(f, "Major bump"),
45            BumpLevel::Minor => write!(f, "Minor bump"),
46            BumpLevel::Patch => write!(f, "Patch bump"),
47            BumpLevel::Specific(ref version) => write!(f, "Specific bump to {}", version),
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn it_parses_generic_bumps() {
58        assert_eq!(BumpLevel::from_str("major"), Ok(BumpLevel::Major));
59        assert_eq!(BumpLevel::from_str("minor"), Ok(BumpLevel::Minor));
60        assert_eq!(BumpLevel::from_str("patch"), Ok(BumpLevel::Patch));
61    }
62
63    #[test]
64    fn it_parses_specific_bumps() {
65        assert_eq!(BumpLevel::from_str("0.0.0"), Ok(BumpLevel::Specific(Version::from_str("0.0.0").unwrap())));
66        assert_eq!(BumpLevel::from_str("1.0.0-alpha.1"), Ok(BumpLevel::Specific(Version::from_str("1.0.0-alpha.1").unwrap())));
67        assert_eq!(BumpLevel::from_str("1.0.0"), Ok(BumpLevel::Specific(Version::from_str("1.0.0").unwrap())));
68        assert_eq!(BumpLevel::from_str("1.2.3"), Ok(BumpLevel::Specific(Version::from_str("1.2.3").unwrap())));
69    }
70
71    #[test]
72    fn it_errors_on_garbage() {
73        assert_eq!(BumpLevel::from_str(" minor"), Err(BumpLevelError::InvalidInput(String::from(" minor"))));
74        assert_eq!(BumpLevel::from_str(""), Err(BumpLevelError::InvalidInput(String::from(""))));
75        assert_eq!(BumpLevel::from_str("1.0.a"), Err(BumpLevelError::InvalidInput(String::from("1.0.a"))));
76        assert_eq!(BumpLevel::from_str("test"), Err(BumpLevelError::InvalidInput(String::from("test"))));
77    }
78}