Created
April 26, 2023 10:54
-
-
Save kadaliao/bfbc46c288f1d111354a89605922f8dd to your computer and use it in GitHub Desktop.
Generate requirements.txt and requirements-dev.txt from pyproject.toml
This file contains 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
import tomlkit | |
def format_version_constraint(constraint): | |
if constraint.startswith("^"): | |
constraint = ( | |
">=" | |
+ constraint[1:] | |
+ ",<" | |
+ ".".join( | |
str(int(part) + 1) if i == 0 else part | |
for i, part in enumerate(constraint[1:].split(".")) | |
) | |
) | |
else: | |
constraint = "==" + constraint | |
return constraint | |
def write_requirements(dependencies, filename): | |
with open(filename, "w") as f: | |
for package, version in dependencies.items(): | |
if package.lower() == "python": | |
continue | |
if isinstance(version, tomlkit.items.InlineTable): | |
constraint = format_version_constraint( | |
version.get("version", "*") | |
) | |
extras = version.get("extras", []) | |
if extras: | |
f.write(f"{package}[{','.join(extras)}]{constraint}\n") | |
else: | |
f.write(f"{package}{constraint}\n") | |
else: | |
constraint = format_version_constraint(str(version)) | |
f.write(f"{package}{constraint}\n") | |
def main(): | |
with open("pyproject.toml", "r") as f: | |
content = tomlkit.parse(f.read()) | |
main_dependencies = content["tool"]["poetry"]["dependencies"] | |
dev_dependencies = content["tool"]["poetry"]["group"]["dev"][ | |
"dependencies" | |
] | |
write_requirements(main_dependencies, "requirements.txt") | |
write_requirements(dev_dependencies, "requirements-dev.txt") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment