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
734    use crate::{Pep723Error, Pep723Script, ScriptTag, serialize_metadata};
735    use std::str::FromStr;
736
737    #[test]
738    fn missing_space() {
739        let contents = indoc::indoc! {r"
740        # /// script
741        #requires-python = '>=3.11'
742        # ///
743    "};
744
745        assert_matches!(
746            ScriptTag::parse(contents.as_bytes()),
747            Err(Pep723Error::UnclosedBlock)
748        );
749    }
750
751    #[test]
752    fn no_closing_pragma() {
753        let contents = indoc::indoc! {r"
754        # /// script
755        # requires-python = '>=3.11'
756        # dependencies = [
757        #     'requests<3',
758        #     'rich',
759        # ]
760    "};
761
762        assert_matches!(
763            ScriptTag::parse(contents.as_bytes()),
764            Err(Pep723Error::UnclosedBlock)
765        );
766    }
767
768    #[test]
769    fn closing_tag_trailing_whitespace() {
770        // Explicit string (not `indoc`) so the closing tag's trailing space is preserved.
771        let contents = "# /// script\n# requires-python = '>=3.11'\n# /// \n";
772
773        assert_matches!(
774            ScriptTag::parse(contents.as_bytes()),
775            Err(Pep723Error::UnclosedBlockTrailingContent)
776        );
777    }
778
779    #[test]
780    fn closing_tag_trailing_content() {
781        let contents = indoc::indoc! {r"
782            # /// script
783            # requires-python = '>=3.11'
784            # /// unexpected
785        "};
786
787        assert_matches!(
788            ScriptTag::parse(contents.as_bytes()),
789            Err(Pep723Error::UnclosedBlockTrailingContent)
790        );
791    }
792
793    #[test]
794    fn closing_tag_followed_by_prefixed_comment() {
795        let contents = indoc::indoc! {r#"
796            # /// script
797            # dependencies = []
798            # ///
799            # /// documentation
800            print("Hello, world!")
801        "#};
802
803        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
804
805        assert_eq!(actual.metadata, "dependencies = []\n");
806        assert_eq!(
807            actual.postlude,
808            "# /// documentation\nprint(\"Hello, world!\")\n"
809        );
810    }
811
812    #[test]
813    fn closing_tag_followed_by_trailing_whitespace_comment() {
814        let contents =
815            "# /// script\n# dependencies = []\n# ///\n# /// \nprint(\"Hello, world!\")\n";
816
817        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
818
819        assert_eq!(actual.metadata, "dependencies = []\n");
820        assert_eq!(actual.postlude, "# /// \nprint(\"Hello, world!\")\n");
821    }
822
823    #[test]
824    fn leading_content() {
825        let contents = indoc::indoc! {r"
826        pass # /// script
827        # requires-python = '>=3.11'
828        # dependencies = [
829        #   'requests<3',
830        #   'rich',
831        # ]
832        # ///
833        #
834        #
835    "};
836
837        assert_eq!(ScriptTag::parse(contents.as_bytes()).unwrap(), None);
838    }
839
840    #[test]
841    fn simple() {
842        let contents = indoc::indoc! {r"
843        # /// script
844        # requires-python = '>=3.11'
845        # dependencies = [
846        #     'requests<3',
847        #     'rich',
848        # ]
849        # ///
850
851        import requests
852        from rich.pretty import pprint
853
854        resp = requests.get('https://peps.python.org/api/peps.json')
855        data = resp.json()
856    "};
857
858        let expected_metadata = indoc::indoc! {r"
859        requires-python = '>=3.11'
860        dependencies = [
861            'requests<3',
862            'rich',
863        ]
864    "};
865
866        let expected_data = indoc::indoc! {r"
867
868        import requests
869        from rich.pretty import pprint
870
871        resp = requests.get('https://peps.python.org/api/peps.json')
872        data = resp.json()
873    "};
874
875        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
876
877        assert_eq!(actual.prelude, String::new());
878        assert_eq!(actual.metadata, expected_metadata);
879        assert_eq!(actual.postlude, expected_data);
880    }
881
882    #[test]
883    fn simple_with_shebang() {
884        let contents = indoc::indoc! {r"
885        #!/usr/bin/env python3
886        # /// script
887        # requires-python = '>=3.11'
888        # dependencies = [
889        #     'requests<3',
890        #     'rich',
891        # ]
892        # ///
893
894        import requests
895        from rich.pretty import pprint
896
897        resp = requests.get('https://peps.python.org/api/peps.json')
898        data = resp.json()
899    "};
900
901        let expected_metadata = indoc::indoc! {r"
902        requires-python = '>=3.11'
903        dependencies = [
904            'requests<3',
905            'rich',
906        ]
907    "};
908
909        let expected_data = indoc::indoc! {r"
910
911        import requests
912        from rich.pretty import pprint
913
914        resp = requests.get('https://peps.python.org/api/peps.json')
915        data = resp.json()
916    "};
917
918        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
919
920        assert_eq!(actual.prelude, "#!/usr/bin/env python3\n".to_string());
921        assert_eq!(actual.metadata, expected_metadata);
922        assert_eq!(actual.postlude, expected_data);
923    }
924
925    #[test]
926    fn embedded_comment() {
927        let contents = indoc::indoc! {r"
928        # /// script
929        # embedded-csharp = '''
930        # /// <summary>
931        # /// text
932        # ///
933        # /// </summary>
934        # public class MyClass { }
935        # '''
936        # ///
937    "};
938
939        let expected = indoc::indoc! {r"
940        embedded-csharp = '''
941        /// <summary>
942        /// text
943        ///
944        /// </summary>
945        public class MyClass { }
946        '''
947    "};
948
949        let actual = ScriptTag::parse(contents.as_bytes())
950            .unwrap()
951            .unwrap()
952            .metadata;
953
954        assert_eq!(actual, expected);
955    }
956
957    #[test]
958    fn trailing_lines() {
959        let contents = indoc::indoc! {r"
960            # /// script
961            # requires-python = '>=3.11'
962            # dependencies = [
963            #     'requests<3',
964            #     'rich',
965            # ]
966            # ///
967            #
968            #
969        "};
970
971        let expected = indoc::indoc! {r"
972            requires-python = '>=3.11'
973            dependencies = [
974                'requests<3',
975                'rich',
976            ]
977        "};
978
979        let actual = ScriptTag::parse(contents.as_bytes())
980            .unwrap()
981            .unwrap()
982            .metadata;
983
984        assert_eq!(actual, expected);
985    }
986
987    #[test]
988    fn unclosed_second_script_block_is_not_duplicate() {
989        let contents = indoc::indoc! {r#"
990            # /// script
991            # dependencies = ["requests"]
992            # ///
993
994            print("Hello, world!")
995
996            # /// script
997        "#};
998
999        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1000    }
1001
1002    #[test]
1003    fn adjacent_unclosed_second_script_block_is_not_duplicate() {
1004        let contents = indoc::indoc! {r#"
1005            # /// script
1006            # dependencies = []
1007            # ///
1008            # /// script
1009            print("Hello, world!")
1010        "#};
1011
1012        let actual = ScriptTag::parse(contents.as_bytes()).unwrap().unwrap();
1013
1014        assert_eq!(actual.metadata, "dependencies = []\n");
1015        assert_eq!(actual.postlude, "# /// script\nprint(\"Hello, world!\")\n");
1016    }
1017
1018    #[test]
1019    fn other_script_block_is_ignored() {
1020        let contents = indoc::indoc! {r#"
1021            # /// script
1022            # dependencies = ["requests"]
1023            # ///
1024
1025
1026            # /// other
1027            # /// script
1028            # ///
1029
1030            print("Hello, world!")
1031        "#};
1032
1033        assert!(ScriptTag::parse(contents.as_bytes()).is_ok());
1034    }
1035
1036    #[test]
1037    fn serialize_metadata_formatting() {
1038        let metadata = indoc::indoc! {r"
1039            requires-python = '>=3.11'
1040            dependencies = [
1041              'requests<3',
1042              'rich',
1043            ]
1044        "};
1045
1046        let expected_output = indoc::indoc! {r"
1047            # /// script
1048            # requires-python = '>=3.11'
1049            # dependencies = [
1050            #   'requests<3',
1051            #   'rich',
1052            # ]
1053            # ///
1054        "};
1055
1056        let result = serialize_metadata(metadata);
1057        assert_eq!(result, expected_output);
1058    }
1059
1060    #[test]
1061    fn serialize_metadata_empty() {
1062        let metadata = "";
1063        let expected_output = "# /// script\n# ///\n";
1064
1065        let result = serialize_metadata(metadata);
1066        assert_eq!(result, expected_output);
1067    }
1068
1069    #[test]
1070    fn script_init_empty() {
1071        let contents = "".as_bytes();
1072        let (prelude, metadata, postlude) =
1073            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1074                .unwrap();
1075        assert_eq!(prelude, "");
1076        assert_eq!(
1077            metadata.raw,
1078            indoc::indoc! {r"
1079            dependencies = []
1080            "}
1081        );
1082        assert_eq!(postlude, "");
1083    }
1084
1085    #[test]
1086    fn script_init_requires_python() {
1087        let contents = "".as_bytes();
1088        let (prelude, metadata, postlude) = Pep723Script::init_metadata(
1089            contents,
1090            &uv_pep440::VersionSpecifiers::from_str(">=3.8").unwrap(),
1091        )
1092        .unwrap();
1093        assert_eq!(prelude, "");
1094        assert_eq!(
1095            metadata.raw,
1096            indoc::indoc! {r#"
1097            requires-python = ">=3.8"
1098            dependencies = []
1099            "#}
1100        );
1101        assert_eq!(postlude, "");
1102    }
1103
1104    #[test]
1105    fn script_init_with_hashbang() {
1106        let contents = indoc::indoc! {r#"
1107        #!/usr/bin/env python3
1108
1109        print("Hello, world!")
1110        "#}
1111        .as_bytes();
1112        let (prelude, metadata, postlude) =
1113            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1114                .unwrap();
1115        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1116        assert_eq!(
1117            metadata.raw,
1118            indoc::indoc! {r"
1119            dependencies = []
1120            "}
1121        );
1122        assert_eq!(
1123            postlude,
1124            indoc::indoc! {r#"
1125
1126            print("Hello, world!")
1127            "#}
1128        );
1129    }
1130
1131    #[test]
1132    fn script_init_with_other_metadata() {
1133        let contents = indoc::indoc! {r#"
1134        # /// noscript
1135        # Hello,
1136        #
1137        # World!
1138        # ///
1139
1140        print("Hello, world!")
1141        "#}
1142        .as_bytes();
1143        let (prelude, metadata, postlude) =
1144            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1145                .unwrap();
1146        assert_eq!(prelude, "");
1147        assert_eq!(
1148            metadata.raw,
1149            indoc::indoc! {r"
1150            dependencies = []
1151            "}
1152        );
1153        // Note the extra line at the beginning.
1154        assert_eq!(
1155            postlude,
1156            indoc::indoc! {r#"
1157
1158            # /// noscript
1159            # Hello,
1160            #
1161            # World!
1162            # ///
1163
1164            print("Hello, world!")
1165            "#}
1166        );
1167    }
1168
1169    #[test]
1170    fn script_init_with_hashbang_and_other_metadata() {
1171        let contents = indoc::indoc! {r#"
1172        #!/usr/bin/env python3
1173        # /// noscript
1174        # Hello,
1175        #
1176        # World!
1177        # ///
1178
1179        print("Hello, world!")
1180        "#}
1181        .as_bytes();
1182        let (prelude, metadata, postlude) =
1183            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1184                .unwrap();
1185        assert_eq!(prelude, "#!/usr/bin/env python3\n");
1186        assert_eq!(
1187            metadata.raw,
1188            indoc::indoc! {r"
1189            dependencies = []
1190            "}
1191        );
1192        // Note the extra line at the beginning.
1193        assert_eq!(
1194            postlude,
1195            indoc::indoc! {r#"
1196
1197            # /// noscript
1198            # Hello,
1199            #
1200            # World!
1201            # ///
1202
1203            print("Hello, world!")
1204            "#}
1205        );
1206    }
1207
1208    #[test]
1209    fn script_init_with_valid_metadata_line() {
1210        let contents = indoc::indoc! {r#"
1211        # Hello,
1212        # /// noscript
1213        #
1214        # World!
1215        # ///
1216
1217        print("Hello, world!")
1218        "#}
1219        .as_bytes();
1220        let (prelude, metadata, postlude) =
1221            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1222                .unwrap();
1223        assert_eq!(prelude, "");
1224        assert_eq!(
1225            metadata.raw,
1226            indoc::indoc! {r"
1227            dependencies = []
1228            "}
1229        );
1230        // Note the extra line at the beginning.
1231        assert_eq!(
1232            postlude,
1233            indoc::indoc! {r#"
1234
1235            # Hello,
1236            # /// noscript
1237            #
1238            # World!
1239            # ///
1240
1241            print("Hello, world!")
1242            "#}
1243        );
1244    }
1245
1246    #[test]
1247    fn script_init_with_valid_empty_metadata_line() {
1248        let contents = indoc::indoc! {r#"
1249        #
1250        # /// noscript
1251        # Hello,
1252        # World!
1253        # ///
1254
1255        print("Hello, world!")
1256        "#}
1257        .as_bytes();
1258        let (prelude, metadata, postlude) =
1259            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1260                .unwrap();
1261        assert_eq!(prelude, "");
1262        assert_eq!(
1263            metadata.raw,
1264            indoc::indoc! {r"
1265            dependencies = []
1266            "}
1267        );
1268        // Note the extra line at the beginning.
1269        assert_eq!(
1270            postlude,
1271            indoc::indoc! {r#"
1272
1273            #
1274            # /// noscript
1275            # Hello,
1276            # World!
1277            # ///
1278
1279            print("Hello, world!")
1280            "#}
1281        );
1282    }
1283
1284    #[test]
1285    fn script_init_with_non_metadata_comment() {
1286        let contents = indoc::indoc! {r#"
1287        #Hello,
1288        # /// noscript
1289        #
1290        # World!
1291        # ///
1292
1293        print("Hello, world!")
1294        "#}
1295        .as_bytes();
1296        let (prelude, metadata, postlude) =
1297            Pep723Script::init_metadata(contents, &uv_pep440::VersionSpecifiers::default())
1298                .unwrap();
1299        assert_eq!(prelude, "");
1300        assert_eq!(
1301            metadata.raw,
1302            indoc::indoc! {r"
1303            dependencies = []
1304            "}
1305        );
1306        assert_eq!(
1307            postlude,
1308            indoc::indoc! {r#"
1309            #Hello,
1310            # /// noscript
1311            #
1312            # World!
1313            # ///
1314
1315            print("Hello, world!")
1316            "#}
1317        );
1318    }
1319}