Skip to main content

uv_scripts/
lib.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::io;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6use std::sync::LazyLock;
7
8use memchr::memmem::Finder;
9use serde::Deserialize;
10use thiserror::Error;
11use tracing::instrument;
12use url::Url;
13
14use uv_configuration::NoSources;
15use uv_normalize::PackageName;
16use uv_pep440::VersionSpecifiers;
17use uv_pypi_types::VerbatimParsedUrl;
18use uv_redacted::DisplaySafeUrl;
19use uv_settings::{GlobalOptions, ResolverInstallerSchema};
20use uv_warnings::warn_user;
21use uv_workspace::pyproject::{BuildConstraintDependency, ExtraBuildDependency, Sources};
22
23mod discovery;
24
25pub use discovery::{ScriptDiscoveryError, find_scripts};
26
27pub use uv_configuration::ExcludeDependency;
28pub use uv_workspace::pyproject::OverrideDependency;
29
30static FINDER: LazyLock<Finder> = LazyLock::new(|| Finder::new(b"# /// script"));
31
32/// A PEP 723 item, either read from a script on disk or provided via `stdin`.
33#[derive(Debug)]
34pub enum Pep723Item {
35    /// A PEP 723 script read from disk.
36    Script(Pep723Script),
37    /// A PEP 723 script provided via `stdin`.
38    Stdin(Pep723Metadata),
39    /// A PEP 723 script provided via a remote URL.
40    Remote(Pep723Metadata, DisplaySafeUrl),
41}
42
43impl Pep723Item {
44    /// Return the [`Pep723Metadata`] associated with the item.
45    pub fn metadata(&self) -> &Pep723Metadata {
46        match self {
47            Self::Script(script) => &script.metadata,
48            Self::Stdin(metadata) => metadata,
49            Self::Remote(metadata, ..) => metadata,
50        }
51    }
52
53    /// Return the PEP 723 script, if any.
54    pub fn as_script(&self) -> Option<&Pep723Script> {
55        match self {
56            Self::Script(script) => Some(script),
57            _ => None,
58        }
59    }
60}
61
62/// A reference to a PEP 723 item.
63#[derive(Debug, Copy, Clone)]
64pub enum Pep723ItemRef<'item> {
65    /// A PEP 723 script read from disk.
66    Script(&'item Pep723Script),
67    /// A PEP 723 script provided via `stdin`.
68    Stdin(&'item Pep723Metadata),
69    /// A PEP 723 script provided via a remote URL.
70    Remote(&'item Pep723Metadata, &'item Url),
71}
72
73impl Pep723ItemRef<'_> {
74    /// Return the [`Pep723Metadata`] associated with the item.
75    pub fn metadata(&self) -> &Pep723Metadata {
76        match self {
77            Self::Script(script) => &script.metadata,
78            Self::Stdin(metadata) => metadata,
79            Self::Remote(metadata, ..) => metadata,
80        }
81    }
82
83    /// Return the path of the PEP 723 item, if any.
84    pub fn path(&self) -> Option<&Path> {
85        match self {
86            Self::Script(script) => Some(&script.path),
87            Self::Stdin(..) => None,
88            Self::Remote(..) => None,
89        }
90    }
91
92    /// Determine the working directory for the script.
93    pub fn directory(&self) -> Result<PathBuf, io::Error> {
94        match self {
95            Self::Script(script) => Ok(std::path::absolute(&script.path)?
96                .parent()
97                .expect("script path has no parent")
98                .to_owned()),
99            Self::Stdin(..) | Self::Remote(..) => std::env::current_dir(),
100        }
101    }
102
103    /// Collect any `tool.uv.index` from the script.
104    pub fn indexes(&self, source_strategy: &NoSources) -> &[uv_distribution_types::Index] {
105        match source_strategy {
106            NoSources::None | NoSources::Packages(_) => self
107                .metadata()
108                .tool
109                .as_ref()
110                .and_then(|tool| tool.uv.as_ref())
111                .and_then(|uv| uv.top_level.index.as_deref())
112                .unwrap_or(&[]),
113            NoSources::All => &[],
114        }
115    }
116
117    /// Collect any `tool.uv.sources` from the script.
118    pub fn sources(&self, source_strategy: &NoSources) -> Cow<'_, BTreeMap<PackageName, Sources>> {
119        static EMPTY: BTreeMap<PackageName, Sources> = BTreeMap::new();
120        let sources = self
121            .metadata()
122            .tool
123            .as_ref()
124            .and_then(|tool| tool.uv.as_ref())
125            .and_then(|uv| uv.sources.as_ref())
126            .unwrap_or(&EMPTY);
127
128        match source_strategy {
129            NoSources::None => Cow::Borrowed(sources),
130            NoSources::All => Cow::Borrowed(&EMPTY),
131            NoSources::Packages(packages) => Cow::Owned(
132                sources
133                    .iter()
134                    .filter(|(name, _)| !packages.contains(name))
135                    .map(|(name, sources)| (name.clone(), sources.clone()))
136                    .collect(),
137            ),
138        }
139    }
140}
141
142impl<'item> From<&'item Pep723Item> for Pep723ItemRef<'item> {
143    fn from(item: &'item Pep723Item) -> Self {
144        match item {
145            Pep723Item::Script(script) => Self::Script(script),
146            Pep723Item::Stdin(metadata) => Self::Stdin(metadata),
147            Pep723Item::Remote(metadata, url) => Self::Remote(metadata, url),
148        }
149    }
150}
151
152impl<'item> From<&'item Pep723Script> for Pep723ItemRef<'item> {
153    fn from(script: &'item Pep723Script) -> Self {
154        Self::Script(script)
155    }
156}
157
158/// A PEP 723 script, including its [`Pep723Metadata`].
159#[derive(Debug, Clone)]
160pub struct Pep723Script {
161    /// The path to the Python script.
162    pub path: PathBuf,
163    /// The parsed [`Pep723Metadata`] table from the script.
164    pub metadata: Pep723Metadata,
165    /// The content of the script before the metadata table.
166    pub prelude: String,
167    /// The content of the script after the metadata table.
168    pub postlude: String,
169}
170
171impl Pep723Script {
172    /// Read the PEP 723 `script` metadata from a Python file, if it exists.
173    ///
174    /// Returns `None` if the file is missing a PEP 723 metadata block.
175    ///
176    /// See: <https://peps.python.org/pep-0723/>
177    pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> {
178        let contents = fs_err::tokio::read(&file).await?;
179
180        // Extract the `script` tag.
181        let ScriptTag {
182            prelude,
183            metadata,
184            postlude,
185        } = match ScriptTag::parse(&contents) {
186            Ok(Some(tag)) => tag,
187            Ok(None) => return Ok(None),
188            Err(err) => return Err(err),
189        };
190
191        // Parse the metadata.
192        let metadata = Pep723Metadata::from_str(&metadata)?;
193
194        Ok(Some(Self {
195            path: std::path::absolute(file)?,
196            metadata,
197            prelude,
198            postlude,
199        }))
200    }
201
202    /// Reads a Python script and generates a default PEP 723 metadata table.
203    ///
204    /// See: <https://peps.python.org/pep-0723/>
205    pub async fn init(
206        file: impl AsRef<Path>,
207        requires_python: &VersionSpecifiers,
208    ) -> Result<Self, Pep723Error> {
209        let contents = fs_err::tokio::read(&file).await?;
210        let (prelude, metadata, postlude) = Self::init_metadata(&contents, requires_python)?;
211        Ok(Self {
212            path: std::path::absolute(file)?,
213            metadata,
214            prelude,
215            postlude,
216        })
217    }
218
219    /// Generates a default PEP 723 metadata table from the provided script contents.
220    ///
221    /// See: <https://peps.python.org/pep-0723/>
222    fn init_metadata(
223        contents: &[u8],
224        requires_python: &VersionSpecifiers,
225    ) -> Result<(String, Pep723Metadata, String), Pep723Error> {
226        // Define the default metadata.
227        let default_metadata = if requires_python.is_empty() {
228            indoc::formatdoc! {r"
229                dependencies = []
230            ",
231            }
232        } else {
233            indoc::formatdoc! {r#"
234                requires-python = "{requires_python}"
235                dependencies = []
236                "#,
237                requires_python = requires_python,
238            }
239        };
240        let metadata = Pep723Metadata::from_str(&default_metadata)?;
241
242        // Extract the shebang and script content.
243        let (shebang, postlude) = extract_shebang(contents)?;
244
245        // Add a newline to the beginning if it starts with a valid metadata comment line.
246        let postlude = if postlude.strip_prefix('#').is_some_and(|postlude| {
247            postlude
248                .chars()
249                .next()
250                .is_some_and(|c| matches!(c, ' ' | '\r' | '\n'))
251        }) {
252            format!("\n{postlude}")
253        } else {
254            postlude
255        };
256
257        Ok((
258            if shebang.is_empty() {
259                String::new()
260            } else {
261                format!("{shebang}\n")
262            },
263            metadata,
264            postlude,
265        ))
266    }
267
268    /// Create a PEP 723 script at the given path.
269    pub async fn create(
270        file: impl AsRef<Path>,
271        requires_python: &VersionSpecifiers,
272        existing_contents: Option<Vec<u8>>,
273        bare: bool,
274    ) -> Result<(), Pep723Error> {
275        let file = file.as_ref();
276
277        let script_name = file
278            .file_name()
279            .and_then(|name| name.to_str())
280            .ok_or_else(|| Pep723Error::InvalidFilename(file.to_string_lossy().to_string()))?;
281
282        let default_metadata = indoc::formatdoc! {r#"
283            requires-python = "{requires_python}"
284            dependencies = []
285            "#,
286        };
287        let metadata = serialize_metadata(&default_metadata);
288
289        let script = if let Some(existing_contents) = existing_contents {
290            let (mut shebang, contents) = extract_shebang(&existing_contents)?;
291            if !shebang.is_empty() {
292                shebang.push_str("\n#\n");
293                // If the shebang doesn't contain `uv`, it's probably something like
294                // `#! /usr/bin/env python`, which isn't going to respect the inline metadata.
295                // Issue a warning for users who might not know that.
296                // TODO: There are a lot of mistakes we could consider detecting here, like
297                // `uv run` without `--script` when the file doesn't end in `.py`.
298                if !regex::regex!(r"\buv\b").is_match(&shebang) {
299                    warn_user!(
300                        "If you execute {} directly, it might ignore its inline metadata.\nConsider replacing its shebang with: {}",
301                        file.to_string_lossy().cyan(),
302                        "#!/usr/bin/env -S uv run --script".cyan(),
303                    );
304                }
305            }
306            indoc::formatdoc! {r"
307            {shebang}{metadata}
308            {contents}" }
309        } else if bare {
310            metadata
311        } else {
312            indoc::formatdoc! {r#"
313            {metadata}
314
315            def main() -> None:
316                print("Hello from {name}!")
317
318
319            if __name__ == "__main__":
320                main()
321        "#,
322                metadata = metadata,
323                name = script_name,
324            }
325        };
326
327        Ok(fs_err::tokio::write(file, script).await?)
328    }
329
330    /// Replace the existing metadata in the file with new metadata and write the updated content.
331    pub fn write(&self, metadata: &str) -> Result<(), io::Error> {
332        let content = format!(
333            "{}{}{}",
334            self.prelude,
335            serialize_metadata(metadata),
336            self.postlude
337        );
338
339        fs_err::write(&self.path, content)?;
340
341        Ok(())
342    }
343
344    /// Return the [`Sources`] defined in the PEP 723 metadata.
345    pub fn sources(&self) -> &BTreeMap<PackageName, Sources> {
346        static EMPTY: BTreeMap<PackageName, Sources> = BTreeMap::new();
347
348        self.metadata
349            .tool
350            .as_ref()
351            .and_then(|tool| tool.uv.as_ref())
352            .and_then(|uv| uv.sources.as_ref())
353            .unwrap_or(&EMPTY)
354    }
355}
356
357/// PEP 723 metadata as parsed from a `script` comment block.
358///
359/// See: <https://peps.python.org/pep-0723/>
360#[derive(Debug, Deserialize, Clone)]
361#[serde(rename_all = "kebab-case")]
362pub struct Pep723Metadata {
363    pub dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
364    pub requires_python: Option<VersionSpecifiers>,
365    pub tool: Option<Tool>,
366    /// The raw unserialized document.
367    #[serde(skip)]
368    pub raw: String,
369}
370
371impl Pep723Metadata {
372    /// Parse the PEP 723 metadata from `stdin`.
373    pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> {
374        // Extract the `script` tag.
375        let ScriptTag { metadata, .. } = match ScriptTag::parse(contents) {
376            Ok(Some(tag)) => tag,
377            Ok(None) => return Ok(None),
378            Err(err) => return Err(err),
379        };
380
381        // Parse the metadata.
382        Ok(Some(Self::from_str(&metadata)?))
383    }
384
385    /// Read the PEP 723 `script` metadata from a Python file, if it exists.
386    ///
387    /// Returns `None` if the file is missing a PEP 723 metadata block.
388    ///
389    /// See: <https://peps.python.org/pep-0723/>
390    pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> {
391        let contents = fs_err::tokio::read(&file).await?;
392
393        // Extract the `script` tag.
394        let ScriptTag { metadata, .. } = match ScriptTag::parse(&contents) {
395            Ok(Some(tag)) => tag,
396            Ok(None) => return Ok(None),
397            Err(err) => return Err(err),
398        };
399
400        // Parse the metadata.
401        Ok(Some(Self::from_str(&metadata)?))
402    }
403}
404
405impl FromStr for Pep723Metadata {
406    type Err = toml::de::Error;
407
408    /// Parse `Pep723Metadata` from a raw TOML string.
409    #[instrument(name = "toml::from_str PEP 723 metadata", skip_all)]
410    fn from_str(raw: &str) -> Result<Self, Self::Err> {
411        let metadata = toml::from_str(raw)?;
412        Ok(Self {
413            raw: raw.to_string(),
414            ..metadata
415        })
416    }
417}
418
419#[derive(Deserialize, Debug, Clone)]
420#[serde(rename_all = "kebab-case")]
421pub struct Tool {
422    pub uv: Option<ToolUv>,
423}
424
425#[derive(Debug, Deserialize, Clone)]
426#[serde(deny_unknown_fields, rename_all = "kebab-case")]
427pub struct ToolUv {
428    #[serde(flatten)]
429    pub globals: GlobalOptions,
430    #[serde(flatten)]
431    pub top_level: ResolverInstallerSchema,
432    pub override_dependencies: Option<Vec<OverrideDependency>>,
433    pub exclude_dependencies: Option<Vec<ExcludeDependency>>,
434    pub constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
435    pub build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
436    pub extra_build_dependencies: Option<BTreeMap<PackageName, Vec<ExtraBuildDependency>>>,
437    pub sources: Option<BTreeMap<PackageName, Sources>>,
438}
439
440#[derive(Debug, Error)]
441pub enum Pep723Error {
442    #[error(
443        "An opening tag (`# /// script`) was found without a closing tag (`# ///`). Ensure that every line between the opening and closing tags (including empty lines) starts with a leading `#`."
444    )]
445    UnclosedBlock,
446    #[error(
447        "An opening tag (`# /// script`) was found, but the closing tag (`# ///`) has trailing content. Remove the trailing content so the line is exactly `# ///`."
448    )]
449    UnclosedBlockTrailingContent,
450    #[error("The script contains multiple PEP 723 metadata blocks")]
451    DuplicateBlock,
452    #[error("The PEP 723 metadata block is missing from the script.")]
453    MissingTag,
454    #[error(transparent)]
455    Io(#[from] io::Error),
456    #[error(transparent)]
457    Utf8(#[from] std::str::Utf8Error),
458    #[error(transparent)]
459    Toml(#[from] toml::de::Error),
460    #[error("Invalid filename `{0}` supplied")]
461    InvalidFilename(String),
462}
463
464#[derive(Debug, Clone, Eq, PartialEq)]
465pub struct ScriptTag {
466    /// The content of the script before the metadata block.
467    prelude: String,
468    /// The metadata block.
469    metadata: String,
470    /// The content of the script after the metadata block.
471    postlude: String,
472}
473
474impl ScriptTag {
475    /// Given the contents of a Python file, extract the `script` metadata block with leading
476    /// comment hashes removed, any preceding shebang or content (prelude), and the remaining Python
477    /// script.
478    ///
479    /// Given the following input string representing the contents of a Python script:
480    ///
481    /// ```python
482    /// #!/usr/bin/env python3
483    /// # /// script
484    /// # requires-python = '>=3.11'
485    /// # dependencies = [
486    /// #   'requests<3',
487    /// #   'rich',
488    /// # ]
489    /// # ///
490    ///
491    /// import requests
492    ///
493    /// print("Hello, World!")
494    /// ```
495    ///
496    /// This function would return:
497    ///
498    /// - Preamble: `#!/usr/bin/env python3\n`
499    /// - Metadata: `requires-python = '>=3.11'\ndependencies = [\n  'requests<3',\n  'rich',\n]`
500    /// - Postlude: `import requests\n\nprint("Hello, World!")\n`
501    ///
502    /// See: <https://peps.python.org/pep-0723/>
503    pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> {
504        // Identify the opening pragma.
505        let Some(index) = FINDER.find(contents) else {
506            return Ok(None);
507        };
508
509        // The opening pragma must be the first line, or immediately preceded by a newline.
510        if !(index == 0 || matches!(contents[index - 1], b'\r' | b'\n')) {
511            return Ok(None);
512        }
513
514        // Extract the preceding content.
515        let prelude = std::str::from_utf8(&contents[..index])?;
516
517        // Decode as UTF-8.
518        let contents = &contents[index..];
519        let contents = std::str::from_utf8(contents)?;
520
521        let mut lines = contents.lines();
522
523        // Ensure that the first line is exactly `# /// script`.
524        if lines.next().is_none_or(|line| line != "# /// script") {
525            return Ok(None);
526        }
527
528        // > Every line between these two lines (# /// TYPE and # ///) MUST be a comment starting
529        // > with #. If there are characters after the # then the first character MUST be a space. The
530        // > embedded content is formed by taking away the first two characters of each line if the
531        // > second character is a space, otherwise just the first character (which means the line
532        // > consists of only a single #).
533        let mut toml = vec![];
534
535        for line in lines {
536            // Remove the leading `#`.
537            let Some(line) = line.strip_prefix('#') else {
538                break;
539            };
540
541            // If the line is empty, continue.
542            if line.is_empty() {
543                toml.push("");
544                continue;
545            }
546
547            // Otherwise, the line _must_ start with ` `.
548            let Some(line) = line.strip_prefix(' ') else {
549                break;
550            };
551
552            toml.push(line);
553        }
554
555        // Find the closing `# ///`. The precedence is such that we need to identify the _last_ such
556        // line.
557        //
558        // For example, given:
559        // ```python
560        // # /// script
561        // #
562        // # ///
563        // #
564        // # ///
565        // ```
566        //
567        // The latter `///` is the closing pragma. Track malformed terminators while searching, but
568        // continue looking for an exact terminator so trailing comments cannot invalidate it.
569        let mut has_trailing_content = false;
570        let mut closing_index = None;
571
572        for (index, line) in toml.iter().enumerate().rev() {
573            if *line == "///" {
574                closing_index = Some(index + 1);
575                break;
576            }
577
578            if line.starts_with("///") {
579                has_trailing_content = true;
580            }
581        }
582
583        let Some(index) = closing_index else {
584            return Err(if has_trailing_content {
585                Pep723Error::UnclosedBlockTrailingContent
586            } else {
587                Pep723Error::UnclosedBlock
588            });
589        };
590
591        // Discard any lines after the closing `# ///`.
592        //
593        // For example, given:
594        // ```python
595        // # /// script
596        // #
597        // # ///
598        // #
599        // #
600        // ```
601        //
602        // We need to discard the last two lines.
603        toml.truncate(index - 1);
604
605        // Extract the remaining content.
606        let postlude = contents.lines().skip(index + 1).collect::<Vec<_>>();
607
608        // Ensure that the remaining content doesn't include another complete `script` block.
609        // A `# /// script` line can be embedded content inside another typed block.
610        let mut lines = postlude.iter().peekable();
611        while let Some(line) = lines.next() {
612            // Capture the metadata.
613            let Some(metadata_type) = line.strip_prefix("# /// ") else {
614                continue;
615            };
616
617            // Parse the metadata type per spec
618            if metadata_type.is_empty()
619                || !metadata_type
620                    .bytes()
621                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
622            {
623                continue;
624            }
625
626            let is_script_block = metadata_type == "script";
627            let mut is_closed = false;
628            while let Some(line) = lines.next() {
629                // Per e.g. # dependencies = []
630                let Some(content) = line.strip_prefix('#') else {
631                    break;
632                };
633                if !(content.is_empty() || content.starts_with(' ')) {
634                    break;
635                }
636
637                if *line == "# ///" {
638                    let Some(next_line) = lines.peek() else {
639                        is_closed = true;
640                        break;
641                    };
642
643                    let Some(next_content) = next_line.strip_prefix('#') else {
644                        is_closed = true;
645                        break;
646                    };
647
648                    if !(next_content.is_empty() || next_content.starts_with(' ')) {
649                        is_closed = true;
650                        break;
651                    }
652                }
653            }
654
655            if is_script_block && is_closed {
656                return Err(Pep723Error::DuplicateBlock);
657            }
658        }
659
660        // Join the lines into a single string.
661        let prelude = prelude.to_string();
662        let metadata = toml.join("\n") + "\n";
663        let postlude = postlude.join("\n") + "\n";
664
665        Ok(Some(Self {
666            prelude,
667            metadata,
668            postlude,
669        }))
670    }
671}
672
673/// Extracts the shebang line from the given file contents and returns it along with the remaining
674/// content.
675fn extract_shebang(contents: &[u8]) -> Result<(String, String), Pep723Error> {
676    let contents = std::str::from_utf8(contents)?;
677
678    if contents.starts_with("#!") {
679        // Find the first newline.
680        let bytes = contents.as_bytes();
681        let index = bytes
682            .iter()
683            .position(|&b| b == b'\r' || b == b'\n')
684            .unwrap_or(bytes.len());
685
686        // Support `\r`, `\n`, and `\r\n` line endings.
687        let width = match bytes.get(index) {
688            Some(b'\r') => {
689                if bytes.get(index + 1) == Some(&b'\n') {
690                    2
691                } else {
692                    1
693                }
694            }
695            Some(b'\n') => 1,
696            _ => 0,
697        };
698
699        // Extract the shebang line.
700        let shebang = contents[..index].to_string();
701        let script = contents[index + width..].to_string();
702
703        Ok((shebang, script))
704    } else {
705        Ok((String::new(), contents.to_string()))
706    }
707}
708
709/// Formats the provided metadata by prefixing each line with `#` and wrapping it with script markers.
710fn serialize_metadata(metadata: &str) -> String {
711    let mut output = String::with_capacity(metadata.len() + 32);
712
713    output.push_str("# /// script");
714    output.push('\n');
715
716    for line in metadata.lines() {
717        output.push('#');
718        if !line.is_empty() {
719            output.push(' ');
720            output.push_str(line);
721        }
722        output.push('\n');
723    }
724
725    output.push_str("# ///");
726    output.push('\n');
727
728    output
729}
730
731#[cfg(test)]
732mod tests {
733    use std::assert_matches;
734
735    use crate::{Pep723Error, Pep723Script, ScriptTag, serialize_metadata};
736    use std::str::FromStr;
737
738    #[test]
739    fn missing_space() {
740        let contents = indoc::indoc! {r"
741        # /// script
742        #requires-python = '>=3.11'
743        # ///
744    "};
745
746        assert_matches!(
747            ScriptTag::parse(contents.as_bytes()),
748            Err(Pep723Error::UnclosedBlock)
749        );
750    }
751
752    #[test]
753    fn no_closing_pragma() {
754        let contents = indoc::indoc! {r"
755        # /// script
756        # requires-python = '>=3.11'
757        # dependencies = [
758        #     'requests<3',
759        #     'rich',
760        # ]
761    "};
762
763        assert_matches!(
764            ScriptTag::parse(contents.as_bytes()),
765            Err(Pep723Error::UnclosedBlock)
766        );
767    }
768
769    #[test]
770    fn closing_tag_trailing_whitespace() {
771        // Explicit string (not `indoc`) so the closing tag's trailing space is preserved.
772        let contents = "# /// script\n# requires-python = '>=3.11'\n# /// \n";
773
774        assert_matches!(
775            ScriptTag::parse(contents.as_bytes()),
776            Err(Pep723Error::UnclosedBlockTrailingContent)
777        );
778    }
779
780    #[test]
781    fn closing_tag_trailing_content() {
782        let contents = indoc::indoc! {r"
783            # /// script
784            # requires-python = '>=3.11'
785            # /// unexpected
786        "};
787
788        assert_matches!(
789            ScriptTag::parse(contents.as_bytes()),
790            Err(Pep723Error::UnclosedBlockTrailingContent)
791        );
792    }
793
794    #[test]
795    fn closing_tag_followed_by_prefixed_comment() {
796        let contents = indoc::indoc! {r#"
797            # /// script
798            # dependencies = []
799            # ///
800            # /// documentation
801            print("Hello, world!")
802        "#};
803
804        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
805
806        assert_eq!(actual.metadata, "dependencies = []\n");
807        assert_eq!(
808            actual.postlude,
809            "# /// documentation\nprint(\"Hello, world!\")\n"
810        );
811    }
812
813    #[test]
814    fn closing_tag_followed_by_trailing_whitespace_comment() {
815        let contents =
816            "# /// script\n# dependencies = []\n# ///\n# /// \nprint(\"Hello, world!\")\n";
817
818        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
819
820        assert_eq!(actual.metadata, "dependencies = []\n");
821        assert_eq!(actual.postlude, "# /// \nprint(\"Hello, world!\")\n");
822    }
823
824    #[test]
825    fn leading_content() {
826        let contents = indoc::indoc! {r"
827        pass # /// script
828        # requires-python = '>=3.11'
829        # dependencies = [
830        #   'requests<3',
831        #   'rich',
832        # ]
833        # ///
834        #
835        #
836    "};
837
838        assert_eq!(ScriptTag::parse(contents.as_bytes()).unwrap(), None);
839    }
840
841    #[test]
842    fn simple() {
843        let contents = indoc::indoc! {r"
844        # /// script
845        # requires-python = '>=3.11'
846        # dependencies = [
847        #     'requests<3',
848        #     'rich',
849        # ]
850        # ///
851
852        import requests
853        from rich.pretty import pprint
854
855        resp = requests.get('https://peps.python.org/api/peps.json')
856        data = resp.json()
857    "};
858
859        let expected_metadata = indoc::indoc! {r"
860        requires-python = '>=3.11'
861        dependencies = [
862            'requests<3',
863            'rich',
864        ]
865    "};
866
867        let expected_data = indoc::indoc! {r"
868
869        import requests
870        from rich.pretty import pprint
871
872        resp = requests.get('https://peps.python.org/api/peps.json')
873        data = resp.json()
874    "};
875
876        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
877
878        assert_eq!(actual.prelude, String::new());
879        assert_eq!(actual.metadata, expected_metadata);
880        assert_eq!(actual.postlude, expected_data);
881    }
882
883    #[test]
884    fn simple_with_shebang() {
885        let contents = indoc::indoc! {r"
886        #!/usr/bin/env python3
887        # /// script
888        # requires-python = '>=3.11'
889        # dependencies = [
890        #     'requests<3',
891        #     'rich',
892        # ]
893        # ///
894
895        import requests
896        from rich.pretty import pprint
897
898        resp = requests.get('https://peps.python.org/api/peps.json')
899        data = resp.json()
900    "};
901
902        let expected_metadata = indoc::indoc! {r"
903        requires-python = '>=3.11'
904        dependencies = [
905            'requests<3',
906            'rich',
907        ]
908    "};
909
910        let expected_data = indoc::indoc! {r"
911
912        import requests
913        from rich.pretty import pprint
914
915        resp = requests.get('https://peps.python.org/api/peps.json')
916        data = resp.json()
917    "};
918
919        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
920
921        assert_eq!(actual.prelude, "#!/usr/bin/env python3\n".to_string());
922        assert_eq!(actual.metadata, expected_metadata);
923        assert_eq!(actual.postlude, expected_data);
924    }
925
926    #[test]
927    fn embedded_comment() {
928        let contents = indoc::indoc! {r"
929        # /// script
930        # embedded-csharp = '''
931        # /// <summary>
932        # /// text
933        # ///
934        # /// </summary>
935        # public class MyClass { }
936        # '''
937        # ///
938    "};
939
940        let expected = indoc::indoc! {r"
941        embedded-csharp = '''
942        /// <summary>
943        /// text
944        ///
945        /// </summary>
946        public class MyClass { }
947        '''
948    "};
949
950        let actual = ScriptTag::parse(contents.as_bytes())
951            .unwrap()
952            .unwrap()
953            .metadata;
954
955        assert_eq!(actual, expected);
956    }
957
958    #[test]
959    fn trailing_lines() {
960        let contents = indoc::indoc! {r"
961            # /// script
962            # requires-python = '>=3.11'
963            # dependencies = [
964            #     'requests<3',
965            #     'rich',
966            # ]
967            # ///
968            #
969            #
970        "};
971
972        let expected = indoc::indoc! {r"
973            requires-python = '>=3.11'
974            dependencies = [
975                'requests<3',
976                'rich',
977            ]
978        "};
979
980        let actual = ScriptTag::parse(contents.as_bytes())
981            .unwrap()
982            .unwrap()
983            .metadata;
984
985        assert_eq!(actual, expected);
986    }
987
988    #[test]
989    fn unclosed_second_script_block_is_not_duplicate() {
990        let contents = indoc::indoc! {r#"
991            # /// script
992            # dependencies = ["requests"]
993            # ///
994
995            print("Hello, world!")
996
997            # /// script
998        "#};
999
1000        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1001    }
1002
1003    #[test]
1004    fn adjacent_unclosed_second_script_block_is_not_duplicate() {
1005        let contents = indoc::indoc! {r#"
1006            # /// script
1007            # dependencies = []
1008            # ///
1009            # /// script
1010            print("Hello, world!")
1011        "#};
1012
1013        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
1014
1015        assert_eq!(actual.metadata, "dependencies = []\n");
1016        assert_eq!(actual.postlude, "# /// script\nprint(\"Hello, world!\")\n");
1017    }
1018
1019    #[test]
1020    fn other_script_block_is_ignored() {
1021        let contents = indoc::indoc! {r#"
1022            # /// script
1023            # dependencies = ["requests"]
1024            # ///
1025
1026
1027            # /// other
1028            # /// script
1029            # ///
1030
1031            print("Hello, world!")
1032        "#};
1033
1034        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1035    }
1036
1037    #[test]
1038    fn serialize_metadata_formatting() {
1039        let metadata = indoc::indoc! {r"
1040            requires-python = '>=3.11'
1041            dependencies = [
1042              'requests<3',
1043              'rich',
1044            ]
1045        "};
1046
1047        let expected_output = indoc::indoc! {r"
1048            # /// script
1049            # requires-python = '>=3.11'
1050            # dependencies = [
1051            #   'requests<3',
1052            #   'rich',
1053            # ]
1054            # ///
1055        "};
1056
1057        let result = serialize_metadata(metadata);
1058        assert_eq!(result, expected_output);
1059    }
1060
1061    #[test]
1062    fn serialize_metadata_empty() {
1063        let metadata = "";
1064        let expected_output = "# /// script\n# ///\n";
1065
1066        let result = serialize_metadata(metadata);
1067        assert_eq!(result, expected_output);
1068    }
1069
1070    #[test]
1071    fn script_init_empty() {
1072        let contents = "".as_bytes();
1073        let (prelude, metadata, postlude) =
1074            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1075                .unwrap();
1076        assert_eq!(prelude, "");
1077        assert_eq!(
1078            metadata.raw,
1079            indoc::indoc! {r"
1080            dependencies = []
1081            "}
1082        );
1083        assert_eq!(postlude, "");
1084    }
1085
1086    #[test]
1087    fn script_init_requires_python() {
1088        let contents = "".as_bytes();
1089        let (prelude, metadata, postlude) = Pep723Script::init_metadata(
1090            contents,
1091            &uv_pep440::VersionSpecifiers::from_str(">=3.8").unwrap(),
1092        )
1093        .unwrap();
1094        assert_eq!(prelude, "");
1095        assert_eq!(
1096            metadata.raw,
1097            indoc::indoc! {r#"
1098            requires-python = ">=3.8"
1099            dependencies = []
1100            "#}
1101        );
1102        assert_eq!(postlude, "");
1103    }
1104
1105    #[test]
1106    fn script_init_with_hashbang() {
1107        let contents = indoc::indoc! {r#"
1108        #!/usr/bin/env python3
1109
1110        print("Hello, world!")
1111        "#}
1112        .as_bytes();
1113        let (prelude, metadata, postlude) =
1114            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1115                .unwrap();
1116        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1117        assert_eq!(
1118            metadata.raw,
1119            indoc::indoc! {r"
1120            dependencies = []
1121            "}
1122        );
1123        assert_eq!(
1124            postlude,
1125            indoc::indoc! {r#"
1126
1127            print("Hello, world!")
1128            "#}
1129        );
1130    }
1131
1132    #[test]
1133    fn script_init_with_other_metadata() {
1134        let contents = indoc::indoc! {r#"
1135        # /// noscript
1136        # Hello,
1137        #
1138        # World!
1139        # ///
1140
1141        print("Hello, world!")
1142        "#}
1143        .as_bytes();
1144        let (prelude, metadata, postlude) =
1145            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1146                .unwrap();
1147        assert_eq!(prelude, "");
1148        assert_eq!(
1149            metadata.raw,
1150            indoc::indoc! {r"
1151            dependencies = []
1152            "}
1153        );
1154        // Note the extra line at the beginning.
1155        assert_eq!(
1156            postlude,
1157            indoc::indoc! {r#"
1158
1159            # /// noscript
1160            # Hello,
1161            #
1162            # World!
1163            # ///
1164
1165            print("Hello, world!")
1166            "#}
1167        );
1168    }
1169
1170    #[test]
1171    fn script_init_with_hashbang_and_other_metadata() {
1172        let contents = indoc::indoc! {r#"
1173        #!/usr/bin/env python3
1174        # /// noscript
1175        # Hello,
1176        #
1177        # World!
1178        # ///
1179
1180        print("Hello, world!")
1181        "#}
1182        .as_bytes();
1183        let (prelude, metadata, postlude) =
1184            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1185                .unwrap();
1186        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1187        assert_eq!(
1188            metadata.raw,
1189            indoc::indoc! {r"
1190            dependencies = []
1191            "}
1192        );
1193        // Note the extra line at the beginning.
1194        assert_eq!(
1195            postlude,
1196            indoc::indoc! {r#"
1197
1198            # /// noscript
1199            # Hello,
1200            #
1201            # World!
1202            # ///
1203
1204            print("Hello, world!")
1205            "#}
1206        );
1207    }
1208
1209    #[test]
1210    fn script_init_with_valid_metadata_line() {
1211        let contents = indoc::indoc! {r#"
1212        # Hello,
1213        # /// noscript
1214        #
1215        # World!
1216        # ///
1217
1218        print("Hello, world!")
1219        "#}
1220        .as_bytes();
1221        let (prelude, metadata, postlude) =
1222            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1223                .unwrap();
1224        assert_eq!(prelude, "");
1225        assert_eq!(
1226            metadata.raw,
1227            indoc::indoc! {r"
1228            dependencies = []
1229            "}
1230        );
1231        // Note the extra line at the beginning.
1232        assert_eq!(
1233            postlude,
1234            indoc::indoc! {r#"
1235
1236            # Hello,
1237            # /// noscript
1238            #
1239            # World!
1240            # ///
1241
1242            print("Hello, world!")
1243            "#}
1244        );
1245    }
1246
1247    #[test]
1248    fn script_init_with_valid_empty_metadata_line() {
1249        let contents = indoc::indoc! {r#"
1250        #
1251        # /// noscript
1252        # Hello,
1253        # World!
1254        # ///
1255
1256        print("Hello, world!")
1257        "#}
1258        .as_bytes();
1259        let (prelude, metadata, postlude) =
1260            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1261                .unwrap();
1262        assert_eq!(prelude, "");
1263        assert_eq!(
1264            metadata.raw,
1265            indoc::indoc! {r"
1266            dependencies = []
1267            "}
1268        );
1269        // Note the extra line at the beginning.
1270        assert_eq!(
1271            postlude,
1272            indoc::indoc! {r#"
1273
1274            #
1275            # /// noscript
1276            # Hello,
1277            # World!
1278            # ///
1279
1280            print("Hello, world!")
1281            "#}
1282        );
1283    }
1284
1285    #[test]
1286    fn script_init_with_non_metadata_comment() {
1287        let contents = indoc::indoc! {r#"
1288        #Hello,
1289        # /// noscript
1290        #
1291        # World!
1292        # ///
1293
1294        print("Hello, world!")
1295        "#}
1296        .as_bytes();
1297        let (prelude, metadata, postlude) =
1298            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1299                .unwrap();
1300        assert_eq!(prelude, "");
1301        assert_eq!(
1302            metadata.raw,
1303            indoc::indoc! {r"
1304            dependencies = []
1305            "}
1306        );
1307        assert_eq!(
1308            postlude,
1309            indoc::indoc! {r#"
1310            #Hello,
1311            # /// noscript
1312            #
1313            # World!
1314            # ///
1315
1316            print("Hello, world!")
1317            "#}
1318        );
1319    }
1320}