use anyhow::{Context, Result};
use ctl_core::formatdoc;
use serde::{Deserialize, Serialize};
const OPEN: &str = "<!-- verctl:stop ";
const CLOSE: &str = " -->";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Stop {
pub package: String,
pub version: String,
pub cause: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retry_after: Option<String>,
}
impl Stop {
#[must_use]
pub fn new(package: &str, version: &str, cause: &str, retry_after: Option<String>) -> Self {
Self {
package: package.to_owned(),
version: version.to_owned(),
cause: cause.to_owned(),
retry_after,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "kebab-case")]
pub enum Record {
#[default]
Absent,
Read(Stop),
Unreadable,
}
#[must_use]
pub fn read(body: &str) -> Record {
let Some(line) = body.lines().map(str::trim).find(|line| is_record(line)) else {
return Record::Absent;
};
line.strip_prefix(OPEN)
.and_then(|rest| rest.strip_suffix(CLOSE))
.and_then(|json| serde_json::from_str(json).ok())
.map_or(Record::Unreadable, Record::Read)
}
pub fn write(body: &str, stop: &Stop) -> Result<String> {
let json = serde_json::to_string(stop)
.context("encode the stop record")?
.replace("-->", "--\\u003e");
let notes = body
.lines()
.filter(|line| !is_record(line.trim()))
.collect::<Vec<_>>()
.join("\n");
Ok(formatdoc! {"
{notes}
{OPEN}{json}{CLOSE}
",
notes = notes.trim_end(),
})
}
fn is_record(line: &str) -> bool {
line.starts_with(OPEN.trim_end())
}
#[cfg(test)]
mod tests;