-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·187 lines (136 loc) · 4.67 KB
/
Copy pathbuild.py
File metadata and controls
executable file
·187 lines (136 loc) · 4.67 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/env python3
import argparse
import hashlib
import json
import os
import platform
import shutil
import subprocess
import tarfile
from argparse import ArgumentParser
from dataclasses import dataclass
from pathlib import Path
from typing import List, AnyStr
import requests
CHEF_HOME = Path.home() / ".chef-package-manager"
@dataclass
class PackageScript:
build: Path
@dataclass
class Package:
name: str
path: Path
version: str
url: str
sha256: str
script: PackageScript
@dataclass
class Registry:
path: Path
def packages(self) -> List[Package]:
packages = [
Package(
path.name,
path,
# we add these in the next statement.
version="",
url="",
sha256="",
script=PackageScript(path / "build.sh"),
)
for path in self.path.glob("packages/*/")
]
# add data from the manifest.json file
for package in packages:
with open(str(package.path / "manifest.json"), "r") as f:
metadata = json.load(f)
package.version = metadata["version"]
package.url = metadata["url"].format(version=package.version)
package.sha256 = metadata["sha256"]
return packages
def create_arg_parser() -> ArgumentParser:
parser = argparse.ArgumentParser(
prog="build.py",
description="Build a Chef registry & compress resulting binaries",
)
parser.add_argument(
"--registry", help="path to the registry to build from", required=True
)
return parser
def sh(args: List[str], cwd: Path, env: dict[AnyStr, AnyStr] | None = None) -> None:
subprocess.run(
args,
cwd=str(cwd),
env=env,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def bootstrap() -> None:
if not CHEF_HOME.exists():
CHEF_HOME.mkdir()
for subpath in ["tmp", "installed", "dist"]:
if not (CHEF_HOME / subpath).exists():
(CHEF_HOME / subpath).mkdir()
def cleanup() -> None:
shutil.rmtree(str(CHEF_HOME))
def verify(path: Path, checksum: str) -> bool:
hasher = hashlib.sha256()
with open(path, "rb") as f:
hasher.update(f.read())
return hasher.hexdigest() == checksum
def download(package: Package) -> Path:
r = requests.get(package.url)
try:
r.raise_for_status()
except Exception as e:
raise e
filename = package.url.split("/")[-1]
path = CHEF_HOME / "tmp" / filename
with open(str(path), "wb") as f:
f.write(r.content)
if not verify(path, package.sha256):
raise ValueError("Failed to verify the integrity of the downloaded file!")
return path
def unpack(path: Path) -> Path:
if "".join(path.suffixes) == ".tar.gz" or path.suffix == ".tgz":
with tarfile.open(str(path), "r:gz") as tar:
extracted_dirname = tar.getnames()[0]
tar.extractall(path=path.parent, filter="data")
return path.parent / extracted_dirname
raise ValueError("Bad archive to unpack!")
def build(package: Package, unpacked: Path) -> Path:
env = os.environ.copy()
env["PACKAGE_NAME"] = package.name
env["CHEF_HOME"] = str(CHEF_HOME)
env["OS"] = "LINUX" if platform.system() == "Linux" else "MACOS"
# yes, I know I can use chmod with pure Python, but this solution is less complicated.
sh(["chmod", "+x", str(package.script.build)], cwd=CHEF_HOME)
sh([str(package.script.build)], cwd=unpacked, env=env)
return CHEF_HOME / "installed" / package.name
def pack(source: Path, destination: Path) -> None:
# creating tar files in pure Python is unnecessarily complicated.
sh(["tar", "-czf", str(destination), str(source)], cwd=CHEF_HOME)
def main() -> None:
if CHEF_HOME.exists():
cleanup()
bootstrap()
parsed = create_arg_parser().parse_args()
registry = Registry(path=Path(parsed.registry).absolute())
packages = registry.packages()
print(f"System: {platform.system()} {platform.machine()}")
for package in packages:
print(f"==> Downloading '{package.name}'")
saved = download(package)
print(f"==> Unpacking '{package.name}'...")
unpacked = unpack(saved)
print(f"==> Building '{package.name}'")
built = build(package, unpacked)
print(f"==> Packing '{package.name}'")
pack(built, CHEF_HOME / "dist" / f"{package.name}-{package.version}.tgz")
print(f"==> Finished building '{package.name}'")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"==> FATAL: {e}")
cleanup()