changelog: parse entries with a shared limit-based helper

Replace parse_previous_version/parse_previous_version_from_str with
parse_changelog_entries(path, limit: Option<usize>), parsing up to the
given number of entries (None: the whole file) newest-first through the
same strict entry parser instead of a header-only scan. The single-entry
helpers stay as thin wrappers, and callers needing the previous entry
now get its full source name and version, not just the raw string.
This commit is contained in:
2026-09-17 23:34:42 +02:00
parent e7b35f5c37
commit c18f1fe9c2
4 changed files with 192 additions and 67 deletions
+170 -41
View File
@@ -36,8 +36,12 @@ pub struct ChangelogEntry {
pub closes: Option<String>,
}
/// Parse the most recent entry of a Debian changelog file.
pub fn parse_changelog_entry(path: &Path) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
/// Parse up to `limit` entries of a Debian changelog file, newest first
/// (`None` parses the whole file).
pub fn parse_changelog_entries(
path: &Path,
limit: Option<usize>,
) -> Result<Vec<ChangelogEntry>, Box<dyn std::error::Error>> {
let content = std::fs::read_to_string(path).map_err(|e| {
format!(
"failed to read changelog '{}': {}. Make sure you are running \
@@ -46,17 +50,60 @@ pub fn parse_changelog_entry(path: &Path) -> Result<ChangelogEntry, Box<dyn std:
e
)
})?;
parse_changelog_entry_from_str(&content)
parse_changelog_entries_from_str(&content, limit)
}
/// Parse the most recent changelog entry from its textual content. `origin`
/// is used in error messages only.
/// Parse the most recent entry of a Debian changelog file.
pub fn parse_changelog_entry(path: &Path) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
parse_changelog_entries(path, Some(1)).map(|mut entries| entries.remove(0))
}
/// Parse the most recent changelog entry from its textual content.
pub fn parse_changelog_entry_from_str(
content: &str,
) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
parse_changelog_entries_from_str(content, Some(1)).map(|mut entries| entries.remove(0))
}
/// Parse changelog entries from their textual content, newest first.
///
/// `limit` bounds the number of parsed entries (`None` parses the whole
/// file). Content below the last entry that is not another entry header
/// (e.g. an older changelog kept in a non-Debian format) is ignored.
pub fn parse_changelog_entries_from_str(
content: &str,
limit: Option<usize>,
) -> Result<Vec<ChangelogEntry>, Box<dyn std::error::Error>> {
let origin = "changelog";
let mut lines = content.lines().peekable();
let mut entries = Vec::new();
loop {
if limit.is_some_and(|n| entries.len() >= n) {
break;
}
// Blank separators between entries.
while lines.peek().is_some_and(|l| l.trim().is_empty()) {
lines.next();
}
let Some(next) = lines.peek() else {
break;
};
if !entries.is_empty() && !looks_like_header(next.trim_end()) {
break;
}
entries.push(parse_one_entry(&mut lines, origin)?);
}
Ok(entries)
}
/// Parse one entry: header line, body, maintainer trailer. Parsing stops
/// without consuming the first line that is a trailer terminator, an emacs
/// local-variables block, or the next entry's header — the stream can then
/// be resumed for the following entry.
fn parse_one_entry(
lines: &mut std::iter::Peekable<std::str::Lines<'_>>,
origin: &str,
) -> Result<ChangelogEntry, Box<dyn std::error::Error>> {
// --- Header line: `package (version) distributions; urgency=medium[, key=value]`
let header = loop {
match lines.next() {
@@ -104,19 +151,24 @@ pub fn parse_changelog_entry_from_str(
// --- Body until trailer line ` -- Name <email> Date`
let mut body_lines: Vec<String> = Vec::new();
let mut trailer: Option<String> = None;
for line in lines {
loop {
let Some(line) = lines.peek().copied() else {
break;
};
let line = line.trim_end();
if line.starts_with(" -- ") {
trailer = Some(line.to_string());
trailer = lines.next().map(|l| l.trim_end().to_string());
break;
}
// Stop at an emacs local-variables block or a new entry header.
// Stop at an emacs local-variables block or a new entry header
// (both peeked, not consumed).
if line.starts_with("Local variables:") {
break;
}
if !line.trim().is_empty() && looks_like_header(line) && !body_lines.is_empty() {
break;
}
lines.next();
// Blank lines become "." like dpkg does for the Changes field.
if line.trim().is_empty() {
body_lines.push(".".to_string());
@@ -211,39 +263,6 @@ fn find_closes(body_lines: &[String]) -> Option<String> {
)
}
/// Return the version of the *previous* changelog entry (the second header
/// in the file), or `None` when only one entry exists.
pub fn parse_previous_version(path: &Path) -> Result<Option<String>, Box<dyn std::error::Error>> {
let content = std::fs::read_to_string(path)
.map_err(|e| format!("failed to read changelog '{}': {}", path.display(), e))?;
parse_previous_version_from_str(&content)
}
/// Return the version of the *previous* changelog entry from the textual
/// content of a changelog file.
pub fn parse_previous_version_from_str(
content: &str,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
let mut seen_first = false;
for line in content.lines() {
let line = line.trim_end();
if looks_like_header(line) {
if !seen_first {
seen_first = true;
continue;
}
let open = line
.find('(')
.ok_or_else(|| format!("invalid changelog header: {line}"))?;
let close = line[open..]
.find(')')
.ok_or_else(|| format!("unbalanced parenthesis in changelog header '{line}'"))?;
return Ok(Some(line[open + 1..open + close].to_string()));
}
}
Ok(None)
}
/// Heuristic check for a changelog entry header line
/// (`name (version) dist; urgency=...`).
fn looks_like_header(line: &str) -> bool {
@@ -309,4 +328,114 @@ pkg (1.0-1+b1) unstable; urgency=medium, binary-only=yes
assert!(entry.binary_only);
assert_eq!(entry.version.full(), "1.0-1+b1");
}
const THREE_ENTRIES: &str = "\
pkg (2.0-1) unstable; urgency=low
* New upstream release.
-- Pkh Tester <pkh@example.com> Thu, 01 Jan 2026 00:00:00 +0000
pkg (1.4-2) unstable; urgency=medium
* Revision bump.
-- Pkh Tester <pkh@example.com> Wed, 01 Jan 2025 00:00:00 +0000
pkg (1.4-1) unstable; urgency=medium
* Initial release.
-- Pkh Tester <pkh@example.com> Sat, 01 Mar 2025 00:00:00 +0000
";
#[test]
fn entries_parse_newest_first_with_limits() {
// Whole file.
let all = parse_changelog_entries_from_str(THREE_ENTRIES, None).unwrap();
assert_eq!(all.len(), 3);
assert_eq!(all[0].version.full(), "2.0-1");
assert_eq!(all[1].version.full(), "1.4-2");
assert_eq!(all[2].version.full(), "1.4-1");
// Bounded limits.
assert_eq!(
parse_changelog_entries_from_str(THREE_ENTRIES, Some(1))
.unwrap()
.len(),
1
);
let two = parse_changelog_entries_from_str(THREE_ENTRIES, Some(2)).unwrap();
assert_eq!(two.len(), 2);
assert_eq!(two[0].version.full(), "2.0-1");
assert_eq!(two[1].version.full(), "1.4-2");
// A limit beyond the entry count yields everything.
assert_eq!(
parse_changelog_entries_from_str(THREE_ENTRIES, Some(10))
.unwrap()
.len(),
3
);
// The single-entry helpers agree with a limit of 1.
let one = parse_changelog_entries_from_str(THREE_ENTRIES, Some(1)).unwrap();
let via_helper = parse_changelog_entry_from_str(THREE_ENTRIES).unwrap();
assert_eq!(one[0].version.full(), via_helper.version.full());
assert_eq!(one[0].source, via_helper.source);
}
#[test]
fn entries_ignore_trailing_foreign_content() {
let content = "\
pkg (1.0) unstable; urgency=medium
* Something.
-- Pkh Tester <pkh@example.com> Thu, 01 Jan 2026 00:00:00 +0000
older changelog kept in an ad-hoc format:
version 0.9 - some text, not a Debian entry
version 0.8 - more text
";
let entries = parse_changelog_entries_from_str(content, None).unwrap();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].version.full(), "1.0");
}
#[test]
fn entries_parse_body_of_later_entries() {
let entries = parse_changelog_entries_from_str(THREE_ENTRIES, Some(2)).unwrap();
// The second entry's body and trailer are fully parsed, not merely
// its header line.
assert_eq!(
entries[1].changes_field,
"\npkg (1.4-2) unstable; urgency=medium\n.\n * Revision bump."
);
assert_eq!(entries[1].maintainer_email, "pkh@example.com");
assert_eq!(entries[1].urgency, "medium");
}
#[test]
fn entries_reject_malformed_later_entry() {
let content = "\
pkg (1.0) unstable; urgency=medium
* Something.
-- Pkh Tester <pkh@example.com> Thu, 01 Jan 2026 00:00:00 +0000
pkg (0.9) unstable; urgency=medium
* No trailer below.
";
assert!(parse_changelog_entries_from_str(content, None).is_err());
// Not parsed when not requested.
assert_eq!(
parse_changelog_entries_from_str(content, Some(1))
.unwrap()
.len(),
1
);
}
}