1use std::{
2 fmt::{self, Display},
3 str::FromStr,
4};
5
6use anyhow::{anyhow, Result};
7use serde::Serialize;
8
9/// A datastructure representing a semantic version number
10#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Serialize)]
11pub struct SemanticVersion {
12 pub major: usize,
13 pub minor: usize,
14 pub patch: usize,
15}
16
17pub fn semver(major: usize, minor: usize, patch: usize) -> SemanticVersion {
18 SemanticVersion {
19 major,
20 minor,
21 patch,
22 }
23}
24
25impl SemanticVersion {
26 pub fn new(major: usize, minor: usize, patch: usize) -> Self {
27 Self {
28 major,
29 minor,
30 patch,
31 }
32 }
33}
34
35impl FromStr for SemanticVersion {
36 type Err = anyhow::Error;
37 fn from_str(s: &str) -> Result<Self> {
38 let mut components = s.trim().split('.');
39 let major = components
40 .next()
41 .ok_or_else(|| anyhow!("missing major version number"))?
42 .parse()?;
43 let minor = components
44 .next()
45 .ok_or_else(|| anyhow!("missing minor version number"))?
46 .parse()?;
47 let patch = components
48 .next()
49 .ok_or_else(|| anyhow!("missing patch version number"))?
50 .parse()?;
51 Ok(Self {
52 major,
53 minor,
54 patch,
55 })
56 }
57}
58
59impl Display for SemanticVersion {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
62 }
63}