Skip to content

Commit

Permalink
Avoid adding extra newline for script with non-empty prelude (#6366)
Browse files Browse the repository at this point in the history
Closes #6364
  • Loading branch information
j178 authored Aug 21, 2024
1 parent 7fdd26c commit 1377c68
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 7 deletions.
14 changes: 7 additions & 7 deletions crates/uv-scripts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand All @@ -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
);
Expand Down
56 changes: 56 additions & 0 deletions crates/uv/tests/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<()> {
Expand Down

0 comments on commit 1377c68

Please sign in to comment.