ciel 0.21.0.dev0__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.
@@ -0,0 +1,220 @@
1
+ # Copyright 2022 Efabless Corporation
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import os
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ from typing import Optional
19
+
20
+ from rich.progress import Progress
21
+
22
+ from ..common import mkdirp
23
+
24
+
25
+ class Repository(object):
26
+ @classmethod
27
+ def from_path(Self, path):
28
+ name = os.path.basename(path)
29
+ url = subprocess.check_output(
30
+ ["git", "remote", "get-url", "origin"], stderr=subprocess.PIPE
31
+ ).strip()
32
+
33
+ remote_branch_info = open(
34
+ os.path.join(path, ".git", "refs", "remotes", "origin", "HEAD")
35
+ ).read()
36
+ remote_branch = os.path.basename(remote_branch_info)
37
+
38
+ return Self(name, url, path, remote_branch)
39
+
40
+ def __init__(self, name, url, path, default_branch="main"):
41
+ path = os.path.abspath(path)
42
+
43
+ self.name = name
44
+ self.url = url
45
+ self.path = path
46
+ self.default_branch = default_branch
47
+
48
+ def clone_if_not_exist(self, callback=None):
49
+ if os.path.exists(self.path):
50
+ self.pristine()
51
+ self.pull(callback)
52
+ else:
53
+ self.clone(callback)
54
+
55
+ def clone(self, callback=None):
56
+ try:
57
+ shutil.rmtree(self.path)
58
+ except FileNotFoundError:
59
+ pass
60
+
61
+ callback(0, f"Cloning {self.name} to {self.path}…")
62
+
63
+ process = subprocess.Popen(
64
+ ["git", "clone", "--progress", self.url, self.path],
65
+ stdout=subprocess.PIPE,
66
+ stderr=subprocess.PIPE,
67
+ )
68
+ assert process.stderr is not None
69
+
70
+ ro_rx = re.compile(r"Receiving objects:\s*(\d+)%")
71
+
72
+ # Python Moment
73
+ buffer = ""
74
+ while True:
75
+ bytes_read = process.stderr.read(1)
76
+ if len(bytes_read) == 0:
77
+ break
78
+ char_read = bytes_read.decode("utf8")
79
+ if char_read in ["\n", "\r"]:
80
+ match = ro_rx.search(buffer)
81
+ if match is not None:
82
+ if callback is not None:
83
+ callback(int(match[1]))
84
+ buffer = ""
85
+ else:
86
+ buffer += char_read
87
+
88
+ process.wait()
89
+
90
+ def pristine(self):
91
+ subprocess.check_output(
92
+ ["git", "clean", "-fdX"], cwd=self.path, stderr=subprocess.PIPE
93
+ )
94
+
95
+ subprocess.check_output(
96
+ ["git", "reset", "--hard", "HEAD"], cwd=self.path, stderr=subprocess.PIPE
97
+ )
98
+
99
+ def pull(self, callback=None):
100
+ subprocess.check_output(
101
+ ["git", "checkout", "-f", self.default_branch],
102
+ cwd=self.path,
103
+ stderr=subprocess.PIPE,
104
+ )
105
+ process = subprocess.Popen(
106
+ ["git", "pull", "--no-recurse-submodules", "--progress"],
107
+ cwd=self.path,
108
+ stdout=subprocess.PIPE,
109
+ stderr=subprocess.PIPE,
110
+ )
111
+ assert process.stderr is not None
112
+ callback(0, f"Updating {self.name} at {self.path}…")
113
+
114
+ ro_rx = re.compile(r"Receiving objects:\s*(\d+)%")
115
+
116
+ # Python Moment #2
117
+ buffer = ""
118
+ while True:
119
+ bytes_read = process.stderr.read(1)
120
+ if len(bytes_read) == 0:
121
+ break
122
+ char_read = bytes_read.decode("utf8")
123
+ if char_read in ["\n", "\r"]:
124
+ match = ro_rx.search(buffer)
125
+ if match is not None:
126
+ if callback is not None:
127
+ callback(int(match[1]))
128
+ buffer = ""
129
+ else:
130
+ buffer += char_read
131
+
132
+ process.wait()
133
+ if callback is not None:
134
+ callback(100)
135
+
136
+ def checkout_commit(self, commit: str):
137
+ subprocess.check_output(
138
+ ["git", "checkout", "-f", self.default_branch],
139
+ cwd=self.path,
140
+ stderr=subprocess.PIPE,
141
+ )
142
+ try:
143
+ subprocess.check_output(
144
+ ["git", "branch", "-f", "-D", "current"],
145
+ cwd=self.path,
146
+ stderr=subprocess.PIPE,
147
+ )
148
+ except Exception:
149
+ pass
150
+ subprocess.check_output(
151
+ ["git", "checkout", "-f", "-b", "current", commit],
152
+ cwd=self.path,
153
+ stderr=subprocess.PIPE,
154
+ )
155
+
156
+ def init_submodule(self, submodule: Optional[str] = None, callback=None):
157
+ cmd = ["git", "submodule", "update", "--init", "--progress"]
158
+ if submodule is not None:
159
+ cmd.append(submodule)
160
+ process = subprocess.Popen(
161
+ cmd,
162
+ stdout=subprocess.PIPE,
163
+ stderr=subprocess.PIPE,
164
+ cwd=self.path,
165
+ )
166
+
167
+ ro_rx = re.compile(r"Receiving objects:\s*(\d+)%")
168
+
169
+ assert process.stderr is not None, "Process doesn't have a stderr channel"
170
+
171
+ # Python Moment #3
172
+ buffer = ""
173
+ while True:
174
+ bytes_read = process.stderr.read(1)
175
+ if len(bytes_read) == 0:
176
+ break
177
+ char_read = bytes_read.decode("utf8")
178
+ if char_read in ["\n", "\r"]:
179
+ match = ro_rx.search(buffer)
180
+ if match is not None:
181
+ if callback is not None:
182
+ callback(int(match[1]))
183
+ buffer = ""
184
+ else:
185
+ buffer += char_read
186
+
187
+ process.wait()
188
+
189
+
190
+ class GitMultiClone(object):
191
+ progress: Progress
192
+
193
+ def __init__(self, folder, progress):
194
+ super().__init__()
195
+ self.folder = os.path.abspath(folder)
196
+ mkdirp(self.folder)
197
+ self.progress = progress
198
+
199
+ def clone(
200
+ self, repo_url: str, commit: str, default_branch: str = "main"
201
+ ) -> Repository:
202
+ current_task = self.progress.add_task("", total=100)
203
+ name = os.path.basename(repo_url)
204
+ path = os.path.join(self.folder, name)
205
+ r = Repository(name, repo_url, path, default_branch=default_branch)
206
+ r.clone_if_not_exist(
207
+ lambda x, y=None: self.progress.update(
208
+ current_task, completed=x, description=y
209
+ )
210
+ )
211
+ r.checkout_commit(commit)
212
+ return r
213
+
214
+ def clone_submodule(self, repo: Repository, submodule: str):
215
+ current_task = self.progress.add_task(
216
+ f"Updating submodule {submodule}…", total=100
217
+ )
218
+ repo.init_submodule(
219
+ submodule, lambda x: self.progress.update(current_task, completed=x)
220
+ )
@@ -0,0 +1,148 @@
1
+ # Copyright 2022-2023 Efabless Corporation
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ from datetime import datetime
18
+ from typing import Optional, List, Tuple, Dict
19
+ from concurrent.futures import ThreadPoolExecutor
20
+
21
+ from rich.console import Console
22
+ from rich.progress import Progress
23
+
24
+ from .git_multi_clone import GitMultiClone
25
+ from ..families import Family
26
+ from ..github import ihp_repo
27
+ from ..common import (
28
+ Version,
29
+ get_cielo_dir,
30
+ mkdirp,
31
+ )
32
+
33
+
34
+ def get_ihp(
35
+ version, build_directory, jobs=1, repo_path=None
36
+ ) -> Tuple[str, Optional[str], Optional[str]]:
37
+ try:
38
+ console = Console()
39
+
40
+ if repo_path is None:
41
+ with Progress() as progress:
42
+ with ThreadPoolExecutor(max_workers=jobs) as executor:
43
+ gmc = GitMultiClone(build_directory, progress)
44
+ ihp_future = executor.submit(
45
+ GitMultiClone.clone,
46
+ gmc,
47
+ ihp_repo.link,
48
+ version,
49
+ )
50
+ repo = ihp_future.result()
51
+ current_task = progress.add_task("Updating submodules…", total=100)
52
+ repo.init_submodule(
53
+ callback=lambda x: progress.update(current_task, completed=x)
54
+ )
55
+ repo_path = repo.path
56
+ console.log(f"Done fetching {ihp_repo.name}.")
57
+ else:
58
+ console.log(f"Using IHP-Open-PDK at {repo_path} unaltered.")
59
+
60
+ return repo_path
61
+
62
+ except subprocess.CalledProcessError as e:
63
+ print(e)
64
+ print(e.stderr)
65
+ exit(-1)
66
+
67
+
68
+ def build_ihp(build_directory, ihp_path):
69
+ # """Build"""
70
+ try:
71
+ shutil.rmtree(os.path.join(build_directory, "ihp-sg13g2"))
72
+ except FileNotFoundError:
73
+ pass
74
+ shutil.copytree(
75
+ os.path.join(ihp_path, "ihp-sg13g2"),
76
+ os.path.join(build_directory, "ihp-sg13g2"),
77
+ ignore=lambda dir, files: (
78
+ files if ".git" in os.path.split(dir) else [".git", ".DS_Store"]
79
+ ),
80
+ )
81
+
82
+
83
+ def install_ihp(build_directory, pdk_root, version):
84
+ console = Console()
85
+ with console.status("Adding build to list of installed versions…"):
86
+ ihp_sg13g2_family = Family.by_name["ihp_sg13g2"]
87
+
88
+ version_directory = Version(version, "ihp_sg13g2").get_dir(pdk_root)
89
+ if (
90
+ os.path.exists(version_directory)
91
+ and len(os.listdir(version_directory)) != 0
92
+ ):
93
+ backup_path = version_directory
94
+ it = 0
95
+ while os.path.exists(backup_path) and len(os.listdir(backup_path)) != 0:
96
+ it += 1
97
+ backup_path = Version(f"{version}.bk{it}", "ihp_sg13g2").get_dir(
98
+ pdk_root
99
+ )
100
+ console.log(
101
+ f"Build already found at {version_directory}, moving to {backup_path}…"
102
+ )
103
+ shutil.move(version_directory, backup_path)
104
+
105
+ console.log("Copying…")
106
+ mkdirp(version_directory)
107
+
108
+ for variant in ihp_sg13g2_family.variants:
109
+ variant_build_path = os.path.join(build_directory, variant)
110
+ variant_install_path = os.path.join(version_directory, variant)
111
+ if os.path.isdir(variant_build_path):
112
+ shutil.copytree(variant_build_path, variant_install_path)
113
+
114
+ console.log("Done.")
115
+
116
+
117
+ def build(
118
+ pdk_root: str,
119
+ version: str,
120
+ jobs: int = 1,
121
+ clear_build_artifacts: bool = True,
122
+ include_libraries: Optional[List[str]] = None,
123
+ using_repos: Optional[Dict[str, str]] = None,
124
+ ):
125
+ console = Console()
126
+ if include_libraries is not None:
127
+ console.log(
128
+ "Note: all libraries will be acquired as part of the trivial PDK build."
129
+ )
130
+
131
+ if using_repos is None:
132
+ using_repos = {}
133
+
134
+ build_directory = os.path.join(
135
+ get_cielo_dir(pdk_root, "ihp_sg13g2"), "build", version
136
+ )
137
+ timestamp = datetime.now().strftime("build_ihp-sg13g2-%Y-%m-%d-%H-%M-%S")
138
+ log_dir = os.path.join(build_directory, "logs", timestamp)
139
+ mkdirp(log_dir)
140
+
141
+ console.log(f"Logging to '{log_dir}'…")
142
+
143
+ ihp_path = get_ihp(version, build_directory, jobs, using_repos.get("ihp"))
144
+ build_ihp(build_directory, ihp_path)
145
+ install_ihp(build_directory, pdk_root, version)
146
+
147
+ if clear_build_artifacts:
148
+ shutil.rmtree(build_directory)