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;
12
13use uv_configuration::NoSources;
14use uv_normalize::PackageName;
15use uv_pep440::VersionSpecifiers;
16use uv_pypi_types::VerbatimParsedUrl;
17use uv_redacted::SafeUrl;
18use uv_settings::{GlobalOptions, ResolverInstallerSchema};
19use uv_warnings::warn_user;
20use uv_workspace::pyproject::{BuildConstraintDependency, ExtraBuildDependency, Sources};
21
22mod discovery;
23
24pub use discovery::{ScriptDiscoveryError, find_scripts};
25
26pub use uv_configuration::ExcludeDependency;
27pub use uv_workspace::pyproject::OverrideDependency;
28
29static FINDER: LazyLock<Finder> = LazyLock::new(|| Finder::new(b"# /// script"));
30
31/// A PEP 723 item, either read from a script on disk or provided via `stdin`.
32#[derive(Debug)]
33pub enum Pep723Item {
34    /// A PEP 723 script read from disk.
35    Script(Pep723Script),
36    /// A PEP 723 script provided via `stdin`.
37    Stdin(Pep723Metadata),
38    /// A PEP 723 script provided via a remote URL.
39    Remote(Pep723Metadata, SafeUrl),
40}
41
42impl Pep723Item {
43    /// Return the [`Pep723Metadata`] associated with the item.
44    pub fn metadata(&self) -> &Pep723Metadata {
45        match self {
46            Self::Script(script) => &script.metadata,
47            Self::Stdin(metadata) => metadata,
48            Self::Remote(metadata, ..) => metadata,
49        }
50    }
51
52    /// Return the PEP 723 script, if any.
53    pub fn as_script(&self) -> Option<&Pep723Script> {
54        match self {
55            Self::Script(script) => Some(script),
56            _ => None,
57        }
58    }
59}
60
61/// A reference to a PEP 723 item.
62#[derive(Debug, Copy, Clone)]
63pub enum Pep723ItemRef<'item> {
64    /// A PEP 723 script read from disk.
65    Script(&'item Pep723Script),
66    /// A PEP 723 script provided via `stdin`.
67    Stdin(&'item Pep723Metadata),
68    /// A PEP 723 script provided via a remote URL.
69    Remote(&'item Pep723Metadata, &'item SafeUrl),
70}
71
72impl Pep723ItemRef<'_> {
73    /// Return the [`Pep723Metadata`] associated with the item.
74    pub fn metadata(&self) -> &Pep723Metadata {
75        match self {
76            Self::Script(script) => &script.metadata,
77            Self::Stdin(metadata) => metadata,
78            Self::Remote(metadata, ..) => metadata,
79        }
80    }
81
82    /// Return the path of the PEP 723 item, if any.
83    pub fn path(&self) -> Option<&Path> {
84        match self {
85            Self::Script(script) => Some(&script.path),
86            Self::Stdin(..) => None,
87            Self::Remote(..) => None,
88        }
89    }
90
91    /// Determine the working directory for the script.
92    pub fn directory(&self) -> Result<PathBuf, io::Error> {
93        match self {
94            Self::Script(script) => Ok(std::path::absolute(&script.path)?
95                .parent()
96                .expect("script path has no parent")
97                .to_owned()),
98            Self::Stdin(..) | Self::Remote(..) => std::env::current_dir(),
99        }
100    }
101
102    /// Collect any `tool.uv.index` from the script.
103    pub fn indexes(&self, source_strategy: &NoSources) -> &[uv_distribution_types::Index] {
104        match source_strategy {
105            NoSources::None | NoSources::Packages(_) => self
106                .metadata()
107                .tool
108                .as_ref()
109                .and_then(|tool| tool.uv.as_ref())
110                .and_then(|uv| uv.top_level.index.as_deref())
111                .unwrap_or(&[]),
112            NoSources::All => &[],
113        }
114    }
115
116    /// Collect any `tool.uv.sources` from the script.
117    pub fn sources(&self, source_strategy: &NoSources) -> Cow<'_, BTreeMap<PackageName, Sources>> {
118        static EMPTY: BTreeMap<PackageName, Sources> = BTreeMap::new();
119        let sources = self
120            .metadata()
121            .tool
122            .as_ref()
123            .and_then(|tool| tool.uv.as_ref())
124            .and_then(|uv| uv.sources.as_ref())
125            .unwrap_or(&EMPTY);
126
127        match source_strategy {
128            NoSources::None => Cow::Borrowed(sources),
129            NoSources::All => Cow::Borrowed(&EMPTY),
130            NoSources::Packages(packages) => Cow::Owned(
131                sources
132                    .iter()
133                    .filter(|(name, _)| !packages.contains(name))
134                    .map(|(name, sources)| (name.clone(), sources.clone()))
135                    .collect(),
136            ),
137        }
138    }
139}
140
141impl<'item> From<&'item Pep723Item> for Pep723ItemRef<'item> {
142    fn from(item: &'item Pep723Item) -> Self {
143        match item {
144            Pep723Item::Script(script) => Self::Script(script),
145            Pep723Item::Stdin(metadata) => Self::Stdin(metadata),
146            Pep723Item::Remote(metadata, url) => Self::Remote(metadata, url),
147        }
148    }
149}
150
151impl<'item> From<&'item Pep723Script> for Pep723ItemRef<'item> {
152    fn from(script: &'item Pep723Script) -> Self {
153        Self::Script(script)
154    }
155}
156
157/// A PEP 723 script, including its [`Pep723Metadata`].
158#[derive(Debug, Clone)]
159pub struct Pep723Script {
160    /// The path to the Python script.
161    pub path: PathBuf,
162    /// The parsed [`Pep723Metadata`] table from the script.
163    pub metadata: Pep723Metadata,
164    /// The content of the script before the metadata table.
165    pub prelude: String,
166    /// The content of the script after the metadata table.
167    pub postlude: String,
168}
169
170impl Pep723Script {
171    /// Read the PEP 723 `script` metadata from a Python file, if it exists.
172    ///
173    /// Returns `None` if the file is missing a PEP 723 metadata block.
174    ///
175    /// See: <https://peps.python.org/pep-0723/>
176    pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> {
177        let contents = fs_err::tokio::read(&file).await?;
178
179        // Extract the `script` tag.
180        let ScriptTag {
181            prelude,
182            metadata,
183            postlude,
184        } = match ScriptTag::parse(&contents) {
185            Ok(Some(tag)) => tag,
186            Ok(None) => return Ok(None),
187            Err(err) => return Err(err),
188        };
189
190        // Parse the metadata.
191        let metadata = Pep723Metadata::from_str(&metadata)?;
192
193        Ok(Some(Self {
194            path: std::path::absolute(file)?,
195            metadata,
196            prelude,
197            postlude,
198        }))
199    }
200
201    /// Reads a Python script and generates a default PEP 723 metadata table.
202    ///
203    /// See: <https://peps.python.org/pep-0723/>
204    pub async fn init(
205        file: impl AsRef<Path>,
206        requires_python: &VersionSpecifiers,
207    ) -> Result<Self, Pep723Error> {
208        let contents = fs_err::tokio::read(&file).await?;
209        let (prelude, metadata, postlude) = Self::init_metadata(&contents, requires_python)?;
210        Ok(Self {
211            path: std::path::absolute(file)?,
212            metadata,
213            prelude,
214            postlude,
215        })
216    }
217
218    /// Generates a default PEP 723 metadata table from the provided script contents.
219    ///
220    /// See: <https://peps.python.org/pep-0723/>
221    fn init_metadata(
222        contents: &[u8],
223        requires_python: &VersionSpecifiers,
224    ) -> Result<(String, Pep723Metadata, String), Pep723Error> {
225        // Define the default metadata.
226        let default_metadata = if requires_python.is_empty() {
227            indoc::formatdoc! {r"
228                dependencies = []
229            ",
230            }
231        } else {
232            indoc::formatdoc! {r#"
233                requires-python = "{requires_python}"
234                dependencies = []
235                "#,
236                requires_python = requires_python,
237            }
238        };
239        let metadata = Pep723Metadata::from_str(&default_metadata)?;
240
241        // Extract the shebang and script content.
242        let (shebang, postlude) = extract_shebang(contents)?;
243
244        // Add a newline to the beginning if it starts with a valid metadata comment line.
245        let postlude = if postlude.strip_prefix('#').is_some_and(|postlude| {
246            postlude
247                .chars()
248                .next()
249                .is_some_and(|c| matches!(c, ' ' | '\r' | '\n'))
250        }) {
251            format!("\n{postlude}")
252        } else {
253            postlude
254        };
255
256        Ok((
257            if shebang.is_empty() {
258                String::new()
259            } else {
260                format!("{shebang}\n")
261            },
262            metadata,
263            postlude,
264        ))
265    }
266
267    /// Create a PEP 723 script at the given path.
268    pub async fn create(
269        file: impl AsRef<Path>,
270        requires_python: &VersionSpecifiers,
271        existing_contents: Option<Vec<u8>>,
272        bare: bool,
273    ) -> Result<(), Pep723Error> {
274        let file = file.as_ref();
275
276        let script_name = file
277            .file_name()
278            .and_then(|name| name.to_str())
279            .ok_or_else(|| Pep723Error::InvalidFilename(file.to_string_lossy().to_string()))?;
280
281        let default_metadata = indoc::formatdoc! {r#"
282            requires-python = "{requires_python}"
283            dependencies = []
284            "#,
285        };
286        let metadata = serialize_metadata(&default_metadata);
287
288        let script = if let Some(existing_contents) = existing_contents {
289            let (mut shebang, contents) = extract_shebang(&existing_contents)?;
290            if !shebang.is_empty() {
291                shebang.push_str("\n#\n");
292                // If the shebang doesn't contain `uv`, it's probably something like
293                // `#! /usr/bin/env python`, which isn't going to respect the inline metadata.
294                // Issue a warning for users who might not know that.
295                // TODO: There are a lot of mistakes we could consider detecting here, like
296                // `uv run` without `--script` when the file doesn't end in `.py`.
297                if !regex::regex!(r"\buv\b").is_match(&shebang) {
298                    warn_user!(
299                        "If you execute {} directly, it might ignore its inline metadata.\nConsider replacing its shebang with: {}",
300                        file.to_string_lossy().cyan(),
301                        "#!/usr/bin/env -S uv run --script".cyan(),
302                    );
303                }
304            }
305            indoc::formatdoc! {r"
306            {shebang}{metadata}
307            {contents}" }
308        } else if bare {
309            metadata
310        } else {
311            indoc::formatdoc! {r#"
312            {metadata}
313
314            def main() -> None:
315                print("Hello from {name}!")
316
317
318            if __name__ == "__main__":
319                main()
320        "#,
321                metadata = metadata,
322                name = script_name,
323            }
324        };
325
326        Ok(fs_err::tokio::write(file, script).await?)
327    }
328
329    /// Replace the existing metadata in the file with new metadata and write the updated content.
330    pub fn write(&self, metadata: &str) -> Result<(), io::Error> {
331        let content = format!(
332            "{}{}{}",
333            self.prelude,
334            serialize_metadata(metadata),
335            self.postlude
336        );
337
338        fs_err::write(&self.path, content)?;
339
340        Ok(())
341    }
342
343    /// Return the [`Sources`] defined in the PEP 723 metadata.
344    pub fn sources(&self) -> &BTreeMap<PackageName, Sources> {
345        static EMPTY: BTreeMap<PackageName, Sources> = BTreeMap::new();
346
347        self.metadata
348            .tool
349            .as_ref()
350            .and_then(|tool| tool.uv.as_ref())
351            .and_then(|uv| uv.sources.as_ref())
352            .unwrap_or(&EMPTY)
353    }
354}
355
356/// PEP 723 metadata as parsed from a `script` comment block.
357///
358/// See: <https://peps.python.org/pep-0723/>
359#[derive(Debug, Deserialize, Clone)]
360#[serde(rename_all = "kebab-case")]
361pub struct Pep723Metadata {
362    #[serde(default)]
363    pub dependencies: 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    use std::str::FromStr;
735
736    use indoc::indoc;
737
738    use crate::{Pep723Error, Pep723Script, ScriptTag, serialize_metadata};
739
740    #[test]
741    fn missing_space() {
742        let contents = indoc::indoc! {r"
743        # /// script
744        #requires-python = '>=3.11'
745        # ///
746    "};
747
748        assert_matches!(
749            ScriptTag::parse(contents.as_bytes()),
750            Err(Pep723Error::UnclosedBlock)
751        );
752    }
753
754    #[test]
755    fn no_closing_pragma() {
756        let contents = indoc::indoc! {r"
757        # /// script
758        # requires-python = '>=3.11'
759        # dependencies = [
760        #     'requests<3',
761        #     'rich',
762        # ]
763    "};
764
765        assert_matches!(
766            ScriptTag::parse(contents.as_bytes()),
767            Err(Pep723Error::UnclosedBlock)
768        );
769    }
770
771    #[test]
772    fn closing_tag_trailing_whitespace() {
773        let contents = indoc! {"
774            # /// script
775            # requires-python = '>=3.11'
776            # ///\x20
777        "};
778
779        assert_matches!(
780            ScriptTag::parse(contents.as_bytes()),
781            Err(Pep723Error::UnclosedBlockTrailingContent)
782        );
783    }
784
785    #[test]
786    fn closing_tag_trailing_content() {
787        let contents = indoc::indoc! {r"
788            # /// script
789            # requires-python = '>=3.11'
790            # /// unexpected
791        "};
792
793        assert_matches!(
794            ScriptTag::parse(contents.as_bytes()),
795            Err(Pep723Error::UnclosedBlockTrailingContent)
796        );
797    }
798
799    #[test]
800    fn closing_tag_followed_by_prefixed_comment() {
801        let contents = indoc::indoc! {r#"
802            # /// script
803            # dependencies = []
804            # ///
805            # /// documentation
806            print("Hello, world!")
807        "#};
808
809        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
810
811        assert_eq!(actual.metadata, "dependencies = []\n");
812        assert_eq!(
813            actual.postlude,
814            indoc! {r#"
815                # /// documentation
816                print("Hello, world!")
817            "#}
818        );
819    }
820
821    #[test]
822    fn closing_tag_followed_by_trailing_whitespace_comment() {
823        let contents = indoc! {"
824            # /// script
825            # dependencies = []
826            # ///
827            # ///\x20
828            print(\"Hello, world!\")
829        "};
830
831        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
832
833        assert_eq!(actual.metadata, "dependencies = []\n");
834        assert_eq!(
835            actual.postlude,
836            indoc! {"
837                # ///\x20
838                print(\"Hello, world!\")
839            "}
840        );
841    }
842
843    #[test]
844    fn leading_content() {
845        let contents = indoc::indoc! {r"
846        pass # /// script
847        # requires-python = '>=3.11'
848        # dependencies = [
849        #   'requests<3',
850        #   'rich',
851        # ]
852        # ///
853        #
854        #
855    "};
856
857        assert_eq!(ScriptTag::parse(contents.as_bytes()).unwrap(), None);
858    }
859
860    #[test]
861    fn simple() {
862        let contents = indoc::indoc! {r"
863        # /// script
864        # requires-python = '>=3.11'
865        # dependencies = [
866        #     'requests<3',
867        #     'rich',
868        # ]
869        # ///
870
871        import requests
872        from rich.pretty import pprint
873
874        resp = requests.get('https://peps.python.org/api/peps.json')
875        data = resp.json()
876    "};
877
878        let expected_metadata = indoc::indoc! {r"
879        requires-python = '>=3.11'
880        dependencies = [
881            'requests<3',
882            'rich',
883        ]
884    "};
885
886        let expected_data = indoc::indoc! {r"
887
888        import requests
889        from rich.pretty import pprint
890
891        resp = requests.get('https://peps.python.org/api/peps.json')
892        data = resp.json()
893    "};
894
895        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
896
897        assert_eq!(actual.prelude, String::new());
898        assert_eq!(actual.metadata, expected_metadata);
899        assert_eq!(actual.postlude, expected_data);
900    }
901
902    #[test]
903    fn simple_with_shebang() {
904        let contents = indoc::indoc! {r"
905        #!/usr/bin/env python3
906        # /// script
907        # requires-python = '>=3.11'
908        # dependencies = [
909        #     'requests<3',
910        #     'rich',
911        # ]
912        # ///
913
914        import requests
915        from rich.pretty import pprint
916
917        resp = requests.get('https://peps.python.org/api/peps.json')
918        data = resp.json()
919    "};
920
921        let expected_metadata = indoc::indoc! {r"
922        requires-python = '>=3.11'
923        dependencies = [
924            'requests<3',
925            'rich',
926        ]
927    "};
928
929        let expected_data = indoc::indoc! {r"
930
931        import requests
932        from rich.pretty import pprint
933
934        resp = requests.get('https://peps.python.org/api/peps.json')
935        data = resp.json()
936    "};
937
938        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
939
940        assert_eq!(actual.prelude, "#!/usr/bin/env python3\n".to_string());
941        assert_eq!(actual.metadata, expected_metadata);
942        assert_eq!(actual.postlude, expected_data);
943    }
944
945    #[test]
946    fn embedded_comment() {
947        let contents = indoc::indoc! {r"
948        # /// script
949        # embedded-csharp = '''
950        # /// <summary>
951        # /// text
952        # ///
953        # /// </summary>
954        # public class MyClass { }
955        # '''
956        # ///
957    "};
958
959        let expected = indoc::indoc! {r"
960        embedded-csharp = '''
961        /// <summary>
962        /// text
963        ///
964        /// </summary>
965        public class MyClass { }
966        '''
967    "};
968
969        let actual = ScriptTag::parse(contents.as_bytes())
970            .unwrap()
971            .unwrap()
972            .metadata;
973
974        assert_eq!(actual, expected);
975    }
976
977    #[test]
978    fn trailing_lines() {
979        let contents = indoc::indoc! {r"
980            # /// script
981            # requires-python = '>=3.11'
982            # dependencies = [
983            #     'requests<3',
984            #     'rich',
985            # ]
986            # ///
987            #
988            #
989        "};
990
991        let expected = indoc::indoc! {r"
992            requires-python = '>=3.11'
993            dependencies = [
994                'requests<3',
995                'rich',
996            ]
997        "};
998
999        let actual = ScriptTag::parse(contents.as_bytes())
1000            .unwrap()
1001            .unwrap()
1002            .metadata;
1003
1004        assert_eq!(actual, expected);
1005    }
1006
1007    #[test]
1008    fn unclosed_second_script_block_is_not_duplicate() {
1009        let contents = indoc::indoc! {r#"
1010            # /// script
1011            # dependencies = ["requests"]
1012            # ///
1013
1014            print("Hello, world!")
1015
1016            # /// script
1017        "#};
1018
1019        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1020    }
1021
1022    #[test]
1023    fn adjacent_unclosed_second_script_block_is_not_duplicate() {
1024        let contents = indoc::indoc! {r#"
1025            # /// script
1026            # dependencies = []
1027            # ///
1028            # /// script
1029            print("Hello, world!")
1030        "#};
1031
1032        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
1033
1034        assert_eq!(actual.metadata, "dependencies = []\n");
1035        assert_eq!(
1036            actual.postlude,
1037            indoc! {r#"
1038                # /// script
1039                print("Hello, world!")
1040            "#}
1041        );
1042    }
1043
1044    #[test]
1045    fn other_script_block_is_ignored() {
1046        let contents = indoc::indoc! {r#"
1047            # /// script
1048            # dependencies = ["requests"]
1049            # ///
1050
1051
1052            # /// other
1053            # /// script
1054            # ///
1055
1056            print("Hello, world!")
1057        "#};
1058
1059        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1060    }
1061
1062    #[test]
1063    fn serialize_metadata_formatting() {
1064        let metadata = indoc::indoc! {r"
1065            requires-python = '>=3.11'
1066            dependencies = [
1067              'requests<3',
1068              'rich',
1069            ]
1070        "};
1071
1072        let expected_output = indoc::indoc! {r"
1073            # /// script
1074            # requires-python = '>=3.11'
1075            # dependencies = [
1076            #   'requests<3',
1077            #   'rich',
1078            # ]
1079            # ///
1080        "};
1081
1082        let result = serialize_metadata(metadata);
1083        assert_eq!(result, expected_output);
1084    }
1085
1086    #[test]
1087    fn serialize_metadata_empty() {
1088        let metadata = "";
1089        let expected_output = indoc! {"
1090            # /// script
1091            # ///
1092        "};
1093
1094        let result = serialize_metadata(metadata);
1095        assert_eq!(result, expected_output);
1096    }
1097
1098    #[test]
1099    fn script_init_empty() {
1100        let contents = "".as_bytes();
1101        let (prelude, metadata, postlude) =
1102            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1103                .unwrap();
1104        assert_eq!(prelude, "");
1105        assert_eq!(
1106            metadata.raw,
1107            indoc::indoc! {r"
1108            dependencies = []
1109            "}
1110        );
1111        assert_eq!(postlude, "");
1112    }
1113
1114    #[test]
1115    fn script_init_requires_python() {
1116        let contents = "".as_bytes();
1117        let (prelude, metadata, postlude) = Pep723Script::init_metadata(
1118            contents,
1119            &uv_pep440::VersionSpecifiers::from_str(">=3.8").unwrap(),
1120        )
1121        .unwrap();
1122        assert_eq!(prelude, "");
1123        assert_eq!(
1124            metadata.raw,
1125            indoc::indoc! {r#"
1126            requires-python = ">=3.8"
1127            dependencies = []
1128            "#}
1129        );
1130        assert_eq!(postlude, "");
1131    }
1132
1133    #[test]
1134    fn script_init_with_hashbang() {
1135        let contents = indoc::indoc! {r#"
1136        #!/usr/bin/env python3
1137
1138        print("Hello, world!")
1139        "#}
1140        .as_bytes();
1141        let (prelude, metadata, postlude) =
1142            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1143                .unwrap();
1144        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1145        assert_eq!(
1146            metadata.raw,
1147            indoc::indoc! {r"
1148            dependencies = []
1149            "}
1150        );
1151        assert_eq!(
1152            postlude,
1153            indoc::indoc! {r#"
1154
1155            print("Hello, world!")
1156            "#}
1157        );
1158    }
1159
1160    #[test]
1161    fn script_init_with_other_metadata() {
1162        let contents = indoc::indoc! {r#"
1163        # /// noscript
1164        # Hello,
1165        #
1166        # World!
1167        # ///
1168
1169        print("Hello, world!")
1170        "#}
1171        .as_bytes();
1172        let (prelude, metadata, postlude) =
1173            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1174                .unwrap();
1175        assert_eq!(prelude, "");
1176        assert_eq!(
1177            metadata.raw,
1178            indoc::indoc! {r"
1179            dependencies = []
1180            "}
1181        );
1182        // Note the extra line at the beginning.
1183        assert_eq!(
1184            postlude,
1185            indoc::indoc! {r#"
1186
1187            # /// noscript
1188            # Hello,
1189            #
1190            # World!
1191            # ///
1192
1193            print("Hello, world!")
1194            "#}
1195        );
1196    }
1197
1198    #[test]
1199    fn script_init_with_hashbang_and_other_metadata() {
1200        let contents = indoc::indoc! {r#"
1201        #!/usr/bin/env python3
1202        # /// noscript
1203        # Hello,
1204        #
1205        # World!
1206        # ///
1207
1208        print("Hello, world!")
1209        "#}
1210        .as_bytes();
1211        let (prelude, metadata, postlude) =
1212            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1213                .unwrap();
1214        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1215        assert_eq!(
1216            metadata.raw,
1217            indoc::indoc! {r"
1218            dependencies = []
1219            "}
1220        );
1221        // Note the extra line at the beginning.
1222        assert_eq!(
1223            postlude,
1224            indoc::indoc! {r#"
1225
1226            # /// noscript
1227            # Hello,
1228            #
1229            # World!
1230            # ///
1231
1232            print("Hello, world!")
1233            "#}
1234        );
1235    }
1236
1237    #[test]
1238    fn script_init_with_valid_metadata_line() {
1239        let contents = indoc::indoc! {r#"
1240        # Hello,
1241        # /// noscript
1242        #
1243        # World!
1244        # ///
1245
1246        print("Hello, world!")
1247        "#}
1248        .as_bytes();
1249        let (prelude, metadata, postlude) =
1250            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1251                .unwrap();
1252        assert_eq!(prelude, "");
1253        assert_eq!(
1254            metadata.raw,
1255            indoc::indoc! {r"
1256            dependencies = []
1257            "}
1258        );
1259        // Note the extra line at the beginning.
1260        assert_eq!(
1261            postlude,
1262            indoc::indoc! {r#"
1263
1264            # Hello,
1265            # /// noscript
1266            #
1267            # World!
1268            # ///
1269
1270            print("Hello, world!")
1271            "#}
1272        );
1273    }
1274
1275    #[test]
1276    fn script_init_with_valid_empty_metadata_line() {
1277        let contents = indoc::indoc! {r#"
1278        #
1279        # /// noscript
1280        # Hello,
1281        # World!
1282        # ///
1283
1284        print("Hello, world!")
1285        "#}
1286        .as_bytes();
1287        let (prelude, metadata, postlude) =
1288            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1289                .unwrap();
1290        assert_eq!(prelude, "");
1291        assert_eq!(
1292            metadata.raw,
1293            indoc::indoc! {r"
1294            dependencies = []
1295            "}
1296        );
1297        // Note the extra line at the beginning.
1298        assert_eq!(
1299            postlude,
1300            indoc::indoc! {r#"
1301
1302            #
1303            # /// noscript
1304            # Hello,
1305            # World!
1306            # ///
1307
1308            print("Hello, world!")
1309            "#}
1310        );
1311    }
1312
1313    #[test]
1314    fn script_init_with_non_metadata_comment() {
1315        let contents = indoc::indoc! {r#"
1316        #Hello,
1317        # /// noscript
1318        #
1319        # World!
1320        # ///
1321
1322        print("Hello, world!")
1323        "#}
1324        .as_bytes();
1325        let (prelude, metadata, postlude) =
1326            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1327                .unwrap();
1328        assert_eq!(prelude, "");
1329        assert_eq!(
1330            metadata.raw,
1331            indoc::indoc! {r"
1332            dependencies = []
1333            "}
1334        );
1335        assert_eq!(
1336            postlude,
1337            indoc::indoc! {r#"
1338            #Hello,
1339            # /// noscript
1340            #
1341            # World!
1342            # ///
1343
1344            print("Hello, world!")
1345            "#}
1346        );
1347    }
1348}