use semver::Version;
use std::{fs, io::Error as IoError, path::Path};
use thiserror::Error;
use toml_edit::{value, Document, Item, TomlError};
#[derive(Debug, Error)]
pub enum Error {
#[error("an io error occurred")]
IoError(#[from] IoError),
#[error("An error occurred during version parsing")]
SemverParseError(#[from] semver::Error),
#[error("a parser error occurred")]
ParseError(#[from] TomlError),
#[error("the field {field:?} is not of type {ty:?}")]
InvalidFieldType { field: String, ty: String },
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SemVer {
Major,
Minor,
Patch,
}
pub fn get_version(path: impl AsRef<Path>) -> Result<Version, Error> {
let cargo_toml_content = fs::read_to_string(path.as_ref())?;
let doc = cargo_toml_content.parse::<Document>()?;
let item: &Item = &doc["package"]["version"];
if let Some(s) = item.as_str() {
Ok(Version::parse(s)?)
} else {
Err(Error::InvalidFieldType {
field: "version".to_string(),
ty: "string".to_string(),
})
}
}
pub fn set_version(path: impl AsRef<Path>, version: impl AsRef<str>) -> Result<(), Error> {
let cargo_toml_content = fs::read_to_string(path.as_ref())?;
let mut doc = cargo_toml_content.parse::<Document>()?;
doc["package"]["version"] = value(version.as_ref());
fs::write(path.as_ref(), doc.to_string())?;
Ok(())
}
pub fn bump_version(path: impl AsRef<Path>, r#type: SemVer) -> Result<Version, Error> {
let mut version = get_version(path.as_ref())?;
match r#type {
SemVer::Major => version.increment_major(),
SemVer::Minor => version.increment_minor(),
SemVer::Patch => version.increment_patch(),
}
set_version(path, &version.to_string())?;
Ok(version)
}
trait SemVerExt {
fn increment_major(&mut self);
fn increment_minor(&mut self);
fn increment_patch(&mut self);
}
impl SemVerExt for Version {
fn increment_major(&mut self) {
self.major += 1;
}
fn increment_minor(&mut self) {
self.minor += 1;
}
fn increment_patch(&mut self) {
self.patch += 1;
}
}