Skip to content

_parse_pyproject

_get_package_name_from_pyproject(pyproject_path)

Get the package name from a local pyproject.toml.

Example 1: if the project table has name="xyz" and import-name=[], return `"xyz".

Example 2: if the project table has name="pillow" and import-name=["PIL"], return "PIL".

Example 3: if the project table has name="xyz" and import-name=["xyz1", "xyz2], return "xyz".

Reference: https://packaging.python.org/en/latest/specifications/pyproject-toml

Source code in src/fractal_task_tools/_parse_pyproject.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def _get_package_name_from_pyproject(pyproject_path: Path) -> str:
    """
    Get the package name from a local `pyproject.toml`.

    Example 1: if the `project` table has `name="xyz"` and
    `import-name=[]`, return `"xyz".

    Example 2: if the `project` table has `name="pillow"` and
    `import-name=["PIL"]`, return `"PIL"`.

    Example 3: if the `project` table has `name="xyz"` and
    `import-name=["xyz1", "xyz2]`, return `"xyz"`.

    Reference:
    https://packaging.python.org/en/latest/specifications/pyproject-toml
    """
    try:
        with Path(pyproject_path).open("rb") as f:
            pyproject = tomllib.load(f)
        project_table = pyproject["project"]
        if "import-names" in project_table and len(project_table["import-names"]) == 1:
            output = project_table["import-names"][0]
            logger.info(f"Identified package name '{output}' from pyproject.toml")
            return output
        else:
            output = project_table["name"]
            logger.info(f"Identified package name '{output}' from pyproject.toml")
            return output
    except Exception as e:
        sys.exit(
            "`--package` was not provided, and discovery based on "
            f"`pyproject.toml` failed with the following error: {str(e)}"
        )