Avoid adding extra newline for script with non-empty prelude (#6366)

Closes #6364
This commit is contained in:
Jo 2024-08-22 04:57:08 +08:00 committed by GitHub
parent 7fdd26c81f
commit 1377c6807d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 63 additions and 7 deletions

View file

@ -80,11 +80,15 @@ impl Pep723Script {
let metadata = Pep723Metadata::from_str(&default_metadata)?;
// Extract the shebang and script content.
let (prelude, postlude) = extract_shebang(&contents)?;
let (shebang, postlude) = extract_shebang(&contents)?;
Ok(Self {
path: file.as_ref().to_path_buf(),
prelude,
prelude: if shebang.is_empty() {
String::new()
} else {
format!("{shebang}\n")
},
metadata,
postlude,
})
@ -94,11 +98,7 @@ impl Pep723Script {
pub async fn write(&self, metadata: &str) -> Result<(), Pep723Error> {
let content = format!(
"{}{}{}",
if self.prelude.is_empty() {
String::new()
} else {
format!("{}\n", self.prelude)
},
self.prelude,
serialize_metadata(metadata),
self.postlude
);

View file

@ -3584,6 +3584,62 @@ fn add_script_without_metadata_table_with_shebang() -> Result<()> {
Ok(())
}
/// Add to a script with a metadata table and a shebang.
#[test]
fn add_script_with_metadata_table_and_shebang() -> Result<()> {
let context = TestContext::new("3.12");
let script = context.temp_dir.child("script.py");
script.write_str(indoc! {r#"
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12"
# dependencies = []
# ///
import requests
from rich.pretty import pprint
resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])
"#})?;
uv_snapshot!(context.filters(), context.add(&["rich", "requests<3"]).arg("--script").arg("script.py"), @r###"
success: true
exit_code: 0
----- stdout -----
----- stderr -----
Updated `script.py`
"###);
let script_content = fs_err::read_to_string(context.temp_dir.join("script.py"))?;
insta::with_settings!({
filters => context.filters(),
}, {
assert_snapshot!(
script_content, @r###"
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "rich",
# "requests<3",
# ]
# ///
import requests
from rich.pretty import pprint
resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])
"###
);
});
Ok(())
}
/// Add to a script without a metadata table, but with a docstring.
#[test]
fn add_script_without_metadata_table_with_docstring() -> Result<()> {