Skip to content

Instantly share code, notes, and snippets.

@gwerbin
Created November 16, 2022 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwerbin/2690e8b4eadaba4aae222be20d736f85 to your computer and use it in GitHub Desktop.
Save gwerbin/2690e8b4eadaba4aae222be20d736f85 to your computer and use it in GitHub Desktop.
Extract deps from pyproject 'project' section, PEP 621 (https://peps.python.org/pep-0621/)
#!/usr/bin/env python
r"""Extract dependencies from Pyproject PEP 621 "project" section.
Specificiation: https://peps.python.org/pep-0621/
"""
import sys
from argparse import ArgumentParser
from enum import IntEnum
from pathlib import Path
from typing import NoReturn
class ErrorCode(IntEnum):
OTHER = 1
USAGE = 2
def warn(message: str) -> None:
print(message, file=sys.stderr)
def die(status: int, message: str) -> NoReturn:
warn(message)
sys.exit(status)
if sys.version_info >= (3, 11):
# `tomllib` will be part of the standard library in Python 3.11+.
import tomllib
else:
try:
import tomli as tomllib
except ImportError:
die(ErrorCode.OTHER, "The 'tomli' package is required for this script when using Python < 3.11.")
arg_parser = ArgumentParser()
arg_parser.add_argument('optional_dependency_groups', nargs='*')
arg_parser.add_argument('--file', '-f', nargs=1, default='pyproject.toml')
arg_parser.add_argument('--all', '-a', dest='use_all_categories', action='store_true')
def main():
cli_args = arg_parser.parse_args()
pyproject_file = Path(cli_args.file)
use_all_categories = cli_args.use_all_categories
opt_dep_groups = cli_args.optional_dependency_groups
with pyproject_file.open('rb') as fp:
pyproject = tomllib.load(fp)
project_data = pyproject.get('project', {})
deps: list[str] = project_data.get('dependencies', [])
opt_deps: dict[str, list[str]] = project_data.get('optional-dependencies', {})
if use_all_categories:
if opt_dep_groups:
warn('Warning: ignoring positional arguments, because -a/--all is set.')
opt_dep_groups = list(opt_deps.keys())
for categ in opt_dep_groups:
try:
deps.extend(opt_deps[categ])
except KeyError:
die(ErrorCode.OTHER, f'Unknown optional dependency group: {categ!r}')
sys.stdout.writelines(f'{dep}\n' for dep in deps)
if __name__ == '__main__':
main()
tomli >= 1.1.0 ; python_version < "3.11"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment