use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Version {
pub major: u32,
pub minor: u32,
pub patch: u32,
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
#[derive(Debug, thiserror::Error)]
pub enum VersionError {
#[error("version file I/O failed: {0}")]
Io(#[from] std::io::Error),
#[error("version parse failed: {0}")]
Parse(String),
#[error("git command failed: {0}")]
Git(String),
}
pub fn detect_version_file(project_root: &Path) -> Option<PathBuf> {
for name in ["Cargo.toml", "pyproject.toml", "package.json"] {
let path = project_root.join(name);
if path.exists() {
return Some(path);
}
}
None
}
fn field_for(path: &Path, contents: &str) -> &'static str {
match path.file_name().and_then(|n| n.to_str()) {
Some("Cargo.toml") => {
if contents.contains("[workspace.package]") {
"workspace.package.version"
} else {
"package.version"
}
}
Some("pyproject.toml") => "project.version",
Some("package.json") => "version",
_ => "version",
}
}
pub fn read_major_version(path: &Path) -> Result<u32, VersionError> {
let contents = std::fs::read_to_string(path)?;
let field = field_for(path, &contents);
let version = find_version_in_contents(&contents, field)
.ok_or_else(|| VersionError::Parse(format!("field `{field}` not found in {path:?}")))?;
let major = version
.split(['.', '+', '-'])
.next()
.unwrap_or("0")
.parse::<u32>()
.map_err(|err| VersionError::Parse(format!("invalid major in `{version}`: {err}")))?;
Ok(major)
}
pub fn count_git_tags(project_root: &Path) -> Result<u32, VersionError> {
let output = Command::new("git")
.arg("tag")
.current_dir(project_root)
.output()
.map_err(|err| VersionError::Git(err.to_string()))?;
if !output.status.success() {
return Err(VersionError::Git(
String::from_utf8_lossy(&output.stderr).trim().to_string(),
));
}
let count = String::from_utf8_lossy(&output.stdout)
.lines()
.filter(|l| !l.trim().is_empty())
.count();
Ok(count as u32)
}
pub fn commits_since_last_minor_tag(project_root: &Path) -> Result<u32, VersionError> {
let last_tag = Command::new("git")
.args(["describe", "--tags", "--abbrev=0"])
.current_dir(project_root)
.output()
.map_err(|err| VersionError::Git(err.to_string()))?;
let range = if last_tag.status.success() {
let tag = String::from_utf8_lossy(&last_tag.stdout).trim().to_string();
format!("{tag}..HEAD")
} else {
"HEAD".to_string()
};
let output = Command::new("git")
.args(["rev-list", "--count", &range])
.current_dir(project_root)
.output()
.map_err(|err| VersionError::Git(err.to_string()))?;
if !output.status.success() {
return Ok(0);
}
let count = String::from_utf8_lossy(&output.stdout)
.trim()
.parse::<u32>()
.unwrap_or(0);
Ok(count)
}
pub fn compute_version(project_root: &Path) -> Result<Version, VersionError> {
let major = match detect_version_file(project_root) {
Some(path) => read_major_version(&path)?,
None => 0,
};
let minor = count_git_tags(project_root)?;
let patch = commits_since_last_minor_tag(project_root)?;
Ok(Version {
major,
minor,
patch,
})
}
pub fn read_version(project_root: &Path) -> Result<Version, VersionError> {
let path = detect_version_file(project_root)
.ok_or_else(|| VersionError::Parse("no version file found".into()))?;
let contents = std::fs::read_to_string(&path)?;
let field = field_for(&path, &contents);
let version_str = find_version_in_contents(&contents, field)
.ok_or_else(|| VersionError::Parse(format!("field `{field}` not found in {path:?}")))?;
parse_version_str(&version_str)
}
fn parse_version_str(version: &str) -> Result<Version, VersionError> {
let mut parts = version.split(['.', '+', '-']);
let mut next =
|label: &str| -> Result<u32, VersionError> {
parts.next().unwrap_or("0").parse::<u32>().map_err(|err| {
VersionError::Parse(format!("invalid {label} in `{version}`: {err}"))
})
};
let major = next("major")?;
let minor = next("minor")?;
let patch = next("patch")?;
Ok(Version {
major,
minor,
patch,
})
}
pub fn write_version(project_root: &Path, version: &Version) -> Result<PathBuf, VersionError> {
let path = detect_version_file(project_root)
.ok_or_else(|| VersionError::Parse("no version file found".into()))?;
let contents = std::fs::read_to_string(&path)?;
let field = field_for(&path, &contents);
let replaced = replace_version_in_contents(&contents, field, &version.to_string())
.ok_or_else(|| VersionError::Parse(format!("field `{field}` not found")))?;
let replaced = if field == "workspace.package.version" {
rewrite_workspace_member_pins(&replaced, &version.to_string())
} else {
replaced
};
std::fs::write(&path, replaced)?;
Ok(path)
}
fn rewrite_workspace_member_pins(contents: &str, new_version: &str) -> String {
let mut current = String::new();
let mut output = String::new();
for line in contents.lines() {
let trimmed = line.trim();
if let Some(header) = parse_section_header(trimmed) {
current = header.to_string();
output.push_str(line);
output.push('\n');
continue;
}
if current == "workspace.dependencies"
&& trimmed.contains('{')
&& trimmed.contains('}')
&& workspace_dependency_has_local_path(trimmed)
&& let Some(rewritten) = rewrite_inline_table_version(line, new_version)
{
output.push_str(&rewritten);
output.push('\n');
continue;
}
output.push_str(line);
output.push('\n');
}
output
}
fn inline_table_fragments(line: &str) -> Option<Vec<(usize, &str)>> {
let brace_start = line.find('{')?;
let brace_end = line.rfind('}')?;
if brace_end <= brace_start {
return None;
}
let inner = &line[brace_start + 1..brace_end];
let mut fragments = Vec::new();
let mut offset = brace_start + 1;
for fragment in inner.split(',') {
fragments.push((offset, fragment));
offset += fragment.len() + 1; }
Some(fragments)
}
fn workspace_dependency_has_local_path(line: &str) -> bool {
let Some(fragments) = inline_table_fragments(line) else {
return false;
};
for (_, fragment) in fragments {
let trimmed = fragment.trim();
let Some((key, value)) = trimmed.split_once('=') else {
continue;
};
if key.trim() != "path" {
continue;
}
let value = value.trim();
let Some(quote) = value.chars().next() else {
return false;
};
if quote != '"' && quote != '\'' {
return false;
}
let inner_value = &value[1..value.len().saturating_sub(1)];
return inner_value.starts_with("crates/");
}
false
}
fn rewrite_inline_table_version(line: &str, new_version: &str) -> Option<String> {
let fragments = inline_table_fragments(line)?;
for (frag_start, fragment) in fragments {
let trimmed = fragment.trim();
let Some((key, _value)) = trimmed.split_once('=') else {
continue;
};
if key.trim() != "version" {
continue;
}
let eq_rel = fragment.find('=')?;
let eq_abs = frag_start + eq_rel;
let after_eq = eq_abs + 1;
let rest = &line[after_eq..];
let ws_len = rest.len() - rest.trim_start().len();
let value_start = after_eq + ws_len;
let value_rest = &line[value_start..];
let quote_char = value_rest.chars().next()?;
if quote_char != '"' && quote_char != '\'' {
return None;
}
let after_quote = &value_rest[1..];
let end_rel = after_quote.find(quote_char)?;
let value_end = value_start + 1 + end_rel + 1;
let remainder = &line[value_end..];
let mut rewritten = String::with_capacity(line.len() + new_version.len());
rewritten.push_str(&line[..value_start]);
rewritten.push(quote_char);
rewritten.push_str(new_version);
rewritten.push(quote_char);
rewritten.push_str(remainder);
return Some(rewritten);
}
None
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelfPin {
pub name: String,
pub version: String,
}
pub fn read_workspace_self_pins(contents: &str) -> (Option<String>, Vec<SelfPin>) {
let workspace_version = find_version_in_contents(contents, "workspace.package.version");
let mut current = String::new();
let mut pins = Vec::new();
for line in contents.lines() {
let trimmed = line.trim();
if let Some(header) = parse_section_header(trimmed) {
current = header.to_string();
continue;
}
if current == "workspace.dependencies"
&& trimmed.contains('{')
&& trimmed.contains('}')
&& workspace_dependency_has_local_path(trimmed)
&& let Some(fragments) = inline_table_fragments(trimmed)
{
let name = trimmed
.split_once('=')
.map(|(n, _)| n.trim().to_string())
.unwrap_or_default();
for (_, fragment) in fragments {
let frag = fragment.trim();
let Some((key, value)) = frag.split_once('=') else {
continue;
};
if key.trim() != "version" {
continue;
}
let value = value.trim().trim_matches(['"', '\'']);
pins.push(SelfPin {
name: name.clone(),
version: value.to_string(),
});
}
}
}
(workspace_version, pins)
}
fn split_field(field: &str) -> (&str, &str) {
match field.rsplit_once('.') {
Some((section, key)) => (section, key),
None => ("", field),
}
}
fn parse_section_header(trimmed: &str) -> Option<&str> {
let inner = if trimmed.starts_with("[[") && trimmed.ends_with("]]") {
trimmed.strip_prefix("[[")?.strip_suffix("]]")?
} else {
trimmed.strip_prefix('[')?.strip_suffix(']')?
};
Some(inner.trim())
}
fn find_version_in_contents(contents: &str, field: &str) -> Option<String> {
let (section, key) = split_field(field);
let mut current = "";
for line in contents.lines() {
let trimmed = line.trim();
if let Some(header) = parse_section_header(trimmed) {
current = header;
continue;
}
if current != section {
continue;
}
if let Some((lhs, value)) = trimmed.split_once(['=', ':']) {
let lhs_key = lhs.trim().trim_matches('"').trim_matches('\'');
if lhs_key != key {
continue;
}
let value = value.trim();
if value.starts_with('{') {
continue;
}
return match value.chars().next() {
Some(q @ ('"' | '\'')) => {
value[1..].find(q).map(|end| value[1..1 + end].to_string())
}
_ => {
let end = value.find([' ', '\t', ',', '#']).unwrap_or(value.len());
Some(value[..end].to_string())
}
};
}
}
None
}
fn replace_version_in_contents(contents: &str, field: &str, new_version: &str) -> Option<String> {
let (section, key) = split_field(field);
let mut current = "";
let mut changed = false;
let mut output = String::new();
for line in contents.lines() {
let trimmed = line.trim();
if let Some(header) = parse_section_header(trimmed) {
current = header;
output.push_str(line);
output.push('\n');
continue;
}
if !changed
&& current == section
&& let Some((left, value)) = line.split_once(['=', ':'])
{
let left_key = left.trim().trim_matches('"').trim_matches('\'');
if left_key == key && !value.trim().starts_with('{') {
let separator: &str = if trimmed.contains('=') { " = " } else { ": " };
let trimmed_value = value.trim();
let needs_quote = trimmed_value.starts_with('"') || trimmed_value.starts_with('\'');
let quote_char: &str = if trimmed_value.starts_with('\'') {
"'"
} else {
"\""
};
let remainder = if needs_quote {
trimmed_value[1..]
.find(quote_char)
.map(|end| &trimmed_value[end + 2..])
.unwrap_or("")
} else {
let end = trimmed_value
.find([' ', '\t', ',', '#'])
.unwrap_or(trimmed_value.len());
&trimmed_value[end..]
};
output.push_str(left.trim_end());
output.push_str(separator);
if needs_quote {
output.push_str(quote_char);
output.push_str(new_version);
output.push_str(quote_char);
} else {
output.push_str(new_version);
}
output.push_str(remainder.trim_end());
output.push('\n');
changed = true;
continue;
}
}
output.push_str(line);
output.push('\n');
}
changed.then_some(output)
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn git(root: &Path, args: &[&str]) {
let ok = Command::new("git")
.args(args)
.current_dir(root)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?} failed");
}
fn init_repo(root: &Path) {
git(root, &["init", "-q"]);
git(root, &["config", "user.email", "test@example.com"]);
git(root, &["config", "user.name", "Test"]);
git(root, &["config", "commit.gpgsign", "false"]);
git(root, &["config", "tag.gpgsign", "false"]);
git(root, &["config", "core.hooksPath", "/dev/null"]);
}
fn commit(root: &Path, name: &str) {
std::fs::write(root.join(name), name).unwrap();
git(root, &["add", "."]);
git(root, &["commit", "-q", "-m", &format!("add {name}")]);
}
#[test]
fn detect_prefers_cargo_then_pyproject_then_package_json() {
let dir = tempfile::tempdir().unwrap();
assert!(detect_version_file(dir.path()).is_none());
std::fs::write(dir.path().join("package.json"), "{\"version\":\"1.0.0\"}").unwrap();
assert!(
detect_version_file(dir.path())
.unwrap()
.ends_with("package.json")
);
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion=\"1.0.0\"",
)
.unwrap();
assert!(
detect_version_file(dir.path())
.unwrap()
.ends_with("Cargo.toml")
);
}
#[test]
fn read_major_from_workspace_package() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("Cargo.toml");
std::fs::write(
&file,
"[workspace.package]\nversion = \"2.5.7\"\nedition = \"2024\"\n",
)
.unwrap();
assert_eq!(read_major_version(&file).unwrap(), 2);
}
#[test]
fn inline_table_version_does_not_shadow_workspace_package() {
assert_eq!(parse_section_header("[[bin]]"), Some("bin"));
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("Cargo.toml");
std::fs::write(
&file,
"[[bin]]\nname = \"devflow\"\n\
[workspace.dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\n\
[workspace.package]\nversion = \"1.2.0\"\n",
)
.unwrap();
assert_eq!(read_major_version(&file).unwrap(), 1);
write_version(
dir.path(),
&Version {
major: 2,
minor: 3,
patch: 4,
},
)
.unwrap();
let contents = std::fs::read_to_string(file).unwrap();
assert!(contents.contains("serde = { version = \"1\""));
assert!(contents.contains("[workspace.package]\nversion = \"2.3.4\""));
}
#[test]
fn read_major_from_package_json() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("package.json");
std::fs::write(&file, "{\n \"version\": \"3.1.0\"\n}\n").unwrap();
assert_eq!(read_major_version(&file).unwrap(), 3);
}
#[test]
fn count_tags_and_commits_drive_minor_and_patch() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init_repo(root);
std::fs::write(root.join("Cargo.toml"), "[package]\nversion = \"2.0.0\"\n").unwrap();
commit(root, "a.txt");
assert_eq!(count_git_tags(root).unwrap(), 0);
let v = compute_version(root).unwrap();
assert_eq!(v.major, 2);
assert_eq!(v.minor, 0);
assert!(v.patch >= 1);
git(root, &["tag", "v2.0.0"]);
commit(root, "b.txt");
commit(root, "c.txt");
assert_eq!(count_git_tags(root).unwrap(), 1);
assert_eq!(commits_since_last_minor_tag(root).unwrap(), 2);
let v = compute_version(root).unwrap();
assert_eq!(
v,
Version {
major: 2,
minor: 1,
patch: 2
}
);
assert_eq!(v.to_string(), "2.1.2");
}
#[test]
fn write_version_replaces_in_cargo_toml() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion = \"0.1.0\"\n",
)
.unwrap();
let path = write_version(
dir.path(),
&Version {
major: 2,
minor: 3,
patch: 4,
},
)
.unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
assert!(contents.contains("version = \"2.3.4\""));
}
#[test]
fn write_version_replaces_in_workspace_cargo_toml() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n",
)
.unwrap();
let path = write_version(
dir.path(),
&Version {
major: 2,
minor: 3,
patch: 4,
},
)
.unwrap();
let contents = std::fs::read_to_string(&path).unwrap();
assert!(contents.contains("[workspace.package]\nversion = \"2.3.4\""));
}
#[test]
fn write_version_errors_without_version_file() {
let dir = tempfile::tempdir().unwrap();
assert!(matches!(
write_version(
dir.path(),
&Version {
major: 1,
minor: 0,
patch: 0
}
),
Err(VersionError::Parse(_))
));
}
#[test]
fn read_version_round_trips_through_write_version_in_plain_cargo_toml() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion = \"0.1.0\"\n",
)
.unwrap();
let written = Version {
major: 2,
minor: 3,
patch: 4,
};
write_version(dir.path(), &written).unwrap();
assert_eq!(read_version(dir.path()).unwrap(), written);
}
#[test]
fn read_version_round_trips_through_write_version_in_workspace_cargo_toml() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n",
)
.unwrap();
let written = Version {
major: 5,
minor: 6,
patch: 7,
};
write_version(dir.path(), &written).unwrap();
assert_eq!(read_version(dir.path()).unwrap(), written);
}
#[test]
fn read_version_round_trips_through_write_version_in_package_json() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("package.json"),
"{\n \"version\": \"0.1.0\"\n}\n",
)
.unwrap();
let written = Version {
major: 1,
minor: 9,
patch: 12,
};
write_version(dir.path(), &written).unwrap();
assert_eq!(read_version(dir.path()).unwrap(), written);
}
#[test]
fn read_version_errors_without_version_file() {
let dir = tempfile::tempdir().unwrap();
assert!(matches!(
read_version(dir.path()),
Err(VersionError::Parse(_))
));
}
#[test]
fn write_version_preserves_trailing_comma_in_package_json() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("package.json"),
"{\n \"name\": \"x\",\n \"version\": \"0.1.0\",\n \"private\": true\n}\n",
)
.unwrap();
write_version(
dir.path(),
&Version {
major: 2,
minor: 3,
patch: 4,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
let parsed: serde_json::Value = serde_json::from_str(&contents).unwrap_or_else(|err| {
panic!("package.json no longer parses as JSON: {err}\n{contents}")
});
assert_eq!(parsed["name"], "x");
assert_eq!(parsed["private"], true);
assert_eq!(parsed["version"], "2.3.4");
}
#[test]
fn write_version_preserves_trailing_comment_in_toml() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion = \"0.1.0\" # pinned\n",
)
.unwrap();
write_version(
dir.path(),
&Version {
major: 2,
minor: 3,
patch: 4,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents.contains("version = \"2.3.4\" # pinned"),
"expected trailing comment to survive, got: {contents}"
);
}
#[test]
fn write_version_preserves_trailing_comment_in_single_quoted_toml() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion = '0.1.0' # pinned\n",
)
.unwrap();
write_version(
dir.path(),
&Version {
major: 2,
minor: 3,
patch: 4,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents.contains("version = '2.3.4' # pinned"),
"expected single-quoted value and trailing comment to survive, got: {contents}"
);
}
#[test]
fn read_version_extracts_clean_value_with_trailing_comment() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion = \"1.7.0\" # pinned release version\n",
)
.unwrap();
assert_eq!(
read_version(dir.path()).unwrap(),
Version {
major: 1,
minor: 7,
patch: 0
}
);
}
#[test]
fn read_version_extracts_clean_value_without_trailing_comment() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[package]\nversion = \"1.7.0\"\n",
)
.unwrap();
assert_eq!(
read_version(dir.path()).unwrap(),
Version {
major: 1,
minor: 7,
patch: 0
}
);
}
#[test]
fn read_workspace_self_pins_extracts_clean_workspace_version_with_trailing_comment() {
let (workspace_version, _pins) = read_workspace_self_pins(
"[workspace.package]\nversion = \"1.7.0\" # pinned release version\nedition = \"2024\"\n",
);
assert_eq!(workspace_version.as_deref(), Some("1.7.0"));
}
#[test]
fn read_version_does_not_recompute_from_git_tags() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
init_repo(root);
std::fs::write(root.join("Cargo.toml"), "[package]\nversion = \"2.0.0\"\n").unwrap();
commit(root, "a.txt");
write_version(
root,
&Version {
major: 2,
minor: 0,
patch: 0,
},
)
.unwrap();
git(root, &["tag", "v2.0.0"]);
commit(root, "b.txt");
commit(root, "c.txt");
assert_eq!(
read_version(root).unwrap(),
Version {
major: 2,
minor: 0,
patch: 0
}
);
}
#[test]
fn write_version_rewrites_workspace_dependency_self_pin() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
[workspace.dependencies]\n\
devflow-core = { path = \"crates/devflow-core\", version = \"1.6.0\" }\n",
)
.unwrap();
write_version(
dir.path(),
&Version {
major: 1,
minor: 7,
patch: 0,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents.contains("[workspace.package]\nversion = \"1.7.0\""),
"expected [workspace.package] version to be rewritten, got: {contents}"
);
assert!(
contents
.contains("devflow-core = { path = \"crates/devflow-core\", version = \"1.7.0\" }"),
"expected the [workspace.dependencies] self-pin to be rewritten to 1.7.0 \
alongside [workspace.package] version, got: {contents}"
);
}
#[test]
fn write_version_no_ops_on_missing_workspace_dependencies_section() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("Cargo.toml"),
"[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n",
)
.unwrap();
write_version(
dir.path(),
&Version {
major: 1,
minor: 7,
patch: 0,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert_eq!(
contents,
"[workspace.package]\nversion = \"1.7.0\"\nedition = \"2024\"\n"
);
}
#[test]
fn write_version_no_ops_on_member_with_no_version_key() {
let dir = tempfile::tempdir().unwrap();
let toml = "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
[workspace.dependencies]\n\
devflow-core = { path = \"crates/devflow-core\" }\n";
std::fs::write(dir.path().join("Cargo.toml"), toml).unwrap();
write_version(
dir.path(),
&Version {
major: 1,
minor: 7,
patch: 0,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents.contains("devflow-core = { path = \"crates/devflow-core\" }"),
"expected the version-less path member to be left byte-identical, got: {contents}"
);
}
#[test]
fn write_version_leaves_third_party_version_only_dep_untouched() {
let dir = tempfile::tempdir().unwrap();
let third_party_line = "serde = { version = \"1\", features = [\"derive\"] }";
let toml = format!(
"[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
[workspace.dependencies]\n\
devflow-core = {{ path = \"crates/devflow-core\", version = \"1.6.0\" }}\n\
{third_party_line}\n"
);
std::fs::write(dir.path().join("Cargo.toml"), &toml).unwrap();
write_version(
dir.path(),
&Version {
major: 1,
minor: 7,
patch: 0,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents
.contains("devflow-core = { path = \"crates/devflow-core\", version = \"1.7.0\" }"),
"expected the local path member's version to be rewritten, got: {contents}"
);
assert!(
contents.contains(third_party_line),
"expected the third-party version-only dep to be byte-identical, got: {contents}"
);
}
#[test]
fn write_version_preserves_comment_and_quote_in_workspace_dependency_pin() {
let dir = tempfile::tempdir().unwrap();
let toml = "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
[workspace.dependencies]\n\
devflow-core = { path = 'crates/devflow-core', version = '1.6.0' } # pinned\n";
std::fs::write(dir.path().join("Cargo.toml"), toml).unwrap();
write_version(
dir.path(),
&Version {
major: 1,
minor: 7,
patch: 0,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents.contains(
"devflow-core = { path = 'crates/devflow-core', version = '1.7.0' } # pinned"
),
"expected single-quote style and trailing comment to survive the rewrite, got: {contents}"
);
}
#[test]
fn write_version_rewrites_self_pin_regardless_of_key_order() {
let dir = tempfile::tempdir().unwrap();
let toml = "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
[workspace.dependencies]\n\
devflow-core = { version = \"1.6.0\", path = \"crates/devflow-core\" }\n";
std::fs::write(dir.path().join("Cargo.toml"), toml).unwrap();
write_version(
dir.path(),
&Version {
major: 1,
minor: 7,
patch: 0,
},
)
.unwrap();
let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
assert!(
contents
.contains("devflow-core = { version = \"1.7.0\", path = \"crates/devflow-core\" }"),
"expected version to be rewritten regardless of key order, got: {contents}"
);
}
}