File: utils.py

package info (click to toggle)
hatch-build-scripts 1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 488 kB
  • sloc: python: 415; makefile: 3
file content (83 lines) | stat: -rw-r--r-- 2,099 bytes parent folder | download
1
2
3
4
5
6
7
8
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from __future__ import annotations

import subprocess
import sys
import zipfile
from contextlib import contextmanager
from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING

import toml

import hatch_build_scripts

if TYPE_CHECKING:
    from collections.abc import Iterator
    from collections.abc import Sequence

    from hatch_build_scripts.plugin import OneScriptConfig

ROOT_DIR = Path(__file__).parent.parent


def create_project(path: Path | str, scripts: Sequence[OneScriptConfig]) -> FakeProject:
    path = Path(path)

    full_config = {
        "project": {
            "name": "test-project",
            "version": "0.0.0",
            "description": "A test project",
        },
        "build-system": {
            "requires": ["hatchling", f"hatch-build-scripts @ {ROOT_DIR.as_uri()}"],
            "build-backend": "hatchling.build",
        },
        "tool": {
            "hatch": {
                "build": {
                    "hooks": {
                        "build-scripts": {
                            "scripts": list(map(asdict, scripts)),
                        }
                    }
                }
            }
        },
    }

    (path / "pyproject.toml").write_text(toml.dumps(full_config), encoding="utf-8")

    return FakeProject(path)


class FakeProject:
    def __init__(self, path: Path) -> None:
        self.path = path

    def build(self) -> None:
        subprocess.run(
            [
                sys.executable,
                "-m",
                "pip",
                "cache",
                "remove",
                hatch_build_scripts.__name__,
            ],
            cwd=self.path,
            check=True,
        )
        subprocess.run(
            [sys.executable, "-m", "hatch", "build"],
            cwd=self.path,
            check=True,
        )

    @contextmanager
    def dist(self) -> Iterator[zipfile.ZipFile]:
        files = list((self.path / "dist").glob("*.whl"))
        assert len(files) == 1
        with zipfile.ZipFile(str(files[0])) as whl:
            yield whl