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    pub dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
363    pub requires_python: Option<VersionSpecifiers>,
364    pub tool: Option<Tool>,
365    /// The raw unserialized document.
366    #[serde(skip)]
367    pub raw: String,
368}
369
370impl Pep723Metadata {
371    /// Parse the PEP 723 metadata from `stdin`.
372    pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> {
373        // Extract the `script` tag.
374        let ScriptTag { metadata, .. } = match ScriptTag::parse(contents) {
375            Ok(Some(tag)) => tag,
376            Ok(None) => return Ok(None),
377            Err(err) => return Err(err),
378        };
379
380        // Parse the metadata.
381        Ok(Some(Self::from_str(&metadata)?))
382    }
383
384    /// Read the PEP 723 `script` metadata from a Python file, if it exists.
385    ///
386    /// Returns `None` if the file is missing a PEP 723 metadata block.
387    ///
388    /// See: <https://peps.python.org/pep-0723/>
389    pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> {
390        let contents = fs_err::tokio::read(&file).await?;
391
392        // Extract the `script` tag.
393        let ScriptTag { metadata, .. } = match ScriptTag::parse(&contents) {
394            Ok(Some(tag)) => tag,
395            Ok(None) => return Ok(None),
396            Err(err) => return Err(err),
397        };
398
399        // Parse the metadata.
400        Ok(Some(Self::from_str(&metadata)?))
401    }
402}
403
404impl FromStr for Pep723Metadata {
405    type Err = toml::de::Error;
406
407    /// Parse `Pep723Metadata` from a raw TOML string.
408    #[instrument(name = "toml::from_str PEP 723 metadata", skip_all)]
409    fn from_str(raw: &str) -> Result<Self, Self::Err> {
410        let metadata = toml::from_str(raw)?;
411        Ok(Self {
412            raw: raw.to_string(),
413            ..metadata
414        })
415    }
416}
417
418#[derive(Deserialize, Debug, Clone)]
419#[serde(rename_all = "kebab-case")]
420pub struct Tool {
421    pub uv: Option<ToolUv>,
422}
423
424#[derive(Debug, Deserialize, Clone)]
425#[serde(deny_unknown_fields, rename_all = "kebab-case")]
426pub struct ToolUv {
427    #[serde(flatten)]
428    pub globals: GlobalOptions,
429    #[serde(flatten)]
430    pub top_level: ResolverInstallerSchema,
431    pub override_dependencies: Option<Vec<OverrideDependency>>,
432    pub exclude_dependencies: Option<Vec<ExcludeDependency>>,
433    pub constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
434    pub build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
435    pub extra_build_dependencies: Option<BTreeMap<PackageName, Vec<ExtraBuildDependency>>>,
436    pub sources: Option<BTreeMap<PackageName, Sources>>,
437}
438
439#[derive(Debug, Error)]
440pub enum Pep723Error {
441    #[error(
442        "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 `#`."
443    )]
444    UnclosedBlock,
445    #[error(
446        "An opening tag (`# /// script`) was found, but the closing tag (`# ///`) has trailing content. Remove the trailing content so the line is exactly `# ///`."
447    )]
448    UnclosedBlockTrailingContent,
449    #[error("The script contains multiple PEP 723 metadata blocks")]
450    DuplicateBlock,
451    #[error("The PEP 723 metadata block is missing from the script.")]
452    MissingTag,
453    #[error(transparent)]
454    Io(#[from] io::Error),
455    #[error(transparent)]
456    Utf8(#[from] std::str::Utf8Error),
457    #[error(transparent)]
458    Toml(#[from] toml::de::Error),
459    #[error("Invalid filename `{0}` supplied")]
460    InvalidFilename(String),
461}
462
463#[derive(Debug, Clone, Eq, PartialEq)]
464pub struct ScriptTag {
465    /// The content of the script before the metadata block.
466    prelude: String,
467    /// The metadata block.
468    metadata: String,
469    /// The content of the script after the metadata block.
470    postlude: String,
471}
472
473impl ScriptTag {
474    /// Given the contents of a Python file, extract the `script` metadata block with leading
475    /// comment hashes removed, any preceding shebang or content (prelude), and the remaining Python
476    /// script.
477    ///
478    /// Given the following input string representing the contents of a Python script:
479    ///
480    /// ```python
481    /// #!/usr/bin/env python3
482    /// # /// script
483    /// # requires-python = '>=3.11'
484    /// # dependencies = [
485    /// #   'requests<3',
486    /// #   'rich',
487    /// # ]
488    /// # ///
489    ///
490    /// import requests
491    ///
492    /// print("Hello, World!")
493    /// ```
494    ///
495    /// This function would return:
496    ///
497    /// - Preamble: `#!/usr/bin/env python3\n`
498    /// - Metadata: `requires-python = '>=3.11'\ndependencies = [\n  'requests<3',\n  'rich',\n]`
499    /// - Postlude: `import requests\n\nprint("Hello, World!")\n`
500    ///
501    /// See: <https://peps.python.org/pep-0723/>
502    pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> {
503        // Identify the opening pragma.
504        let Some(index) = FINDER.find(contents) else {
505            return Ok(None);
506        };
507
508        // The opening pragma must be the first line, or immediately preceded by a newline.
509        if !(index == 0 || matches!(contents[index - 1], b'\r' | b'\n')) {
510            return Ok(None);
511        }
512
513        // Extract the preceding content.
514        let prelude = std::str::from_utf8(&contents[..index])?;
515
516        // Decode as UTF-8.
517        let contents = &contents[index..];
518        let contents = std::str::from_utf8(contents)?;
519
520        let mut lines = contents.lines();
521
522        // Ensure that the first line is exactly `# /// script`.
523        if lines.next().is_none_or(|line| line != "# /// script") {
524            return Ok(None);
525        }
526
527        // > Every line between these two lines (# /// TYPE and # ///) MUST be a comment starting
528        // > with #. If there are characters after the # then the first character MUST be a space. The
529        // > embedded content is formed by taking away the first two characters of each line if the
530        // > second character is a space, otherwise just the first character (which means the line
531        // > consists of only a single #).
532        let mut toml = vec![];
533
534        for line in lines {
535            // Remove the leading `#`.
536            let Some(line) = line.strip_prefix('#') else {
537                break;
538            };
539
540            // If the line is empty, continue.
541            if line.is_empty() {
542                toml.push("");
543                continue;
544            }
545
546            // Otherwise, the line _must_ start with ` `.
547            let Some(line) = line.strip_prefix(' ') else {
548                break;
549            };
550
551            toml.push(line);
552        }
553
554        // Find the closing `# ///`. The precedence is such that we need to identify the _last_ such
555        // line.
556        //
557        // For example, given:
558        // ```python
559        // # /// script
560        // #
561        // # ///
562        // #
563        // # ///
564        // ```
565        //
566        // The latter `///` is the closing pragma. Track malformed terminators while searching, but
567        // continue looking for an exact terminator so trailing comments cannot invalidate it.
568        let mut has_trailing_content = false;
569        let mut closing_index = None;
570
571        for (index, line) in toml.iter().enumerate().rev() {
572            if *line == "///" {
573                closing_index = Some(index + 1);
574                break;
575            }
576
577            if line.starts_with("///") {
578                has_trailing_content = true;
579            }
580        }
581
582        let Some(index) = closing_index else {
583            return Err(if has_trailing_content {
584                Pep723Error::UnclosedBlockTrailingContent
585            } else {
586                Pep723Error::UnclosedBlock
587            });
588        };
589
590        // Discard any lines after the closing `# ///`.
591        //
592        // For example, given:
593        // ```python
594        // # /// script
595        // #
596        // # ///
597        // #
598        // #
599        // ```
600        //
601        // We need to discard the last two lines.
602        toml.truncate(index - 1);
603
604        // Extract the remaining content.
605        let postlude = contents.lines().skip(index + 1).collect::<Vec<_>>();
606
607        // Ensure that the remaining content doesn't include another complete `script` block.
608        // A `# /// script` line can be embedded content inside another typed block.
609        let mut lines = postlude.iter().peekable();
610        while let Some(line) = lines.next() {
611            // Capture the metadata.
612            let Some(metadata_type) = line.strip_prefix("# /// ") else {
613                continue;
614            };
615
616            // Parse the metadata type per spec
617            if metadata_type.is_empty()
618                || !metadata_type
619                    .bytes()
620                    .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
621            {
622                continue;
623            }
624
625            let is_script_block = metadata_type == "script";
626            let mut is_closed = false;
627            while let Some(line) = lines.next() {
628                // Per e.g. # dependencies = []
629                let Some(content) = line.strip_prefix('#') else {
630                    break;
631                };
632                if !(content.is_empty() || content.starts_with(' ')) {
633                    break;
634                }
635
636                if *line == "# ///" {
637                    let Some(next_line) = lines.peek() else {
638                        is_closed = true;
639                        break;
640                    };
641
642                    let Some(next_content) = next_line.strip_prefix('#') else {
643                        is_closed = true;
644                        break;
645                    };
646
647                    if !(next_content.is_empty() || next_content.starts_with(' ')) {
648                        is_closed = true;
649                        break;
650                    }
651                }
652            }
653
654            if is_script_block && is_closed {
655                return Err(Pep723Error::DuplicateBlock);
656            }
657        }
658
659        // Join the lines into a single string.
660        let prelude = prelude.to_string();
661        let metadata = toml.join("\n") + "\n";
662        let postlude = postlude.join("\n") + "\n";
663
664        Ok(Some(Self {
665            prelude,
666            metadata,
667            postlude,
668        }))
669    }
670}
671
672/// Extracts the shebang line from the given file contents and returns it along with the remaining
673/// content.
674fn extract_shebang(contents: &[u8]) -> Result<(String, String), Pep723Error> {
675    let contents = std::str::from_utf8(contents)?;
676
677    if contents.starts_with("#!") {
678        // Find the first newline.
679        let bytes = contents.as_bytes();
680        let index = bytes
681            .iter()
682            .position(|&b| b == b'\r' || b == b'\n')
683            .unwrap_or(bytes.len());
684
685        // Support `\r`, `\n`, and `\r\n` line endings.
686        let width = match bytes.get(index) {
687            Some(b'\r') => {
688                if bytes.get(index + 1) == Some(&b'\n') {
689                    2
690                } else {
691                    1
692                }
693            }
694            Some(b'\n') => 1,
695            _ => 0,
696        };
697
698        // Extract the shebang line.
699        let shebang = contents[..index].to_string();
700        let script = contents[index + width..].to_string();
701
702        Ok((shebang, script))
703    } else {
704        Ok((String::new(), contents.to_string()))
705    }
706}
707
708/// Formats the provided metadata by prefixing each line with `#` and wrapping it with script markers.
709fn serialize_metadata(metadata: &str) -> String {
710    let mut output = String::with_capacity(metadata.len() + 32);
711
712    output.push_str("# /// script");
713    output.push('\n');
714
715    for line in metadata.lines() {
716        output.push('#');
717        if !line.is_empty() {
718            output.push(' ');
719            output.push_str(line);
720        }
721        output.push('\n');
722    }
723
724    output.push_str("# ///");
725    output.push('\n');
726
727    output
728}
729
730#[cfg(test)]
731mod tests {
732    use std::assert_matches;
733    use std::str::FromStr;
734
735    use indoc::indoc;
736
737    use crate::{Pep723Error, Pep723Script, ScriptTag, serialize_metadata};
738
739    #[test]
740    fn missing_space() {
741        let contents = indoc::indoc! {r"
742        # /// script
743        #requires-python = '>=3.11'
744        # ///
745    "};
746
747        assert_matches!(
748            ScriptTag::parse(contents.as_bytes()),
749            Err(Pep723Error::UnclosedBlock)
750        );
751    }
752
753    #[test]
754    fn no_closing_pragma() {
755        let contents = indoc::indoc! {r"
756        # /// script
757        # requires-python = '>=3.11'
758        # dependencies = [
759        #     'requests<3',
760        #     'rich',
761        # ]
762    "};
763
764        assert_matches!(
765            ScriptTag::parse(contents.as_bytes()),
766            Err(Pep723Error::UnclosedBlock)
767        );
768    }
769
770    #[test]
771    fn closing_tag_trailing_whitespace() {
772        let contents = indoc! {"
773            # /// script
774            # requires-python = '>=3.11'
775            # ///\x20
776        "};
777
778        assert_matches!(
779            ScriptTag::parse(contents.as_bytes()),
780            Err(Pep723Error::UnclosedBlockTrailingContent)
781        );
782    }
783
784    #[test]
785    fn closing_tag_trailing_content() {
786        let contents = indoc::indoc! {r"
787            # /// script
788            # requires-python = '>=3.11'
789            # /// unexpected
790        "};
791
792        assert_matches!(
793            ScriptTag::parse(contents.as_bytes()),
794            Err(Pep723Error::UnclosedBlockTrailingContent)
795        );
796    }
797
798    #[test]
799    fn closing_tag_followed_by_prefixed_comment() {
800        let contents = indoc::indoc! {r#"
801            # /// script
802            # dependencies = []
803            # ///
804            # /// documentation
805            print("Hello, world!")
806        "#};
807
808        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
809
810        assert_eq!(actual.metadata, "dependencies = []\n");
811        assert_eq!(
812            actual.postlude,
813            indoc! {r#"
814                # /// documentation
815                print("Hello, world!")
816            "#}
817        );
818    }
819
820    #[test]
821    fn closing_tag_followed_by_trailing_whitespace_comment() {
822        let contents = indoc! {"
823            # /// script
824            # dependencies = []
825            # ///
826            # ///\x20
827            print(\"Hello, world!\")
828        "};
829
830        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
831
832        assert_eq!(actual.metadata, "dependencies = []\n");
833        assert_eq!(
834            actual.postlude,
835            indoc! {"
836                # ///\x20
837                print(\"Hello, world!\")
838            "}
839        );
840    }
841
842    #[test]
843    fn leading_content() {
844        let contents = indoc::indoc! {r"
845        pass # /// script
846        # requires-python = '>=3.11'
847        # dependencies = [
848        #   'requests<3',
849        #   'rich',
850        # ]
851        # ///
852        #
853        #
854    "};
855
856        assert_eq!(ScriptTag::parse(contents.as_bytes()).unwrap(), None);
857    }
858
859    #[test]
860    fn simple() {
861        let contents = indoc::indoc! {r"
862        # /// script
863        # requires-python = '>=3.11'
864        # dependencies = [
865        #     'requests<3',
866        #     'rich',
867        # ]
868        # ///
869
870        import requests
871        from rich.pretty import pprint
872
873        resp = requests.get('https://peps.python.org/api/peps.json')
874        data = resp.json()
875    "};
876
877        let expected_metadata = indoc::indoc! {r"
878        requires-python = '>=3.11'
879        dependencies = [
880            'requests<3',
881            'rich',
882        ]
883    "};
884
885        let expected_data = indoc::indoc! {r"
886
887        import requests
888        from rich.pretty import pprint
889
890        resp = requests.get('https://peps.python.org/api/peps.json')
891        data = resp.json()
892    "};
893
894        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
895
896        assert_eq!(actual.prelude, String::new());
897        assert_eq!(actual.metadata, expected_metadata);
898        assert_eq!(actual.postlude, expected_data);
899    }
900
901    #[test]
902    fn simple_with_shebang() {
903        let contents = indoc::indoc! {r"
904        #!/usr/bin/env python3
905        # /// script
906        # requires-python = '>=3.11'
907        # dependencies = [
908        #     'requests<3',
909        #     'rich',
910        # ]
911        # ///
912
913        import requests
914        from rich.pretty import pprint
915
916        resp = requests.get('https://peps.python.org/api/peps.json')
917        data = resp.json()
918    "};
919
920        let expected_metadata = indoc::indoc! {r"
921        requires-python = '>=3.11'
922        dependencies = [
923            'requests<3',
924            'rich',
925        ]
926    "};
927
928        let expected_data = indoc::indoc! {r"
929
930        import requests
931        from rich.pretty import pprint
932
933        resp = requests.get('https://peps.python.org/api/peps.json')
934        data = resp.json()
935    "};
936
937        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
938
939        assert_eq!(actual.prelude, "#!/usr/bin/env python3\n".to_string());
940        assert_eq!(actual.metadata, expected_metadata);
941        assert_eq!(actual.postlude, expected_data);
942    }
943
944    #[test]
945    fn embedded_comment() {
946        let contents = indoc::indoc! {r"
947        # /// script
948        # embedded-csharp = '''
949        # /// <summary>
950        # /// text
951        # ///
952        # /// </summary>
953        # public class MyClass { }
954        # '''
955        # ///
956    "};
957
958        let expected = indoc::indoc! {r"
959        embedded-csharp = '''
960        /// <summary>
961        /// text
962        ///
963        /// </summary>
964        public class MyClass { }
965        '''
966    "};
967
968        let actual = ScriptTag::parse(contents.as_bytes())
969            .unwrap()
970            .unwrap()
971            .metadata;
972
973        assert_eq!(actual, expected);
974    }
975
976    #[test]
977    fn trailing_lines() {
978        let contents = indoc::indoc! {r"
979            # /// script
980            # requires-python = '>=3.11'
981            # dependencies = [
982            #     'requests<3',
983            #     'rich',
984            # ]
985            # ///
986            #
987            #
988        "};
989
990        let expected = indoc::indoc! {r"
991            requires-python = '>=3.11'
992            dependencies = [
993                'requests<3',
994                'rich',
995            ]
996        "};
997
998        let actual = ScriptTag::parse(contents.as_bytes())
999            .unwrap()
1000            .unwrap()
1001            .metadata;
1002
1003        assert_eq!(actual, expected);
1004    }
1005
1006    #[test]
1007    fn unclosed_second_script_block_is_not_duplicate() {
1008        let contents = indoc::indoc! {r#"
1009            # /// script
1010            # dependencies = ["requests"]
1011            # ///
1012
1013            print("Hello, world!")
1014
1015            # /// script
1016        "#};
1017
1018        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1019    }
1020
1021    #[test]
1022    fn adjacent_unclosed_second_script_block_is_not_duplicate() {
1023        let contents = indoc::indoc! {r#"
1024            # /// script
1025            # dependencies = []
1026            # ///
1027            # /// script
1028            print("Hello, world!")
1029        "#};
1030
1031        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
1032
1033        assert_eq!(actual.metadata, "dependencies = []\n");
1034        assert_eq!(
1035            actual.postlude,
1036            indoc! {r#"
1037                # /// script
1038                print("Hello, world!")
1039            "#}
1040        );
1041    }
1042
1043    #[test]
1044    fn other_script_block_is_ignored() {
1045        let contents = indoc::indoc! {r#"
1046            # /// script
1047            # dependencies = ["requests"]
1048            # ///
1049
1050
1051            # /// other
1052            # /// script
1053            # ///
1054
1055            print("Hello, world!")
1056        "#};
1057
1058        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1059    }
1060
1061    #[test]
1062    fn serialize_metadata_formatting() {
1063        let metadata = indoc::indoc! {r"
1064            requires-python = '>=3.11'
1065            dependencies = [
1066              'requests<3',
1067              'rich',
1068            ]
1069        "};
1070
1071        let expected_output = indoc::indoc! {r"
1072            # /// script
1073            # requires-python = '>=3.11'
1074            # dependencies = [
1075            #   'requests<3',
1076            #   'rich',
1077            # ]
1078            # ///
1079        "};
1080
1081        let result = serialize_metadata(metadata);
1082        assert_eq!(result, expected_output);
1083    }
1084
1085    #[test]
1086    fn serialize_metadata_empty() {
1087        let metadata = "";
1088        let expected_output = indoc! {"
1089            # /// script
1090            # ///
1091        "};
1092
1093        let result = serialize_metadata(metadata);
1094        assert_eq!(result, expected_output);
1095    }
1096
1097    #[test]
1098    fn script_init_empty() {
1099        let contents = "".as_bytes();
1100        let (prelude, metadata, postlude) =
1101            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1102                .unwrap();
1103        assert_eq!(prelude, "");
1104        assert_eq!(
1105            metadata.raw,
1106            indoc::indoc! {r"
1107            dependencies = []
1108            "}
1109        );
1110        assert_eq!(postlude, "");
1111    }
1112
1113    #[test]
1114    fn script_init_requires_python() {
1115        let contents = "".as_bytes();
1116        let (prelude, metadata, postlude) = Pep723Script::init_metadata(
1117            contents,
1118            &uv_pep440::VersionSpecifiers::from_str(">=3.8").unwrap(),
1119        )
1120        .unwrap();
1121        assert_eq!(prelude, "");
1122        assert_eq!(
1123            metadata.raw,
1124            indoc::indoc! {r#"
1125            requires-python = ">=3.8"
1126            dependencies = []
1127            "#}
1128        );
1129        assert_eq!(postlude, "");
1130    }
1131
1132    #[test]
1133    fn script_init_with_hashbang() {
1134        let contents = indoc::indoc! {r#"
1135        #!/usr/bin/env python3
1136
1137        print("Hello, world!")
1138        "#}
1139        .as_bytes();
1140        let (prelude, metadata, postlude) =
1141            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1142                .unwrap();
1143        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1144        assert_eq!(
1145            metadata.raw,
1146            indoc::indoc! {r"
1147            dependencies = []
1148            "}
1149        );
1150        assert_eq!(
1151            postlude,
1152            indoc::indoc! {r#"
1153
1154            print("Hello, world!")
1155            "#}
1156        );
1157    }
1158
1159    #[test]
1160    fn script_init_with_other_metadata() {
1161        let contents = indoc::indoc! {r#"
1162        # /// noscript
1163        # Hello,
1164        #
1165        # World!
1166        # ///
1167
1168        print("Hello, world!")
1169        "#}
1170        .as_bytes();
1171        let (prelude, metadata, postlude) =
1172            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1173                .unwrap();
1174        assert_eq!(prelude, "");
1175        assert_eq!(
1176            metadata.raw,
1177            indoc::indoc! {r"
1178            dependencies = []
1179            "}
1180        );
1181        // Note the extra line at the beginning.
1182        assert_eq!(
1183            postlude,
1184            indoc::indoc! {r#"
1185
1186            # /// noscript
1187            # Hello,
1188            #
1189            # World!
1190            # ///
1191
1192            print("Hello, world!")
1193            "#}
1194        );
1195    }
1196
1197    #[test]
1198    fn script_init_with_hashbang_and_other_metadata() {
1199        let contents = indoc::indoc! {r#"
1200        #!/usr/bin/env python3
1201        # /// noscript
1202        # Hello,
1203        #
1204        # World!
1205        # ///
1206
1207        print("Hello, world!")
1208        "#}
1209        .as_bytes();
1210        let (prelude, metadata, postlude) =
1211            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1212                .unwrap();
1213        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1214        assert_eq!(
1215            metadata.raw,
1216            indoc::indoc! {r"
1217            dependencies = []
1218            "}
1219        );
1220        // Note the extra line at the beginning.
1221        assert_eq!(
1222            postlude,
1223            indoc::indoc! {r#"
1224
1225            # /// noscript
1226            # Hello,
1227            #
1228            # World!
1229            # ///
1230
1231            print("Hello, world!")
1232            "#}
1233        );
1234    }
1235
1236    #[test]
1237    fn script_init_with_valid_metadata_line() {
1238        let contents = indoc::indoc! {r#"
1239        # Hello,
1240        # /// noscript
1241        #
1242        # World!
1243        # ///
1244
1245        print("Hello, world!")
1246        "#}
1247        .as_bytes();
1248        let (prelude, metadata, postlude) =
1249            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1250                .unwrap();
1251        assert_eq!(prelude, "");
1252        assert_eq!(
1253            metadata.raw,
1254            indoc::indoc! {r"
1255            dependencies = []
1256            "}
1257        );
1258        // Note the extra line at the beginning.
1259        assert_eq!(
1260            postlude,
1261            indoc::indoc! {r#"
1262
1263            # Hello,
1264            # /// noscript
1265            #
1266            # World!
1267            # ///
1268
1269            print("Hello, world!")
1270            "#}
1271        );
1272    }
1273
1274    #[test]
1275    fn script_init_with_valid_empty_metadata_line() {
1276        let contents = indoc::indoc! {r#"
1277        #
1278        # /// noscript
1279        # Hello,
1280        # World!
1281        # ///
1282
1283        print("Hello, world!")
1284        "#}
1285        .as_bytes();
1286        let (prelude, metadata, postlude) =
1287            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1288                .unwrap();
1289        assert_eq!(prelude, "");
1290        assert_eq!(
1291            metadata.raw,
1292            indoc::indoc! {r"
1293            dependencies = []
1294            "}
1295        );
1296        // Note the extra line at the beginning.
1297        assert_eq!(
1298            postlude,
1299            indoc::indoc! {r#"
1300
1301            #
1302            # /// noscript
1303            # Hello,
1304            # World!
1305            # ///
1306
1307            print("Hello, world!")
1308            "#}
1309        );
1310    }
1311
1312    #[test]
1313    fn script_init_with_non_metadata_comment() {
1314        let contents = indoc::indoc! {r#"
1315        #Hello,
1316        # /// noscript
1317        #
1318        # World!
1319        # ///
1320
1321        print("Hello, world!")
1322        "#}
1323        .as_bytes();
1324        let (prelude, metadata, postlude) =
1325            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1326                .unwrap();
1327        assert_eq!(prelude, "");
1328        assert_eq!(
1329            metadata.raw,
1330            indoc::indoc! {r"
1331            dependencies = []
1332            "}
1333        );
1334        assert_eq!(
1335            postlude,
1336            indoc::indoc! {r#"
1337            #Hello,
1338            # /// noscript
1339            #
1340            # World!
1341            # ///
1342
1343            print("Hello, world!")
1344            "#}
1345        );
1346    }
1347}