Preserve comments on version bump (#16141)

## Summary
Fixes [1633](https://github.com/astral-sh/uv/issues/16133). Preserves
comments preceding "version = ..." line when uv version --bump is ran

## Test Plan
Added IT test

---------

Co-authored-by: konsti <konstin@mailbox.org>
This commit is contained in:
Assad Yousuf 2025-10-09 09:07:00 -07:00 committed by GitHub
parent 787d035d5e
commit 24ebdf02c0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 56 additions and 4 deletions

View File

@ -1141,10 +1141,18 @@ impl PyProjectTomlMut {
.get_mut("project") .get_mut("project")
.and_then(Item::as_table_mut) .and_then(Item::as_table_mut)
.ok_or(Error::MalformedWorkspace)?; .ok_or(Error::MalformedWorkspace)?;
project.insert(
"version", if let Some(existing) = project.get_mut("version") {
Item::Value(Value::String(Formatted::new(version.to_string()))), if let Some(value) = existing.as_value_mut() {
); let mut formatted = Value::from(version.to_string());
*formatted.decor_mut() = value.decor().clone();
*value = formatted;
} else {
*existing = Item::Value(Value::from(version.to_string()));
}
} else {
project.insert("version", Item::Value(Value::from(version.to_string())));
}
Ok(()) Ok(())
} }

View File

@ -289,6 +289,50 @@ requires-python = ">=3.12"
Ok(()) Ok(())
} }
/// Preserve comments immediately preceding the version when bumping
#[test]
fn version_bump_preserves_preceding_comments() -> Result<()> {
let context: TestContext = TestContext::new("3.12");
let pyproject_toml = context.temp_dir.child("pyproject.toml");
pyproject_toml.write_str(
r#"
[project]
name = "hello-world"
# pre-1: stays above version
# pre-2: stays below pre-1
version = "0.1.0" # eol: stays on same line
# after-version: remains after version
description = "Add your description here"
"#,
)?;
// Bump patch version
context
.version()
.arg("--bump")
.arg("patch")
.assert()
.success();
// Ensure comments are preserved around the version entry
let pyproject = fs_err::read_to_string(&pyproject_toml)?;
assert_snapshot!(
pyproject,
@r#"
[project]
name = "hello-world"
# pre-1: stays above version
# pre-2: stays below pre-1
version = "0.1.1" # eol: stays on same line
# after-version: remains after version
description = "Add your description here"
"#
);
Ok(())
}
// Bump minor version // Bump minor version
#[test] #[test]
fn version_bump_minor() -> Result<()> { fn version_bump_minor() -> Result<()> {