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#[derive(Debug)]
33pub enum Pep723Item {
34 Script(Pep723Script),
36 Stdin(Pep723Metadata),
38 Remote(Pep723Metadata, SafeUrl),
40}
41
42impl Pep723Item {
43 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 pub fn as_script(&self) -> Option<&Pep723Script> {
54 match self {
55 Self::Script(script) => Some(script),
56 _ => None,
57 }
58 }
59}
60
61#[derive(Debug, Copy, Clone)]
63pub enum Pep723ItemRef<'item> {
64 Script(&'item Pep723Script),
66 Stdin(&'item Pep723Metadata),
68 Remote(&'item Pep723Metadata, &'item SafeUrl),
70}
71
72impl Pep723ItemRef<'_> {
73 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 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 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 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 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#[derive(Debug, Clone)]
159pub struct Pep723Script {
160 pub path: PathBuf,
162 pub metadata: Pep723Metadata,
164 pub prelude: String,
166 pub postlude: String,
168}
169
170impl Pep723Script {
171 pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> {
177 let contents = fs_err::tokio::read(&file).await?;
178
179 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 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 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 fn init_metadata(
222 contents: &[u8],
223 requires_python: &VersionSpecifiers,
224 ) -> Result<(String, Pep723Metadata, String), Pep723Error> {
225 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 let (shebang, postlude) = extract_shebang(contents)?;
243
244 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 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 !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 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 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#[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 #[serde(skip)]
367 pub raw: String,
368}
369
370impl Pep723Metadata {
371 pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> {
373 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 Ok(Some(Self::from_str(&metadata)?))
382 }
383
384 pub async fn read(file: impl AsRef<Path>) -> Result<Option<Self>, Pep723Error> {
390 let contents = fs_err::tokio::read(&file).await?;
391
392 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 Ok(Some(Self::from_str(&metadata)?))
401 }
402}
403
404impl FromStr for Pep723Metadata {
405 type Err = toml::de::Error;
406
407 #[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 prelude: String,
467 metadata: String,
469 postlude: String,
471}
472
473impl ScriptTag {
474 pub fn parse(contents: &[u8]) -> Result<Option<Self>, Pep723Error> {
503 let Some(index) = FINDER.find(contents) else {
505 return Ok(None);
506 };
507
508 if !(index == 0 || matches!(contents[index - 1], b'\r' | b'\n')) {
510 return Ok(None);
511 }
512
513 let prelude = std::str::from_utf8(&contents[..index])?;
515
516 let contents = &contents[index..];
518 let contents = std::str::from_utf8(contents)?;
519
520 let mut lines = contents.lines();
521
522 if lines.next().is_none_or(|line| line != "# /// script") {
524 return Ok(None);
525 }
526
527 let mut toml = vec![];
533
534 for line in lines {
535 let Some(line) = line.strip_prefix('#') else {
537 break;
538 };
539
540 if line.is_empty() {
542 toml.push("");
543 continue;
544 }
545
546 let Some(line) = line.strip_prefix(' ') else {
548 break;
549 };
550
551 toml.push(line);
552 }
553
554 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 toml.truncate(index - 1);
603
604 let postlude = contents.lines().skip(index + 1).collect::<Vec<_>>();
606
607 let mut lines = postlude.iter().peekable();
610 while let Some(line) = lines.next() {
611 let Some(metadata_type) = line.strip_prefix("# /// ") else {
613 continue;
614 };
615
616 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 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 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
672fn extract_shebang(contents: &[u8]) -> Result<(String, String), Pep723Error> {
675 let contents = std::str::from_utf8(contents)?;
676
677 if contents.starts_with("#!") {
678 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 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 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
708fn 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 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 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 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 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 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}