Last active
June 24, 2025 17:44
-
-
Save duckythescientist/c9e2dbeea0fbc4698f4777aaa2503f58 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Get dependencies from inline script metadata | |
""" | |
import re | |
import tomllib | |
REGEX = r'(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$' | |
def read(script: str) -> dict | None: | |
name = 'script' | |
matches = list( | |
filter(lambda m: m.group('type') == name, re.finditer(REGEX, script)) | |
) | |
if len(matches) > 1: | |
raise ValueError(f'Multiple {name} blocks found') | |
elif len(matches) == 1: | |
content = ''.join( | |
line[2:] if line.startswith('# ') else line[1:] | |
for line in matches[0].group('content').splitlines(keepends=True) | |
) | |
return tomllib.loads(content) | |
else: | |
return None | |
if __name__ == "__main__": | |
import sys | |
fname = sys.argv[1] | |
try: | |
with open(fname, "r") as f: | |
script = f.read() | |
metadata = read(script) | |
if metadata is not None: | |
args = [] | |
for dep in metadata["dependencies"]: | |
args.append("--with") | |
args.append(dep) | |
print(" ".join(args)) | |
except FileNotFoundError: | |
pass | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment