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 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 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 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 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 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}