From e1fa0c5e617ff95f464a8f23fe909769d8a1d634 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Tue, 27 Aug 2024 13:23:26 -0400 Subject: [PATCH] Avoid writing invalid PEP 723 scripts on tool.uv.sources --- crates/uv-scripts/src/lib.rs | 9 +++---- crates/uv/tests/edit.rs | 52 ++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 5 deletions(-) diff --git a/crates/uv-scripts/src/lib.rs b/crates/uv-scripts/src/lib.rs index 470c452f83b2e..089765f11c838 100644 --- a/crates/uv-scripts/src/lib.rs +++ b/crates/uv-scripts/src/lib.rs @@ -347,13 +347,12 @@ fn serialize_metadata(metadata: &str) -> String { output.push('\n'); for line in metadata.lines() { - if line.is_empty() { - output.push('\n'); - } else { - output.push_str("# "); + output.push('#'); + if !line.is_empty() { + output.push(' '); output.push_str(line); - output.push('\n'); } + output.push('\n'); } output.push_str("# ///"); diff --git a/crates/uv/tests/edit.rs b/crates/uv/tests/edit.rs index c8425aa140c2a..86a9af9b26491 100644 --- a/crates/uv/tests/edit.rs +++ b/crates/uv/tests/edit.rs @@ -3792,6 +3792,58 @@ fn add_script_without_metadata_table_with_docstring() -> Result<()> { Ok(()) } +/// Add to a PEP 732 script with a `tool.uv.sources` dependency. +#[test] +fn add_script_sources() -> Result<()> { + let context = TestContext::new("3.12"); + + let script = context.temp_dir.child("script.py"); + script.write_str(indoc! {r#" + 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(&["anyio @ git+https://github.com/agronholm/anyio"]).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###" + # /// script + # requires-python = ">=3.12" + # dependencies = [ + # "anyio", + # ] + # + # [tool.uv.sources] + # anyio = { git = "https://github.com/agronholm/anyio" } + # /// + 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(()) +} + /// Remove from a PEP732 script, #[test] fn remove_script() -> Result<()> {