#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Semver {
pub prefix: bool,
pub major: u64,
pub minor: u64,
pub patch: u64,
pub pre: Option<String>,
pub build: Option<String>,
}
pub fn parse_semver(text: &str) -> Option<Semver> {
let text = text.trim();
let (prefix, rest) = match text.strip_prefix('v') {
Some(rest) => (true, rest),
None => (false, text),
};
let (rest, build) = match rest.split_once('+') {
Some((core, build)) => (core, Some(build)),
None => (rest, None),
};
let (core, pre) = match rest.split_once('-') {
Some((core, pre)) => (core, Some(pre)),
None => (rest, None),
};
let ident_ok = |s: &str| {
!s.is_empty()
&& s.split('.')
.all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
};
if pre.is_some_and(|p| !ident_ok(p)) || build.is_some_and(|b| !ident_ok(b)) {
return None;
}
let mut nums = core.split('.').map(|part| {
let digits = !part.is_empty() && part.chars().all(|c| c.is_ascii_digit());
if !digits || (part.len() > 1 && part.starts_with('0')) {
None
} else {
part.parse::<u64>().ok()
}
});
let (major, minor, patch) = (nums.next()??, nums.next()??, nums.next()??);
if nums.next().is_some() {
return None;
}
Some(Semver {
prefix,
major,
minor,
patch,
pre: pre.map(str::to_string),
build: build.map(str::to_string),
})
}
impl Semver {
fn plain(&self, major: u64, minor: u64, patch: u64) -> Semver {
Semver {
prefix: self.prefix,
major,
minor,
patch,
pre: None,
build: None,
}
}
pub fn bump_major(&self) -> Semver {
self.plain(self.major.saturating_add(1), 0, 0)
}
pub fn bump_minor(&self) -> Semver {
self.plain(self.major, self.minor.saturating_add(1), 0)
}
pub fn bump_patch(&self) -> Semver {
self.plain(self.major, self.minor, self.patch.saturating_add(1))
}
pub fn to_string_with_prefix(&self) -> String {
let mut text = format!(
"{}{}.{}.{}",
if self.prefix { "v" } else { "" },
self.major,
self.minor,
self.patch
);
if let Some(pre) = &self.pre {
text.push('-');
text.push_str(pre);
}
if let Some(build) = &self.build {
text.push('+');
text.push_str(build);
}
text
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Commit {
pub kind: String,
pub scope: Option<String>,
pub breaking: bool,
pub desc: String,
}
const KINDS: [&str; 10] = [
"feat", "fix", "docs", "chore", "refactor", "perf", "test", "build", "ci", "revert",
];
pub fn classify_commit(subject: &str, body: &str) -> Commit {
let subject = subject.trim();
let footer_breaking = body.lines().any(|line| {
let line = line.trim_start();
line.starts_with("BREAKING CHANGE:") || line.starts_with("BREAKING-CHANGE:")
});
let conventional = subject.split_once(':').and_then(|(head, desc)| {
let (head, bang) = match head.strip_suffix('!') {
Some(h) => (h, true),
None => (head, false),
};
let (kind, scope) = match head.split_once('(') {
Some((kind, rest)) => {
let scope = rest.strip_suffix(')')?;
(
kind,
(!scope.trim().is_empty()).then(|| scope.trim().to_string()),
)
}
None => (head, None),
};
let kind = kind.to_ascii_lowercase();
KINDS
.contains(&kind.as_str())
.then(|| (kind, scope, bang, desc.trim().to_string()))
});
match conventional {
Some((kind, scope, bang, desc)) => Commit {
kind,
scope,
breaking: bang || footer_breaking,
desc,
},
None => Commit {
kind: "other".into(),
scope: None,
breaking: footer_breaking,
desc: subject.to_string(),
},
}
}
pub fn suggest_bump(commits: &[Commit], current: &Semver) -> Semver {
if commits.iter().any(|c| c.breaking) {
if current.major == 0 {
current.bump_minor()
} else {
current.bump_major()
}
} else if commits.iter().any(|c| c.kind == "feat") {
current.bump_minor()
} else {
current.bump_patch()
}
}
pub fn suggest_next(commits: &[Commit], current: Option<&Semver>) -> Semver {
match current {
Some(current) => suggest_bump(commits, current),
None => Semver {
prefix: true,
major: 0,
minor: 1,
patch: 0,
pre: None,
build: None,
},
}
}
pub fn render_changelog(commits: &[Commit]) -> String {
let line = |c: &Commit| match &c.scope {
Some(scope) => format!("- {scope}: {}", c.desc),
None => format!("- {}", c.desc),
};
let groups: [(&str, Vec<&Commit>); 4] = [
(
"Breaking changes",
commits.iter().filter(|c| c.breaking).collect(),
),
(
"Features",
commits
.iter()
.filter(|c| !c.breaking && c.kind == "feat")
.collect(),
),
(
"Fixes",
commits
.iter()
.filter(|c| !c.breaking && c.kind == "fix")
.collect(),
),
(
"Other",
commits
.iter()
.filter(|c| !c.breaking && c.kind != "feat" && c.kind != "fix")
.collect(),
),
];
let sections: Vec<String> = groups
.iter()
.filter(|(_, items)| !items.is_empty())
.map(|(title, items)| {
let body: Vec<String> = items.iter().map(|c| line(c)).collect();
format!("### {title}\n{}", body.join("\n"))
})
.collect();
sections.join("\n\n")
}
pub fn parse_ls_remote_oids(text: &str) -> Vec<(String, String)> {
let mut found: Vec<(String, String)> = Vec::new();
for line in text.lines() {
let Some((oid, name)) = line.trim_end().split_once(['\t', ' ']) else {
continue;
};
let Some(name) = name.trim().strip_prefix("refs/tags/") else {
continue;
};
if name.is_empty() || name.ends_with("^{}") || oid.is_empty() {
continue;
}
if !found.iter().any(|(n, _)| n == name) {
found.push((name.to_string(), oid.to_string()));
}
}
found
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ls_remote_oids_parse() {
let text = "aaa\trefs/tags/v1\r\nbbb\trefs/tags/v2\nccc\trefs/tags/v2^{}\nddd\trefs/heads/main\nbad\n";
assert_eq!(
parse_ls_remote_oids(text),
[
("v1".to_string(), "aaa".to_string()),
("v2".to_string(), "bbb".to_string())
]
);
assert!(parse_ls_remote_oids("").is_empty());
}
fn v(text: &str) -> Semver {
parse_semver(text).unwrap()
}
fn commit(subject: &str) -> Commit {
classify_commit(subject, "")
}
#[test]
fn parse_table() {
let ok = [
("1.2.3", false, (1, 2, 3), None, None),
("v1.2.3", true, (1, 2, 3), None, None),
("v1.2.3-rc.1+b5", true, (1, 2, 3), Some("rc.1"), Some("b5")),
("0.0.0+build", false, (0, 0, 0), None, Some("build")),
(" v10.20.30 ", true, (10, 20, 30), None, None),
];
for (text, prefix, (a, b, c), pre, build) in ok {
let s = v(text);
assert_eq!(
(s.prefix, s.major, s.minor, s.patch),
(prefix, a, b, c),
"{text}"
);
assert_eq!(s.pre.as_deref(), pre, "{text}");
assert_eq!(s.build.as_deref(), build, "{text}");
}
for bad in [
"",
"v",
"1.2",
"1.2.3.4",
"a.b.c",
"01.2.3",
"1.2.x",
"v1.2.3-",
"1.2.3+",
"release",
"1..3",
"-1.2.3",
"1.2.3-a..b",
"99999999999999999999.0.0",
] {
assert!(parse_semver(bad).is_none(), "{bad:?} should be rejected");
}
}
#[test]
fn bump_and_print() {
let s = v("v1.2.3-rc.1+b5");
assert_eq!(s.to_string_with_prefix(), "v1.2.3-rc.1+b5");
assert_eq!(s.bump_patch().to_string_with_prefix(), "v1.2.4");
assert_eq!(s.bump_minor().to_string_with_prefix(), "v1.3.0");
assert_eq!(s.bump_major().to_string_with_prefix(), "v2.0.0");
assert_eq!(v("1.9.9").bump_minor().to_string_with_prefix(), "1.10.0");
}
#[test]
fn classify_table() {
let c = commit("feat(ui)!: new menu");
assert_eq!(
(c.kind.as_str(), c.scope.as_deref(), c.breaking),
("feat", Some("ui"), true)
);
assert_eq!(c.desc, "new menu");
let c = commit("fix: crash on empty repo");
assert_eq!(
(c.kind.as_str(), c.scope.clone(), c.breaking),
("fix", None, false)
);
let c = classify_commit("refactor: split", "text\n\nBREAKING CHANGE: api gone");
assert!(c.breaking && c.kind == "refactor");
let c = commit("Merge branch 'x'");
assert_eq!(
(c.kind.as_str(), c.desc.as_str()),
("other", "Merge branch 'x'")
);
assert_eq!(commit("wip: thing").kind, "other");
assert_eq!(commit("FEAT: loud").kind, "feat");
assert_eq!(commit("fix(: broken").kind, "other");
for kind in KINDS {
assert_eq!(commit(&format!("{kind}: x")).kind, kind);
}
assert_eq!(commit("feat(): x").scope, None);
assert_eq!(commit("Ünï: ключ").kind, "other");
}
#[test]
fn suggest_rules() {
let cur = v("v1.4.2");
assert_eq!(
suggest_bump(&[commit("fix: a")], &cur).to_string_with_prefix(),
"v1.4.3"
);
assert_eq!(suggest_bump(&[], &cur).to_string_with_prefix(), "v1.4.3");
assert_eq!(
suggest_bump(&[commit("fix: a"), commit("feat: b")], &cur).to_string_with_prefix(),
"v1.5.0"
);
assert_eq!(
suggest_bump(&[commit("fix!: a")], &cur).to_string_with_prefix(),
"v2.0.0"
);
let zero = v("0.3.1");
assert_eq!(
suggest_bump(&[commit("feat!: a")], &zero).to_string_with_prefix(),
"0.4.0"
);
assert_eq!(
suggest_next(&[commit("feat: a")], None).to_string_with_prefix(),
"v0.1.0"
);
}
#[test]
fn changelog_snapshot() {
let commits = vec![
commit("feat(ui): menu"),
commit("fix: crash"),
commit("chore: deps"),
commit("refactor!: drop api"),
commit("plain subject"),
];
let expected = "### Breaking changes\n- drop api\n\n### Features\n- ui: menu\n\n### Fixes\n- crash\n\n### Other\n- deps\n- plain subject";
assert_eq!(render_changelog(&commits), expected);
assert_eq!(render_changelog(&[]), "");
}
#[test]
fn ls_remote_oids_unicode_and_noise() {
let text =
"aaa\trefs/tags/v1\nddd\trefs/heads/main\n\nbad line\neee\trefs/tags/release/é\n";
let names: Vec<String> = parse_ls_remote_oids(text)
.into_iter()
.map(|(n, _)| n)
.collect();
assert_eq!(names, ["v1", "release/é"]);
}
}