pdksetup 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pdksetup/__init__.py +0 -0
- pdksetup/cli.py +684 -0
- pdksetup/config.py +80 -0
- pdksetup/installers/__init__.py +0 -0
- pdksetup/installers/base.py +101 -0
- pdksetup/installers/custom.py +45 -0
- pdksetup/installers/iic.py +375 -0
- pdksetup/installers/volare.py +33 -0
- pdksetup/registry.py +319 -0
- pdksetup/state.py +69 -0
- pdksetup/updater.py +115 -0
- pdksetup-0.3.0.dist-info/METADATA +402 -0
- pdksetup-0.3.0.dist-info/RECORD +17 -0
- pdksetup-0.3.0.dist-info/WHEEL +5 -0
- pdksetup-0.3.0.dist-info/entry_points.txt +2 -0
- pdksetup-0.3.0.dist-info/licenses/LICENSE +201 -0
- pdksetup-0.3.0.dist-info/top_level.txt +1 -0
pdksetup/config.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tomllib
|
|
3
|
+
from dataclasses import dataclass, fields as dc_fields
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
CONFIG_PATH = Path.home() / ".config" / "pdksetup" / "config.toml"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _normalize(raw: str) -> Path:
|
|
10
|
+
"""Expand ~ and $VAR, then resolve to an absolute path.
|
|
11
|
+
|
|
12
|
+
Applied to every path value that originates as a user-supplied string
|
|
13
|
+
(config file, env var, CLI flag). TOML/env strings never get shell
|
|
14
|
+
expansion for free, so without this a config like `pdk_root = "~/pdk"`
|
|
15
|
+
creates a literal ~ directory. resolve(strict=False) makes relative
|
|
16
|
+
paths absolute against CWD without requiring the directory to exist yet.
|
|
17
|
+
"""
|
|
18
|
+
return Path(os.path.expandvars(os.path.expanduser(raw))).resolve()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _write_toml(path: Path, data: dict) -> None:
|
|
22
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
23
|
+
lines = ["[pdksetup]\n"]
|
|
24
|
+
for k, v in data.items():
|
|
25
|
+
escaped = str(v).replace("\\", "\\\\").replace('"', '\\"')
|
|
26
|
+
lines.append(f'{k} = "{escaped}"\n')
|
|
27
|
+
path.write_text("".join(lines), encoding="utf-8")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _read_toml(path: Path) -> dict:
|
|
31
|
+
if not path.exists():
|
|
32
|
+
return {}
|
|
33
|
+
with path.open("rb") as f:
|
|
34
|
+
return tomllib.load(f).get("pdksetup", {})
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class Config:
|
|
39
|
+
pdk_root: Path
|
|
40
|
+
volare_root: Path
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def load(
|
|
44
|
+
cls,
|
|
45
|
+
pdk_root_flag: str | None = None,
|
|
46
|
+
*,
|
|
47
|
+
config_path: Path | None = None,
|
|
48
|
+
) -> "Config":
|
|
49
|
+
path = config_path if config_path is not None else CONFIG_PATH
|
|
50
|
+
file_data = _read_toml(path)
|
|
51
|
+
|
|
52
|
+
pdk_root = (
|
|
53
|
+
_normalize(pdk_root_flag)
|
|
54
|
+
if pdk_root_flag
|
|
55
|
+
else _normalize(os.environ["PDK_ROOT"])
|
|
56
|
+
if "PDK_ROOT" in os.environ
|
|
57
|
+
else _normalize(file_data["pdk_root"])
|
|
58
|
+
if "pdk_root" in file_data
|
|
59
|
+
else Path.home() / ".pdk"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
volare_root = (
|
|
63
|
+
_normalize(os.environ["VOLARE_ROOT"])
|
|
64
|
+
if "VOLARE_ROOT" in os.environ
|
|
65
|
+
else _normalize(file_data["volare_root"])
|
|
66
|
+
if "volare_root" in file_data
|
|
67
|
+
else Path.home() / ".volare"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
return cls(pdk_root=pdk_root, volare_root=volare_root)
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def set(key: str, value: str, *, config_path: Path | None = None) -> None:
|
|
74
|
+
valid = {f.name for f in dc_fields(Config)}
|
|
75
|
+
if key not in valid:
|
|
76
|
+
raise ValueError(f"Unknown config key {key!r}. Valid keys: {sorted(valid)}")
|
|
77
|
+
path = config_path if config_path is not None else CONFIG_PATH
|
|
78
|
+
existing = _read_toml(path)
|
|
79
|
+
existing[key] = value
|
|
80
|
+
_write_toml(path, existing)
|
|
File without changes
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import shutil
|
|
3
|
+
import subprocess
|
|
4
|
+
import tempfile
|
|
5
|
+
from contextlib import contextmanager
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
INSTALL_DEPS = ["git", "python3"] # required by all installers
|
|
10
|
+
|
|
11
|
+
# Short hint strings shown when a runtime tool isn't on PATH. Prefer the
|
|
12
|
+
# distro-packaged name where most users will succeed with `apt install`, and
|
|
13
|
+
# a source URL otherwise. Missing tools never block an install — this is
|
|
14
|
+
# purely for user guidance.
|
|
15
|
+
RUNTIME_TOOL_HINTS: dict[str, str] = {
|
|
16
|
+
"magic": "https://github.com/RTimothyEdwards/magic",
|
|
17
|
+
"klayout": "apt install klayout | https://www.klayout.org",
|
|
18
|
+
"xschem": "https://github.com/StefanSchippers/xschem",
|
|
19
|
+
"ngspice": "apt install ngspice | http://ngspice.sourceforge.net",
|
|
20
|
+
"netgen": "apt install netgen-lvs",
|
|
21
|
+
"openroad": "https://github.com/The-OpenROAD-Project/OpenROAD",
|
|
22
|
+
"yosys": "apt install yosys | https://github.com/YosysHQ/yosys",
|
|
23
|
+
"Xyce": "https://xyce.sandia.gov",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
# How to read a tool's major version: regex applied to `<tool> --version`
|
|
27
|
+
# output. Tools not listed here are only checked for presence.
|
|
28
|
+
VERSION_PROBES: dict[str, str] = {
|
|
29
|
+
"ngspice": r"ngspice-(\d+)",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def tool_major_version(tool: str, path: str) -> int | None:
|
|
34
|
+
"""Major version of the tool at `path`, or None if it can't be determined.
|
|
35
|
+
|
|
36
|
+
Never raises: an unreadable version is reported as unknown, not as old.
|
|
37
|
+
"""
|
|
38
|
+
pattern = VERSION_PROBES.get(tool)
|
|
39
|
+
if pattern is None:
|
|
40
|
+
return None
|
|
41
|
+
try:
|
|
42
|
+
proc = subprocess.run(
|
|
43
|
+
[path, "--version"], capture_output=True, text=True, timeout=10, check=False
|
|
44
|
+
)
|
|
45
|
+
except (OSError, subprocess.SubprocessError):
|
|
46
|
+
return None
|
|
47
|
+
match = re.search(pattern, (proc.stdout or "") + (proc.stderr or ""))
|
|
48
|
+
return int(match.group(1)) if match else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def check_runtime_tools(tools: tuple[str, ...]) -> list[tuple[str, str | None]]:
|
|
52
|
+
"""Return [(tool_name, path_or_None)] for each tool in `tools`.
|
|
53
|
+
|
|
54
|
+
Uses shutil.which() to detect presence on PATH. Never raises.
|
|
55
|
+
"""
|
|
56
|
+
return [(t, shutil.which(t)) for t in tools]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class DepCheckResult:
|
|
61
|
+
missing_required: list[str] = field(default_factory=list)
|
|
62
|
+
missing_optional: list[str] = field(default_factory=list)
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def ok(self) -> bool:
|
|
66
|
+
return len(self.missing_required) == 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def check_deps(required: list[str], optional: list[str]) -> DepCheckResult:
|
|
70
|
+
result = DepCheckResult()
|
|
71
|
+
for dep in required:
|
|
72
|
+
if not shutil.which(dep):
|
|
73
|
+
result.missing_required.append(dep)
|
|
74
|
+
for dep in optional:
|
|
75
|
+
if not shutil.which(dep):
|
|
76
|
+
result.missing_optional.append(dep)
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@contextmanager
|
|
81
|
+
def temp_install_dir(target: Path):
|
|
82
|
+
# Ensure target.parent (typically pdk_root) exists, otherwise mkdtemp
|
|
83
|
+
# raises FileNotFoundError on a brand-new install root.
|
|
84
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
85
|
+
tmp = Path(tempfile.mkdtemp(dir=target.parent, prefix=".pdksetup_tmp_"))
|
|
86
|
+
try:
|
|
87
|
+
yield tmp
|
|
88
|
+
# success: move contents into target
|
|
89
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
for item in tmp.iterdir():
|
|
91
|
+
shutil.move(str(item), str(target / item.name))
|
|
92
|
+
except Exception:
|
|
93
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
94
|
+
raise
|
|
95
|
+
finally:
|
|
96
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
|
|
100
|
+
kwargs.setdefault("check", True)
|
|
101
|
+
return subprocess.run(cmd, **kwargs)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from pdksetup.installers.base import run, temp_install_dir
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class CustomInstaller:
|
|
8
|
+
"""Clone (or pull) a PDK from a git repo and report the installed ref.
|
|
9
|
+
|
|
10
|
+
`ref_strategy` controls which git ref gets recorded in state.json so that
|
|
11
|
+
`pdk check-updates` later compares like-for-like against the remote:
|
|
12
|
+
|
|
13
|
+
- "commit" (default): short SHA via `git rev-parse --short HEAD`. Use for
|
|
14
|
+
registry entries with version_source="github_commit".
|
|
15
|
+
- "tag": latest tag via `git describe --tags --abbrev=0`. Use for entries
|
|
16
|
+
with version_source="github_tag" or "github_release".
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def install(
|
|
20
|
+
self,
|
|
21
|
+
pdk_name: str,
|
|
22
|
+
*,
|
|
23
|
+
source_url: str,
|
|
24
|
+
pdk_root: Path,
|
|
25
|
+
ref_strategy: str = "commit",
|
|
26
|
+
) -> str:
|
|
27
|
+
dest = pdk_root / pdk_name
|
|
28
|
+
if (dest / ".git").exists():
|
|
29
|
+
run(["git", "-C", str(dest), "pull", "--ff-only"])
|
|
30
|
+
# Always sync submodules after pull — some PDKs (e.g. ASAP7) keep
|
|
31
|
+
# their real content in submodules, and a plain clone/pull without
|
|
32
|
+
# this step leaves an almost-empty skeleton.
|
|
33
|
+
run(["git", "-C", str(dest), "submodule", "update", "--init", "--recursive"])
|
|
34
|
+
else:
|
|
35
|
+
with temp_install_dir(dest) as tmp:
|
|
36
|
+
run(["git", "clone", "--recurse-submodules", source_url, str(tmp)])
|
|
37
|
+
return self._current_ref(dest, strategy=ref_strategy)
|
|
38
|
+
|
|
39
|
+
def _current_ref(self, dest: Path, *, strategy: str = "commit") -> str:
|
|
40
|
+
if strategy == "tag":
|
|
41
|
+
cmd = ["git", "-C", str(dest), "describe", "--tags", "--abbrev=0"]
|
|
42
|
+
else:
|
|
43
|
+
cmd = ["git", "-C", str(dest), "rev-parse", "--short", "HEAD"]
|
|
44
|
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
45
|
+
return result.stdout.strip() if result.returncode == 0 else "unknown"
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""Install a PDK by running an IIC-OSIC-TOOLS install recipe outside Docker.
|
|
2
|
+
|
|
3
|
+
IIC-OSIC-TOOLS builds some PDKs (ASAP7) from pinned slices of upstream repos
|
|
4
|
+
with a shell script that its Docker build runs. We run the same script, at a
|
|
5
|
+
pinned commit, with three things the Docker build would otherwise supply:
|
|
6
|
+
|
|
7
|
+
* the Dockerfile `ARG` pins the script reads, passed as environment variables;
|
|
8
|
+
* `$TOOLS/openvaf/bin/openvaf`, a two-line wrapper around the user's compiler;
|
|
9
|
+
* a private temp directory, by rewriting the script's one `SRC_DIR=` line to
|
|
10
|
+
read `$PDKSETUP_SRC_DIR` (the original is a fixed `/tmp` path).
|
|
11
|
+
|
|
12
|
+
The script deletes and recreates `$PDK_ROOT/<output_dir>`, so it runs against
|
|
13
|
+
a staging root inside the real PDK root, and the result is renamed into place
|
|
14
|
+
only after it built completely. The live install is never touched by the
|
|
15
|
+
script itself. Everything that can fail cheaply (tools, git version, compiler
|
|
16
|
+
that actually runs, a legacy clone in the way) is checked before anything on
|
|
17
|
+
disk changes.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import base64
|
|
23
|
+
import fnmatch
|
|
24
|
+
import hashlib
|
|
25
|
+
import os
|
|
26
|
+
import re
|
|
27
|
+
import shutil
|
|
28
|
+
import subprocess
|
|
29
|
+
import tempfile
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from pdksetup.installers.base import run
|
|
33
|
+
from pdksetup.registry import IICRecipe
|
|
34
|
+
|
|
35
|
+
# `git sparse-checkout set --no-cone` (used by the recipe) needs git 2.35:
|
|
36
|
+
# that release unified `init` and `set`, giving `set` its mode options.
|
|
37
|
+
MIN_GIT = (2, 35)
|
|
38
|
+
|
|
39
|
+
_COMPILERS = ("openvaf-r", "openvaf")
|
|
40
|
+
_SHA_RE = re.compile(r"^[0-9a-f]{7,40}$")
|
|
41
|
+
_ARG_RE = re.compile(r'^\s*ARG\s+([A-Za-z_][A-Za-z0-9_]*)=(.*)$', re.MULTILINE)
|
|
42
|
+
_SRC_DIR_RE = re.compile(r"^SRC_DIR=.*$", re.MULTILINE)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RecipeError(Exception):
|
|
46
|
+
"""A recipe install can't proceed; the message is shown to the user."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# --- Pure helpers (shared with the updater) --------------------------------
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_dockerfile_args(text: str) -> dict[str, str]:
|
|
53
|
+
"""`ARG NAME=value` lines of a Dockerfile, with surrounding quotes removed."""
|
|
54
|
+
return {name: value.strip().strip('"').strip("'") for name, value in _ARG_RE.findall(text)}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def script_env(dockerfile_text: str, script_text: str) -> dict[str, str]:
|
|
58
|
+
"""The Dockerfile ARGs the install script refers to, as its environment.
|
|
59
|
+
|
|
60
|
+
Selecting by reference (rather than a hard-coded list) keeps the
|
|
61
|
+
environment in step with whatever the pinned script expects.
|
|
62
|
+
"""
|
|
63
|
+
return {
|
|
64
|
+
name: value
|
|
65
|
+
for name, value in parse_dockerfile_args(dockerfile_text).items()
|
|
66
|
+
if re.search(rf"(?<![A-Za-z0-9_]){re.escape(name)}(?![A-Za-z0-9_])", script_text)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def patch_src_dir(script_text: str) -> str:
|
|
71
|
+
"""Point the script's temp directory at $PDKSETUP_SRC_DIR.
|
|
72
|
+
|
|
73
|
+
Reading an environment variable (instead of interpolating a path) means a
|
|
74
|
+
PDK root containing spaces or `$` can't break the script. Exactly one
|
|
75
|
+
`SRC_DIR=` line must exist; anything else means the upstream script
|
|
76
|
+
changed shape and we refuse rather than guess.
|
|
77
|
+
"""
|
|
78
|
+
patched, count = _SRC_DIR_RE.subn('SRC_DIR="${PDKSETUP_SRC_DIR:?}"', script_text)
|
|
79
|
+
if count != 1:
|
|
80
|
+
raise RecipeError(
|
|
81
|
+
f"Expected exactly one SRC_DIR= line in the IIC install script, found "
|
|
82
|
+
f"{count}. The upstream recipe changed; pdksetup needs an update."
|
|
83
|
+
)
|
|
84
|
+
return patched
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def select_scripts(names, patterns: tuple[str, ...]) -> list[str]:
|
|
88
|
+
return sorted(n for n in names if any(fnmatch.fnmatch(n, p) for p in patterns))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def recipe_fingerprint(
|
|
92
|
+
overlay_tree: str, script_blobs: dict[str, str], env: dict[str, str]
|
|
93
|
+
) -> str:
|
|
94
|
+
"""Content fingerprint of a recipe.
|
|
95
|
+
|
|
96
|
+
Inputs are git object IDs (content hashes) and pin values, so the same
|
|
97
|
+
recipe yields the same fingerprint on any commit or branch.
|
|
98
|
+
"""
|
|
99
|
+
lines = [f"overlay {overlay_tree}"]
|
|
100
|
+
lines += [f"script {name} {sha}" for name, sha in sorted(script_blobs.items())]
|
|
101
|
+
lines += [f"pin {name}={value}" for name, value in sorted(env.items())]
|
|
102
|
+
return hashlib.sha256("\n".join(lines).encode()).hexdigest()[:16]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# --- Prerequisites ---------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def git_version() -> tuple[int, int] | None:
|
|
109
|
+
try:
|
|
110
|
+
proc = subprocess.run(["git", "--version"], capture_output=True, text=True, timeout=10, check=False
|
|
111
|
+
)
|
|
112
|
+
except (OSError, subprocess.SubprocessError):
|
|
113
|
+
return None
|
|
114
|
+
match = re.search(r"(\d+)\.(\d+)", proc.stdout or "")
|
|
115
|
+
return (int(match.group(1)), int(match.group(2))) if match else None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _runs_ok(path: str) -> tuple[bool, str]:
|
|
119
|
+
"""Run `<path> --version`; (ok, detail). Catches binaries that can't start."""
|
|
120
|
+
try:
|
|
121
|
+
proc = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=30, check=False
|
|
122
|
+
)
|
|
123
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
124
|
+
return False, str(exc)
|
|
125
|
+
if proc.returncode != 0:
|
|
126
|
+
detail = (proc.stderr or proc.stdout or "").strip().splitlines()
|
|
127
|
+
return False, f"exit {proc.returncode}: {detail[-1] if detail else 'no output'}"
|
|
128
|
+
return True, ""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def check_prereqs(which=shutil.which) -> str:
|
|
132
|
+
"""Check everything the recipe needs; return the compiler path.
|
|
133
|
+
|
|
134
|
+
Raises RecipeError listing every problem at once. Runs before anything
|
|
135
|
+
on disk is changed.
|
|
136
|
+
"""
|
|
137
|
+
if os.name == "nt":
|
|
138
|
+
raise RecipeError(
|
|
139
|
+
"This PDK's install runs a bash recipe and needs Linux or macOS. "
|
|
140
|
+
"On Windows, use WSL. Nothing was changed."
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
problems = []
|
|
144
|
+
for tool in ("bash", "python3", "gzip"):
|
|
145
|
+
if not which(tool):
|
|
146
|
+
problems.append(f"{tool} not found on PATH")
|
|
147
|
+
|
|
148
|
+
version = git_version()
|
|
149
|
+
if version is None:
|
|
150
|
+
problems.append("git not found on PATH")
|
|
151
|
+
elif version < MIN_GIT:
|
|
152
|
+
problems.append(
|
|
153
|
+
f"git {version[0]}.{version[1]} is too old; needs ≥ {MIN_GIT[0]}.{MIN_GIT[1]} "
|
|
154
|
+
"(for `git sparse-checkout set --no-cone`)"
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
compiler = next((p for p in (which(c) for c in _COMPILERS) if p), None)
|
|
158
|
+
if compiler is None:
|
|
159
|
+
problems.append(
|
|
160
|
+
"OpenVAF not found on PATH (openvaf-r or openvaf); it compiles the "
|
|
161
|
+
"BSIM-CMG model. See the README's OpenVAF install steps."
|
|
162
|
+
)
|
|
163
|
+
else:
|
|
164
|
+
ok, detail = _runs_ok(compiler)
|
|
165
|
+
if not ok:
|
|
166
|
+
problems.append(
|
|
167
|
+
f"{compiler} is on PATH but fails to run ({detail}). On Linux this is "
|
|
168
|
+
"usually the missing libLLVM 21 runtime; see the README's libLLVM recipe."
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
if problems:
|
|
172
|
+
raise RecipeError(
|
|
173
|
+
"ASAP7 install prerequisites not met (nothing was changed):\n - "
|
|
174
|
+
+ "\n - ".join(problems)
|
|
175
|
+
)
|
|
176
|
+
return compiler
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# --- Ref resolution --------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _ls_remote(repo_url: str, branch: str) -> str | None:
|
|
183
|
+
proc = subprocess.run(
|
|
184
|
+
["git", "ls-remote", repo_url, f"refs/heads/{branch}"],
|
|
185
|
+
capture_output=True, text=True, timeout=60, check=False,
|
|
186
|
+
)
|
|
187
|
+
first = (proc.stdout or "").split()
|
|
188
|
+
return first[0] if proc.returncode == 0 and first else None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def resolve_ref(recipe: IICRecipe, version: str | None) -> str:
|
|
192
|
+
"""The commit to install: an explicit sha or branch, else the pin, else the branch head."""
|
|
193
|
+
target = version or recipe.pin or recipe.branch
|
|
194
|
+
if _SHA_RE.match(target):
|
|
195
|
+
return target
|
|
196
|
+
sha = _ls_remote(recipe.repo_url, target)
|
|
197
|
+
if sha is None:
|
|
198
|
+
raise RecipeError(f"No branch '{target}' in {recipe.repo_url}.")
|
|
199
|
+
return sha
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# --- Installer -------------------------------------------------------------
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _git(clone: Path, *args: str) -> str:
|
|
206
|
+
return subprocess.run(
|
|
207
|
+
["git", "-C", str(clone), *args], capture_output=True, text=True, check=True
|
|
208
|
+
).stdout
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def local_fingerprint(clone: Path, sha: str, recipe: IICRecipe, env: dict[str, str]) -> str:
|
|
212
|
+
"""Fingerprint from a local checkout; equals the updater's API-based one."""
|
|
213
|
+
overlay_tree = _git(clone, "rev-parse", f"{sha}:{recipe.overlay}").strip()
|
|
214
|
+
blobs = {}
|
|
215
|
+
for line in _git(clone, "ls-tree", sha, f"{recipe.script_dir}/").splitlines():
|
|
216
|
+
meta, path = line.split("\t", 1)
|
|
217
|
+
_mode, kind, obj = meta.split()
|
|
218
|
+
name = path.rsplit("/", 1)[-1]
|
|
219
|
+
if kind == "blob":
|
|
220
|
+
blobs[name] = obj
|
|
221
|
+
selected = {n: blobs[n] for n in select_scripts(blobs, recipe.script_patterns)}
|
|
222
|
+
return recipe_fingerprint(overlay_tree, selected, env)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _read_checkout(clone: Path, recipe: IICRecipe) -> tuple[str, str, str, str]:
|
|
226
|
+
"""(full sha, script text, Dockerfile text, fingerprint) of the checkout."""
|
|
227
|
+
sha = _git(clone, "rev-parse", "HEAD").strip()
|
|
228
|
+
script_text = (clone / recipe.script).read_text()
|
|
229
|
+
docker_text = (clone / recipe.dockerfile).read_text()
|
|
230
|
+
fp = local_fingerprint(clone, sha, recipe, script_env(docker_text, script_text))
|
|
231
|
+
return sha, script_text, docker_text, fp
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _with_git_config(env: dict[str, str], key: str, value: str) -> dict[str, str]:
|
|
235
|
+
"""Append one setting via git's GIT_CONFIG_COUNT mechanism (git ≥ 2.31).
|
|
236
|
+
|
|
237
|
+
Affects only the child process, and keeps any settings the user already
|
|
238
|
+
passes this way (e.g. a proxy).
|
|
239
|
+
"""
|
|
240
|
+
count = int(env.get("GIT_CONFIG_COUNT", "0") or 0)
|
|
241
|
+
return {
|
|
242
|
+
**env,
|
|
243
|
+
"GIT_CONFIG_COUNT": str(count + 1),
|
|
244
|
+
f"GIT_CONFIG_KEY_{count}": key,
|
|
245
|
+
f"GIT_CONFIG_VALUE_{count}": value,
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _swap_into_place(new: Path, dest: Path, work: Path) -> None:
|
|
250
|
+
"""Replace `dest` with `new` by rename; restore the old one on failure."""
|
|
251
|
+
if dest.exists() or dest.is_symlink():
|
|
252
|
+
previous = work / "previous"
|
|
253
|
+
os.rename(dest, previous)
|
|
254
|
+
try:
|
|
255
|
+
os.rename(new, dest)
|
|
256
|
+
except OSError:
|
|
257
|
+
os.rename(previous, dest)
|
|
258
|
+
raise
|
|
259
|
+
else:
|
|
260
|
+
os.rename(new, dest)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class IICRecipeInstaller:
|
|
264
|
+
def install(
|
|
265
|
+
self,
|
|
266
|
+
pdk_name: str,
|
|
267
|
+
*,
|
|
268
|
+
recipe: IICRecipe,
|
|
269
|
+
pdk_root: Path,
|
|
270
|
+
artifacts: tuple[str, ...],
|
|
271
|
+
version: str | None = None,
|
|
272
|
+
) -> tuple[str, str]:
|
|
273
|
+
"""Build and install; return (short commit, recipe fingerprint)."""
|
|
274
|
+
pdk_root = Path(pdk_root)
|
|
275
|
+
dest = pdk_root / recipe.output_dir
|
|
276
|
+
if (dest / ".git").exists():
|
|
277
|
+
raise RecipeError(
|
|
278
|
+
f"{dest} is a git clone from an older pdksetup (the raw upstream "
|
|
279
|
+
f"{pdk_name} checkout). Remove it with `pdk uninstall {pdk_name}`, "
|
|
280
|
+
f"then install again. Nothing was changed."
|
|
281
|
+
)
|
|
282
|
+
compiler = check_prereqs()
|
|
283
|
+
sha = resolve_ref(recipe, version)
|
|
284
|
+
|
|
285
|
+
pdk_root.mkdir(parents=True, exist_ok=True)
|
|
286
|
+
work = Path(tempfile.mkdtemp(dir=pdk_root, prefix=".pdksetup_tmp_"))
|
|
287
|
+
try:
|
|
288
|
+
clone = work / "iic"
|
|
289
|
+
run(["git", "clone", "--quiet", "--filter=blob:none", "--no-checkout",
|
|
290
|
+
recipe.repo_url, str(clone)])
|
|
291
|
+
run(["git", "-C", str(clone), "sparse-checkout", "set", "--no-cone",
|
|
292
|
+
f"/{recipe.script_dir}/", f"/{recipe.overlay}/", f"/{recipe.dockerfile}"])
|
|
293
|
+
try:
|
|
294
|
+
run(["git", "-C", str(clone), "checkout", "--quiet", sha])
|
|
295
|
+
except subprocess.CalledProcessError as exc:
|
|
296
|
+
raise RecipeError(
|
|
297
|
+
f"Commit {sha[:8]} is not in {recipe.repo_url} (upstream history "
|
|
298
|
+
f"may have been rewritten). Try `pdk install {pdk_name} "
|
|
299
|
+
f"--version {recipe.branch}`, or upgrade pdksetup. Nothing was changed."
|
|
300
|
+
) from exc
|
|
301
|
+
full_sha, script_text, docker_text, fingerprint = _read_checkout(clone, recipe)
|
|
302
|
+
|
|
303
|
+
# The patched copy sits next to the original: the script finds its
|
|
304
|
+
# helpers and overlay relative to its own location.
|
|
305
|
+
script = clone / recipe.script
|
|
306
|
+
patched = script.with_name(script.stem + ".pdksetup" + script.suffix)
|
|
307
|
+
patched.write_text(patch_src_dir(script_text))
|
|
308
|
+
|
|
309
|
+
shim = work / "tools" / "openvaf" / "bin" / "openvaf"
|
|
310
|
+
shim.parent.mkdir(parents=True)
|
|
311
|
+
shim.write_text('#!/bin/sh\nexec "$PDKSETUP_OPENVAF" "$@"\n')
|
|
312
|
+
shim.chmod(0o755)
|
|
313
|
+
|
|
314
|
+
stage = work / "root"
|
|
315
|
+
stage.mkdir()
|
|
316
|
+
env = {
|
|
317
|
+
**os.environ,
|
|
318
|
+
**script_env(docker_text, script_text),
|
|
319
|
+
"PDK_ROOT": str(stage),
|
|
320
|
+
"TOOLS": str(work / "tools"),
|
|
321
|
+
"PDKSETUP_SRC_DIR": str(work / "src"),
|
|
322
|
+
"PDKSETUP_OPENVAF": compiler,
|
|
323
|
+
}
|
|
324
|
+
# The script checks out commits by sha; git's detached-HEAD
|
|
325
|
+
# advice would print a paragraph per source repo.
|
|
326
|
+
env = _with_git_config(env, "advice.detachedHead", "false")
|
|
327
|
+
print(
|
|
328
|
+
f"Building {pdk_name} from IIC-OSIC-TOOLS {full_sha[:8]} "
|
|
329
|
+
f"(about a minute; compiles BSIM-CMG with {Path(compiler).name})...",
|
|
330
|
+
flush=True,
|
|
331
|
+
)
|
|
332
|
+
run(["bash", str(patched)], env=env, cwd=str(work))
|
|
333
|
+
|
|
334
|
+
built = stage / recipe.output_dir
|
|
335
|
+
missing = [a for a in artifacts if not (built / a).exists()]
|
|
336
|
+
if missing:
|
|
337
|
+
raise RecipeError(
|
|
338
|
+
"The IIC recipe finished but these files are missing: "
|
|
339
|
+
+ ", ".join(missing) + ". Nothing was changed."
|
|
340
|
+
)
|
|
341
|
+
_swap_into_place(built, dest, work)
|
|
342
|
+
finally:
|
|
343
|
+
shutil.rmtree(work, ignore_errors=True)
|
|
344
|
+
return full_sha[:8], fingerprint
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# --- Remote fingerprint (for check-updates) --------------------------------
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def remote_fingerprint(recipe: IICRecipe, get_json) -> tuple[str, str]:
|
|
351
|
+
"""(short head sha, fingerprint) of `recipe.branch`, via the GitHub API.
|
|
352
|
+
|
|
353
|
+
`get_json(path)` returns the decoded JSON of `GET /repos/<repo>/<path>`.
|
|
354
|
+
Uses the same object IDs as `local_fingerprint`, so they agree by
|
|
355
|
+
construction for identical content.
|
|
356
|
+
"""
|
|
357
|
+
ref = f"?ref={recipe.branch}"
|
|
358
|
+
head = get_json(f"commits/{recipe.branch}")["sha"]
|
|
359
|
+
|
|
360
|
+
parent, overlay_name = recipe.overlay.rsplit("/", 1)
|
|
361
|
+
overlay_tree = next(
|
|
362
|
+
e["sha"] for e in get_json(f"contents/{parent}{ref}")
|
|
363
|
+
if e["name"] == overlay_name and e["type"] == "dir"
|
|
364
|
+
)
|
|
365
|
+
blobs = {
|
|
366
|
+
e["name"]: e["sha"] for e in get_json(f"contents/{recipe.script_dir}{ref}")
|
|
367
|
+
if e["type"] == "file"
|
|
368
|
+
}
|
|
369
|
+
selected = {n: blobs[n] for n in select_scripts(blobs, recipe.script_patterns)}
|
|
370
|
+
|
|
371
|
+
def text(path: str) -> str:
|
|
372
|
+
return base64.b64decode(get_json(f"contents/{path}{ref}")["content"]).decode()
|
|
373
|
+
|
|
374
|
+
env = script_env(text(recipe.dockerfile), text(recipe.script))
|
|
375
|
+
return head[:8], recipe_fingerprint(overlay_tree, selected, env)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from pdksetup.installers.base import run
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class VolareInstaller:
|
|
7
|
+
def install(self, pdk_name: str, *, pdk_root: Path, version: str | None) -> str:
|
|
8
|
+
if version is None:
|
|
9
|
+
version = self._latest_version(pdk_name, pdk_root)
|
|
10
|
+
run(
|
|
11
|
+
["volare", "fetch", "--pdk", pdk_name, "--pdk-root", str(pdk_root), version],
|
|
12
|
+
check=True,
|
|
13
|
+
)
|
|
14
|
+
run(
|
|
15
|
+
["volare", "enable", "--pdk", pdk_name, "--pdk-root", str(pdk_root), version],
|
|
16
|
+
check=True,
|
|
17
|
+
)
|
|
18
|
+
return version
|
|
19
|
+
|
|
20
|
+
def _latest_version(self, pdk_name: str, pdk_root: Path) -> str:
|
|
21
|
+
versions = self.list_versions(pdk_name, pdk_root=pdk_root)
|
|
22
|
+
if not versions:
|
|
23
|
+
raise RuntimeError(f"No versions found for {pdk_name}")
|
|
24
|
+
return versions[0]
|
|
25
|
+
|
|
26
|
+
def list_versions(self, pdk_name: str, *, pdk_root: Path) -> list[str]:
|
|
27
|
+
result = subprocess.run(
|
|
28
|
+
["volare", "ls-remote", "--pdk", pdk_name, "--pdk-root", str(pdk_root)],
|
|
29
|
+
check=True,
|
|
30
|
+
capture_output=True,
|
|
31
|
+
text=True,
|
|
32
|
+
)
|
|
33
|
+
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
|