Given the contents of a Python file, extract the `script` metadata block with leading comment hashes removed, any preceding shebang or content (prelude), and the remaining Python script. Given the following input string representing the contents of a Python script: ```python #!/usr/bin/env python3 # /// script # requires-python = '>=3.11' # dependencies = [ # 'requests<3', # 'rich', # ] # //
(contents: &[u8])
| 49 | /// |
| 50 | /// See: <https://peps.python.org/pep-0723/> |
| 51 | pub fn parse(contents: &[u8]) -> Option<Self> { |
| 52 | // Identify the opening pragma. |
| 53 | let index = FINDER.find(contents)?; |
| 54 | |
| 55 | // The opening pragma must be the first line, or immediately preceded by a newline. |
| 56 | if !(index == 0 || matches!(contents[index - 1], b'\r' | b'\n')) { |
| 57 | return None; |
| 58 | } |
| 59 | |
| 60 | // Extract the preceding content. |
| 61 | let prelude = std::str::from_utf8(&contents[..index]).ok()?; |
| 62 | |
| 63 | // Decode as UTF-8. |
| 64 | let contents = &contents[index..]; |
| 65 | let contents = std::str::from_utf8(contents).ok()?; |
| 66 | |
| 67 | let mut lines = contents.lines(); |
| 68 | |
| 69 | // Ensure that the first line is exactly `# /// script`. |
| 70 | if lines.next().is_none_or(|line| line != "# /// script") { |
| 71 | return None; |
| 72 | } |
| 73 | |
| 74 | // > Every line between these two lines (# /// TYPE and # ///) MUST be a comment starting |
| 75 | // > with #. If there are characters after the # then the first character MUST be a space. The |
| 76 | // > embedded content is formed by taking away the first two characters of each line if the |
| 77 | // > second character is a space, otherwise just the first character (which means the line |
| 78 | // > consists of only a single #). |
| 79 | let mut toml = vec![]; |
| 80 | |
| 81 | // Extract the content that follows the metadata block. |
| 82 | let mut python_script = vec![]; |
| 83 | |
| 84 | while let Some(line) = lines.next() { |
| 85 | // Remove the leading `#`. |
| 86 | let Some(line) = line.strip_prefix('#') else { |
| 87 | python_script.push(line); |
| 88 | python_script.extend(lines); |
| 89 | break; |
| 90 | }; |
| 91 | |
| 92 | // If the line is empty, continue. |
| 93 | if line.is_empty() { |
| 94 | toml.push(""); |
| 95 | continue; |
| 96 | } |
| 97 | |
| 98 | // Otherwise, the line _must_ start with ` `. |
| 99 | let Some(line) = line.strip_prefix(' ') else { |
| 100 | python_script.push(line); |
| 101 | python_script.extend(lines); |
| 102 | break; |
| 103 | }; |
| 104 | |
| 105 | toml.push(line); |
| 106 | } |
| 107 | |
| 108 | // Find the closing `# ///`. The precedence is such that we need to identify the _last_ such |