fastled 1.3.10__py3-none-any.whl → 1.3.12__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.
@@ -1,332 +1,316 @@
1
- import subprocess
2
- import sys
3
- import time
4
- import traceback
5
- import warnings
6
- from datetime import datetime, timezone
7
- from pathlib import Path
8
-
9
- import httpx
10
-
11
- from fastled.docker_manager import (
12
- DISK_CACHE,
13
- Container,
14
- DockerManager,
15
- RunningContainer,
16
- Volume,
17
- )
18
- from fastled.settings import DEFAULT_CONTAINER_NAME, IMAGE_NAME, SERVER_PORT
19
- from fastled.sketch import looks_like_fastled_repo
20
- from fastled.types import BuildMode, CompileResult, CompileServerError
21
- from fastled.util import port_is_free
22
-
23
- SERVER_OPTIONS = [
24
- "--allow-shutdown", # Allow the server to be shut down without a force kill.
25
- "--no-auto-update", # Don't auto live updates from the git repo.
26
- ]
27
-
28
- LOCAL_DOCKER_ENV = {
29
- "ONLY_QUICK_BUILDS": "0" # When running docker always allow release and debug.
30
- }
31
-
32
-
33
- def _try_get_fastled_src(path: Path) -> Path | None:
34
- fastled_src_dir: Path | None = None
35
- if looks_like_fastled_repo(path):
36
- print(
37
- "Looks like a FastLED repo, using it as the source directory and mapping it into the server."
38
- )
39
- fastled_src_dir = path / "src"
40
- return fastled_src_dir
41
- return None
42
-
43
-
44
- class CompileServerImpl:
45
- def __init__(
46
- self,
47
- interactive: bool = False,
48
- auto_updates: bool | None = None,
49
- mapped_dir: Path | None = None,
50
- auto_start: bool = True,
51
- container_name: str | None = None,
52
- remove_previous: bool = False,
53
- ) -> None:
54
- container_name = container_name or DEFAULT_CONTAINER_NAME
55
- if interactive and not mapped_dir:
56
- raise ValueError(
57
- "Interactive mode requires a mapped directory point to a sketch"
58
- )
59
- if not interactive and mapped_dir:
60
- warnings.warn(
61
- f"Mapped directory {mapped_dir} is ignored in non-interactive mode"
62
- )
63
- self.container_name = container_name
64
- self.mapped_dir = mapped_dir
65
- self.docker = DockerManager()
66
- self.fastled_src_dir: Path | None = _try_get_fastled_src(Path(".").resolve())
67
- self.interactive = interactive
68
- self.running_container: RunningContainer | None = None
69
- self.auto_updates = auto_updates
70
- self.remove_previous = remove_previous
71
- self._port = 0 # 0 until compile server is started
72
- if auto_start:
73
- self.start()
74
-
75
- def start(self, wait_for_startup=True) -> None:
76
- if not DockerManager.is_docker_installed():
77
- raise CompileServerError("Docker is not installed")
78
- if self._port != 0:
79
- warnings.warn("Server has already been started")
80
- self._port = self._start()
81
- if wait_for_startup:
82
- ok = self.wait_for_startup()
83
- if not ok:
84
- if self.interactive:
85
- print("Exited from container.")
86
- sys.exit(0)
87
- return
88
- raise CompileServerError("Server did not start")
89
- if not self.interactive:
90
- msg = f"# FastLED Compile Server started at {self.url()} #"
91
- print("\n" + "#" * len(msg))
92
- print(msg)
93
- print("#" * len(msg) + "\n")
94
-
95
- def web_compile(
96
- self,
97
- directory: Path | str,
98
- build_mode: BuildMode = BuildMode.QUICK,
99
- profile: bool = False,
100
- ) -> CompileResult:
101
- from fastled.web_compile import web_compile # avoid circular import
102
-
103
- if not self._port:
104
- raise RuntimeError("Server has not been started yet")
105
- if not self.ping():
106
- raise RuntimeError("Server is not running")
107
- out: CompileResult = web_compile(
108
- directory, host=self.url(), build_mode=build_mode, profile=profile
109
- )
110
- return out
111
-
112
- def project_init(
113
- self, example: str | None = None, outputdir: Path | None = None
114
- ) -> None:
115
- from fastled.project_init import project_init # avoid circular import
116
-
117
- project_init(example=example, outputdir=outputdir)
118
-
119
- @property
120
- def running(self) -> tuple[bool, Exception | None]:
121
- if not self._port:
122
- return False, Exception("Docker hasn't been initialzed with a port yet")
123
- if not DockerManager.is_docker_installed():
124
- return False, Exception("Docker is not installed")
125
- docker_running, err = self.docker.is_running()
126
- if not docker_running:
127
- IS_MAC = sys.platform == "darwin"
128
- if IS_MAC:
129
- if "FileNotFoundError" in str(err):
130
- traceback.print_exc()
131
- print("\n\nNone fatal debug print for MacOS\n")
132
- return False, err
133
- ok: bool = self.docker.is_container_running(self.container_name)
134
- if ok:
135
- return True, None
136
- else:
137
- return False, Exception("Docker is not running")
138
-
139
- def using_fastled_src_dir_volume(self) -> bool:
140
- out = self.fastled_src_dir is not None
141
- if out:
142
- print(f"Using FastLED source directory: {self.fastled_src_dir}")
143
- return out
144
-
145
- def port(self) -> int:
146
- if self._port == 0:
147
- warnings.warn("Server has not been started yet")
148
- return self._port
149
-
150
- def url(self) -> str:
151
- if self._port == 0:
152
- warnings.warn("Server has not been started yet")
153
- return f"http://localhost:{self._port}"
154
-
155
- def ping(self) -> bool:
156
- try:
157
- response = httpx.get(
158
- f"http://localhost:{self._port}", follow_redirects=True
159
- )
160
- if response.status_code < 400:
161
- return True
162
- except KeyboardInterrupt:
163
- raise
164
- except Exception:
165
- pass
166
- return False
167
-
168
- # by default this is automatically called by the constructor, unless
169
- # auto_start is set to False.
170
- def wait_for_startup(self, timeout: int = 100) -> bool:
171
- """Wait for the server to start up."""
172
- start_time = time.time()
173
- while time.time() - start_time < timeout:
174
- # ping the server to see if it's up
175
- if not self._port:
176
- return False
177
- # use httpx to ping the server
178
- # if successful, return True
179
- if self.ping():
180
- return True
181
- time.sleep(0.1)
182
- if not self.docker.is_container_running(self.container_name):
183
- return False
184
- return False
185
-
186
- def _start(self) -> int:
187
- print("Compiling server starting")
188
-
189
- # Ensure Docker is running
190
- if not self.docker.is_running():
191
- if not self.docker.start():
192
- print("Docker could not be started. Exiting.")
193
- raise RuntimeError("Docker could not be started. Exiting.")
194
- now = datetime.now(timezone.utc)
195
- now_str = now.strftime("%Y-%m-%d")
196
-
197
- upgrade = False
198
- if self.auto_updates is None:
199
- prev_date_str = DISK_CACHE.get("last-update")
200
- if prev_date_str != now_str:
201
- print("One day has passed, checking docker for updates")
202
- upgrade = True
203
- else:
204
- upgrade = self.auto_updates
205
- updated = self.docker.validate_or_download_image(
206
- image_name=IMAGE_NAME, tag="latest", upgrade=upgrade
207
- )
208
- DISK_CACHE.put("last-update", now_str)
209
- INTERNAL_DOCKER_PORT = 80
210
-
211
- print("Docker image now validated")
212
- port = SERVER_PORT
213
- if self.interactive:
214
- server_command = ["/bin/bash"]
215
- else:
216
- server_command = ["python", "/js/run.py", "server"] + SERVER_OPTIONS
217
- if self.interactive:
218
- print("Disabling port forwarding in interactive mode")
219
- ports = {}
220
- else:
221
- ports = {INTERNAL_DOCKER_PORT: port}
222
- volumes = []
223
- if self.fastled_src_dir:
224
- print(
225
- f"Mounting FastLED source directory {self.fastled_src_dir} into container /host/fastled/src"
226
- )
227
- volumes.append(
228
- Volume(
229
- host_path=str(self.fastled_src_dir),
230
- container_path="/host/fastled/src",
231
- mode="ro",
232
- )
233
- )
234
- if self.interactive:
235
- # add the mapped directory to the container
236
- print(f"Mounting {self.mapped_dir} into container /mapped")
237
- assert self.mapped_dir is not None
238
- dir_name = self.mapped_dir.name
239
- if not volumes:
240
- volumes = []
241
- volumes.append(
242
- Volume(
243
- host_path=str(self.mapped_dir),
244
- container_path=f"/mapped/{dir_name}",
245
- mode="rw",
246
- )
247
- )
248
- if self.fastled_src_dir is not None:
249
- # to allow for interactive compilation
250
- # interactive_sources = list(INTERACTIVE_SOURCES)
251
- interactive_sources: list[tuple[Path, str]] = []
252
- init_runtime_py = (
253
- Path(self.fastled_src_dir)
254
- / ".."
255
- / ".."
256
- / "fastled-wasm"
257
- / "compiler"
258
- / "init_runtime.py"
259
- )
260
- if init_runtime_py.exists():
261
- # fastled-wasm is in a sister directory, mapping this in to the container.
262
- mapping = (
263
- init_runtime_py,
264
- "/js/init_runtime.py",
265
- )
266
- interactive_sources.append(mapping)
267
-
268
- src_host: Path
269
- dst_container: str
270
- for src_host, dst_container in interactive_sources:
271
- src_path = Path(src_host).absolute()
272
- if src_path.exists():
273
- print(f"Mounting {src_host} into container")
274
- volumes.append(
275
- Volume(
276
- host_path=str(src_path),
277
- container_path=dst_container,
278
- mode="rw",
279
- )
280
- )
281
- else:
282
- print(f"Could not find {src_path}")
283
-
284
- cmd_str = subprocess.list2cmdline(server_command)
285
- if not self.interactive:
286
- container: Container = self.docker.run_container_detached(
287
- image_name=IMAGE_NAME,
288
- tag="latest",
289
- container_name=self.container_name,
290
- command=cmd_str,
291
- ports=ports,
292
- volumes=volumes,
293
- remove_previous=self.interactive or self.remove_previous or updated,
294
- environment=LOCAL_DOCKER_ENV,
295
- )
296
- self.running_container = self.docker.attach_and_run(container)
297
- assert self.running_container is not None, "Container should be running"
298
- print("Compile server starting")
299
- return port
300
- else:
301
- client_port_mapped = INTERNAL_DOCKER_PORT in ports
302
- free_port = port_is_free(INTERNAL_DOCKER_PORT)
303
- if client_port_mapped and free_port:
304
- warnings.warn(
305
- f"Can't expose port {INTERNAL_DOCKER_PORT}, disabling port forwarding in interactive mode"
306
- )
307
- ports = {}
308
- self.docker.run_container_interactive(
309
- image_name=IMAGE_NAME,
310
- tag="latest",
311
- container_name=self.container_name,
312
- command=cmd_str,
313
- ports=ports,
314
- volumes=volumes,
315
- environment=LOCAL_DOCKER_ENV,
316
- )
317
-
318
- print("Exiting interactive mode")
319
- return port
320
-
321
- def process_running(self) -> bool:
322
- return self.docker.is_container_running(self.container_name)
323
-
324
- def stop(self) -> None:
325
- if self.docker.is_suspended:
326
- return
327
- if self.running_container:
328
- self.running_container.detach()
329
- self.running_container = None
330
- self.docker.suspend_container(self.container_name)
331
- self._port = 0
332
- print("Compile server stopped")
1
+ import subprocess
2
+ import sys
3
+ import time
4
+ import traceback
5
+ import warnings
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+
11
+ from fastled.docker_manager import (
12
+ DISK_CACHE,
13
+ Container,
14
+ DockerManager,
15
+ RunningContainer,
16
+ Volume,
17
+ )
18
+ from fastled.settings import DEFAULT_CONTAINER_NAME, IMAGE_NAME, SERVER_PORT
19
+ from fastled.sketch import looks_like_fastled_repo
20
+ from fastled.types import BuildMode, CompileResult, CompileServerError
21
+ from fastled.util import port_is_free
22
+
23
+ SERVER_OPTIONS = [
24
+ "--allow-shutdown", # Allow the server to be shut down without a force kill.
25
+ "--no-auto-update", # Don't auto live updates from the git repo.
26
+ ]
27
+
28
+ LOCAL_DOCKER_ENV = {
29
+ "ONLY_QUICK_BUILDS": "0" # When running docker always allow release and debug.
30
+ }
31
+
32
+
33
+ def _try_get_fastled_src(path: Path) -> Path | None:
34
+ fastled_src_dir: Path | None = None
35
+ if looks_like_fastled_repo(path):
36
+ print(
37
+ "Looks like a FastLED repo, using it as the source directory and mapping it into the server."
38
+ )
39
+ fastled_src_dir = path / "src"
40
+ return fastled_src_dir
41
+ return None
42
+
43
+
44
+ class CompileServerImpl:
45
+ def __init__(
46
+ self,
47
+ interactive: bool = False,
48
+ auto_updates: bool | None = None,
49
+ mapped_dir: Path | None = None,
50
+ auto_start: bool = True,
51
+ container_name: str | None = None,
52
+ remove_previous: bool = False,
53
+ ) -> None:
54
+ container_name = container_name or DEFAULT_CONTAINER_NAME
55
+ if interactive and not mapped_dir:
56
+ raise ValueError(
57
+ "Interactive mode requires a mapped directory point to a sketch"
58
+ )
59
+ if not interactive and mapped_dir:
60
+ warnings.warn(
61
+ f"Mapped directory {mapped_dir} is ignored in non-interactive mode"
62
+ )
63
+ self.container_name = container_name
64
+ self.mapped_dir = mapped_dir
65
+ self.docker = DockerManager()
66
+ self.fastled_src_dir: Path | None = _try_get_fastled_src(Path(".").resolve())
67
+ self.interactive = interactive
68
+ self.running_container: RunningContainer | None = None
69
+ self.auto_updates = auto_updates
70
+ self.remove_previous = remove_previous
71
+ self._port = 0 # 0 until compile server is started
72
+ if auto_start:
73
+ self.start()
74
+
75
+ def start(self, wait_for_startup=True) -> None:
76
+ if not DockerManager.is_docker_installed():
77
+ raise CompileServerError("Docker is not installed")
78
+ if self._port != 0:
79
+ warnings.warn("Server has already been started")
80
+ self._port = self._start()
81
+ if wait_for_startup:
82
+ ok = self.wait_for_startup()
83
+ if not ok:
84
+ if self.interactive:
85
+ print("Exited from container.")
86
+ sys.exit(0)
87
+ return
88
+ raise CompileServerError("Server did not start")
89
+ if not self.interactive:
90
+ msg = f"# FastLED Compile Server started at {self.url()} #"
91
+ print("\n" + "#" * len(msg))
92
+ print(msg)
93
+ print("#" * len(msg) + "\n")
94
+
95
+ def web_compile(
96
+ self,
97
+ directory: Path | str,
98
+ build_mode: BuildMode = BuildMode.QUICK,
99
+ profile: bool = False,
100
+ ) -> CompileResult:
101
+ from fastled.web_compile import web_compile # avoid circular import
102
+
103
+ if not self._port:
104
+ raise RuntimeError("Server has not been started yet")
105
+ if not self.ping():
106
+ raise RuntimeError("Server is not running")
107
+ out: CompileResult = web_compile(
108
+ directory, host=self.url(), build_mode=build_mode, profile=profile
109
+ )
110
+ return out
111
+
112
+ def project_init(
113
+ self, example: str | None = None, outputdir: Path | None = None
114
+ ) -> None:
115
+ from fastled.project_init import project_init # avoid circular import
116
+
117
+ project_init(example=example, outputdir=outputdir)
118
+
119
+ @property
120
+ def running(self) -> tuple[bool, Exception | None]:
121
+ if not self._port:
122
+ return False, Exception("Docker hasn't been initialzed with a port yet")
123
+ if not DockerManager.is_docker_installed():
124
+ return False, Exception("Docker is not installed")
125
+ docker_running, err = self.docker.is_running()
126
+ if not docker_running:
127
+ IS_MAC = sys.platform == "darwin"
128
+ if IS_MAC:
129
+ if "FileNotFoundError" in str(err):
130
+ traceback.print_exc()
131
+ print("\n\nNone fatal debug print for MacOS\n")
132
+ return False, err
133
+ ok: bool = self.docker.is_container_running(self.container_name)
134
+ if ok:
135
+ return True, None
136
+ else:
137
+ return False, Exception("Docker is not running")
138
+
139
+ def using_fastled_src_dir_volume(self) -> bool:
140
+ out = self.fastled_src_dir is not None
141
+ if out:
142
+ print(f"Using FastLED source directory: {self.fastled_src_dir}")
143
+ return out
144
+
145
+ def port(self) -> int:
146
+ if self._port == 0:
147
+ warnings.warn("Server has not been started yet")
148
+ return self._port
149
+
150
+ def url(self) -> str:
151
+ if self._port == 0:
152
+ warnings.warn("Server has not been started yet")
153
+ return f"http://localhost:{self._port}"
154
+
155
+ def ping(self) -> bool:
156
+ try:
157
+ response = httpx.get(
158
+ f"http://localhost:{self._port}", follow_redirects=True
159
+ )
160
+ if response.status_code < 400:
161
+ return True
162
+ except KeyboardInterrupt:
163
+ raise
164
+ except Exception:
165
+ pass
166
+ return False
167
+
168
+ # by default this is automatically called by the constructor, unless
169
+ # auto_start is set to False.
170
+ def wait_for_startup(self, timeout: int = 100) -> bool:
171
+ """Wait for the server to start up."""
172
+ start_time = time.time()
173
+ while time.time() - start_time < timeout:
174
+ # ping the server to see if it's up
175
+ if not self._port:
176
+ return False
177
+ # use httpx to ping the server
178
+ # if successful, return True
179
+ if self.ping():
180
+ return True
181
+ time.sleep(0.1)
182
+ if not self.docker.is_container_running(self.container_name):
183
+ return False
184
+ return False
185
+
186
+ def _start(self) -> int:
187
+ print("Compiling server starting")
188
+
189
+ # Ensure Docker is running
190
+ if not self.docker.is_running():
191
+ if not self.docker.start():
192
+ print("Docker could not be started. Exiting.")
193
+ raise RuntimeError("Docker could not be started. Exiting.")
194
+ now = datetime.now(timezone.utc)
195
+ now_str = now.strftime("%Y-%m-%d")
196
+
197
+ upgrade = False
198
+ if self.auto_updates is None:
199
+ prev_date_str = DISK_CACHE.get("last-update")
200
+ if prev_date_str != now_str:
201
+ print("One day has passed, checking docker for updates")
202
+ upgrade = True
203
+ else:
204
+ upgrade = self.auto_updates
205
+ updated = self.docker.validate_or_download_image(
206
+ image_name=IMAGE_NAME, tag="latest", upgrade=upgrade
207
+ )
208
+ DISK_CACHE.put("last-update", now_str)
209
+ INTERNAL_DOCKER_PORT = 80
210
+
211
+ print("Docker image now validated")
212
+ port = SERVER_PORT
213
+ if self.interactive:
214
+ server_command = ["/bin/bash"]
215
+ else:
216
+ server_command = ["python", "/js/run.py", "server"] + SERVER_OPTIONS
217
+ if self.interactive:
218
+ print("Disabling port forwarding in interactive mode")
219
+ ports = {}
220
+ else:
221
+ ports = {INTERNAL_DOCKER_PORT: port}
222
+ volumes = []
223
+ if self.fastled_src_dir:
224
+ print(
225
+ f"Mounting FastLED source directory {self.fastled_src_dir} into container /host/fastled/src"
226
+ )
227
+ volumes.append(
228
+ Volume(
229
+ host_path=str(self.fastled_src_dir),
230
+ container_path="/host/fastled/src",
231
+ mode="ro",
232
+ )
233
+ )
234
+ if self.interactive:
235
+ # add the mapped directory to the container
236
+ print(f"Mounting {self.mapped_dir} into container /mapped")
237
+ assert self.mapped_dir is not None
238
+ dir_name = self.mapped_dir.name
239
+ if not volumes:
240
+ volumes = []
241
+ volumes.append(
242
+ Volume(
243
+ host_path=str(self.mapped_dir),
244
+ container_path=f"/mapped/{dir_name}",
245
+ mode="rw",
246
+ )
247
+ )
248
+ if self.fastled_src_dir is not None:
249
+ # to allow for interactive compilation
250
+ # interactive_sources = list(INTERACTIVE_SOURCES)
251
+ interactive_sources: list[tuple[Path, str]] = []
252
+ src_host: Path
253
+ dst_container: str
254
+ for src_host, dst_container in interactive_sources:
255
+ src_path = Path(src_host).absolute()
256
+ if src_path.exists():
257
+ print(f"Mounting {src_host} into container")
258
+ volumes.append(
259
+ Volume(
260
+ host_path=str(src_path),
261
+ container_path=dst_container,
262
+ mode="rw",
263
+ )
264
+ )
265
+ else:
266
+ print(f"Could not find {src_path}")
267
+
268
+ cmd_str = subprocess.list2cmdline(server_command)
269
+ if not self.interactive:
270
+ container: Container = self.docker.run_container_detached(
271
+ image_name=IMAGE_NAME,
272
+ tag="latest",
273
+ container_name=self.container_name,
274
+ command=cmd_str,
275
+ ports=ports,
276
+ volumes=volumes,
277
+ remove_previous=self.interactive or self.remove_previous or updated,
278
+ environment=LOCAL_DOCKER_ENV,
279
+ )
280
+ self.running_container = self.docker.attach_and_run(container)
281
+ assert self.running_container is not None, "Container should be running"
282
+ print("Compile server starting")
283
+ return port
284
+ else:
285
+ client_port_mapped = INTERNAL_DOCKER_PORT in ports
286
+ free_port = port_is_free(INTERNAL_DOCKER_PORT)
287
+ if client_port_mapped and free_port:
288
+ warnings.warn(
289
+ f"Can't expose port {INTERNAL_DOCKER_PORT}, disabling port forwarding in interactive mode"
290
+ )
291
+ ports = {}
292
+ self.docker.run_container_interactive(
293
+ image_name=IMAGE_NAME,
294
+ tag="latest",
295
+ container_name=self.container_name,
296
+ command=cmd_str,
297
+ ports=ports,
298
+ volumes=volumes,
299
+ environment=LOCAL_DOCKER_ENV,
300
+ )
301
+
302
+ print("Exiting interactive mode")
303
+ return port
304
+
305
+ def process_running(self) -> bool:
306
+ return self.docker.is_container_running(self.container_name)
307
+
308
+ def stop(self) -> None:
309
+ if self.docker.is_suspended:
310
+ return
311
+ if self.running_container:
312
+ self.running_container.detach()
313
+ self.running_container = None
314
+ self.docker.suspend_container(self.container_name)
315
+ self._port = 0
316
+ print("Compile server stopped")