verctl-core 0.9.5

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! A package's version on one marker line of any file type.
//! The line contains a comment opener (`#`, `//`, or `<!--`), `version:`, a
//! space, and the version, with an optional `-->` after it.
//!
//! A single file can be a package, such as one reusable workflow. Its
//! version has to live in the file, and a comment is the one place every
//! format leaves alone. A package opts in with `marker: true`. A stray
//! `# version:` line then never changes how verctl reads a file nobody
//! declared.

use anyhow::{Result, bail};
use semver::Version;

/// Comment openers a marker line may start with, longest first so `<!--`
/// is never read as text after some shorter opener.
const OPENERS: [&str; 3] = ["<!--", "//", "#"];

/// The key every marker line spells.
const KEY: &str = "version:";

/// The one marker line: where its version sits and what it contains.
struct Marker<'a> {
    /// Byte range of the version text in the file.
    start: usize,
    end: usize,
    /// The version text.
    version: &'a str,
}

/// The version on the file's one marker line.
///
/// # Errors
///
/// Returns an error when the file contains no marker line, more than one, or
/// one whose value is not a version. The error lists the line numbers.
pub(crate) fn read(raw: &str) -> Result<String> {
    Ok(marker(raw)?.version.to_owned())
}

/// `raw` with the marker line's version replaced and every other byte kept.
///
/// # Errors
///
/// Fails on the same conditions as [`read`].
pub(crate) fn write(raw: &str, new_version: &str) -> Result<String> {
    let found = marker(raw)?;
    Ok(format!(
        "{}{new_version}{}",
        &raw[..found.start],
        &raw[found.end..]
    ))
}

fn marker(raw: &str) -> Result<Marker<'_>> {
    let mut found = Vec::new();
    let mut offset = 0;
    for (index, line) in raw.split_inclusive('\n').enumerate() {
        if let Some(marker) = parse_line(line, offset) {
            found.push((index + 1, marker));
        }
        offset += line.len();
    }
    if found.len() > 1 {
        let lines: Vec<String> = found.iter().map(|(number, _)| number.to_string()).collect();
        bail!(
            "contains a marker line on lines {}; keep exactly one",
            lines.join(" and ")
        );
    }
    let Some((number, marker)) = found.pop() else {
        bail!("contains no marker line such as `# version: 0.1.0`");
    };
    if Version::parse(marker.version).is_err() {
        bail!(
            "line {number} has `version: {}`, which is not a version",
            marker.version
        );
    }
    Ok(marker)
}

/// The marker on `line`, when the line is one. The line starts at byte
/// `offset` of the file. It contains optional indentation, an opener,
/// `version:`, one space, the value, and nothing after it but `-->` for an HTML
/// comment.
fn parse_line(line: &str, offset: usize) -> Option<Marker<'_>> {
    let content = line.trim_end_matches(['\n', '\r']);
    let trimmed = content.trim_start();
    let opener = OPENERS
        .into_iter()
        .find(|opener| trimmed.starts_with(opener))?;
    let after_opener = trimmed[opener.len()..].trim_start();
    let value = after_opener.strip_prefix(KEY)?.strip_prefix(' ')?;
    let version = value.split_whitespace().next()?;
    let rest = value.strip_prefix(version)?.trim();
    let closes = rest.is_empty() || (opener == "<!--" && rest == "-->");
    if !closes {
        return None;
    }
    let start = offset + (content.len() - value.len());
    Some(Marker {
        start,
        end: start + version.len(),
        version,
    })
}

#[cfg(test)]
mod tests;