micropython-stubber 1.23.1.post1__py3-none-any.whl → 1.23.2__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.
Files changed (152) hide show
  1. {micropython_stubber-1.23.1.post1.dist-info → micropython_stubber-1.23.2.dist-info}/LICENSE +30 -30
  2. {micropython_stubber-1.23.1.post1.dist-info → micropython_stubber-1.23.2.dist-info}/METADATA +4 -4
  3. micropython_stubber-1.23.2.dist-info/RECORD +158 -0
  4. mpflash/README.md +220 -220
  5. mpflash/libusb_flash.ipynb +203 -203
  6. mpflash/mpflash/add_firmware.py +98 -98
  7. mpflash/mpflash/ask_input.py +236 -236
  8. mpflash/mpflash/basicgit.py +284 -284
  9. mpflash/mpflash/bootloader/__init__.py +2 -2
  10. mpflash/mpflash/bootloader/activate.py +60 -60
  11. mpflash/mpflash/bootloader/detect.py +82 -82
  12. mpflash/mpflash/bootloader/manual.py +101 -101
  13. mpflash/mpflash/bootloader/micropython.py +12 -12
  14. mpflash/mpflash/bootloader/touch1200.py +36 -36
  15. mpflash/mpflash/cli_download.py +129 -129
  16. mpflash/mpflash/cli_flash.py +224 -216
  17. mpflash/mpflash/cli_group.py +111 -111
  18. mpflash/mpflash/cli_list.py +87 -87
  19. mpflash/mpflash/cli_main.py +39 -39
  20. mpflash/mpflash/common.py +210 -166
  21. mpflash/mpflash/config.py +44 -44
  22. mpflash/mpflash/connected.py +96 -77
  23. mpflash/mpflash/download.py +364 -364
  24. mpflash/mpflash/downloaded.py +130 -130
  25. mpflash/mpflash/errors.py +9 -9
  26. mpflash/mpflash/flash/__init__.py +55 -55
  27. mpflash/mpflash/flash/esp.py +59 -59
  28. mpflash/mpflash/flash/stm32.py +19 -19
  29. mpflash/mpflash/flash/stm32_dfu.py +104 -104
  30. mpflash/mpflash/flash/uf2/__init__.py +88 -88
  31. mpflash/mpflash/flash/uf2/boardid.py +15 -15
  32. mpflash/mpflash/flash/uf2/linux.py +136 -130
  33. mpflash/mpflash/flash/uf2/macos.py +42 -42
  34. mpflash/mpflash/flash/uf2/uf2disk.py +12 -12
  35. mpflash/mpflash/flash/uf2/windows.py +43 -43
  36. mpflash/mpflash/flash/worklist.py +170 -170
  37. mpflash/mpflash/list.py +106 -106
  38. mpflash/mpflash/logger.py +41 -41
  39. mpflash/mpflash/mpboard_id/__init__.py +93 -93
  40. mpflash/mpflash/mpboard_id/add_boards.py +251 -251
  41. mpflash/mpflash/mpboard_id/board.py +37 -37
  42. mpflash/mpflash/mpboard_id/board_id.py +86 -86
  43. mpflash/mpflash/mpboard_id/store.py +43 -43
  44. mpflash/mpflash/mpremoteboard/__init__.py +266 -266
  45. mpflash/mpflash/mpremoteboard/mpy_fw_info.py +141 -141
  46. mpflash/mpflash/mpremoteboard/runner.py +140 -140
  47. mpflash/mpflash/vendor/click_aliases.py +91 -91
  48. mpflash/mpflash/vendor/dfu.py +165 -165
  49. mpflash/mpflash/vendor/pydfu.py +605 -605
  50. mpflash/mpflash/vendor/readme.md +2 -2
  51. mpflash/mpflash/versions.py +135 -135
  52. mpflash/poetry.lock +1599 -1599
  53. mpflash/pyproject.toml +65 -65
  54. mpflash/stm32_udev_rules.md +62 -62
  55. stubber/__init__.py +3 -3
  56. stubber/board/board_info.csv +193 -193
  57. stubber/board/boot.py +34 -34
  58. stubber/board/createstubs.py +1004 -986
  59. stubber/board/createstubs_db.py +826 -825
  60. stubber/board/createstubs_db_min.py +332 -331
  61. stubber/board/createstubs_db_mpy.mpy +0 -0
  62. stubber/board/createstubs_lvgl.py +741 -741
  63. stubber/board/createstubs_lvgl_min.py +741 -741
  64. stubber/board/createstubs_mem.py +767 -766
  65. stubber/board/createstubs_mem_min.py +307 -306
  66. stubber/board/createstubs_mem_mpy.mpy +0 -0
  67. stubber/board/createstubs_min.py +295 -294
  68. stubber/board/createstubs_mpy.mpy +0 -0
  69. stubber/board/fw_info.py +141 -141
  70. stubber/board/info.py +183 -183
  71. stubber/board/main.py +19 -19
  72. stubber/board/modulelist.txt +247 -247
  73. stubber/board/pyrightconfig.json +34 -34
  74. stubber/bulk/mcu_stubber.py +437 -437
  75. stubber/codemod/_partials/__init__.py +48 -48
  76. stubber/codemod/_partials/db_main.py +147 -147
  77. stubber/codemod/_partials/lvgl_main.py +77 -77
  78. stubber/codemod/_partials/modules_reader.py +80 -80
  79. stubber/codemod/add_comment.py +53 -53
  80. stubber/codemod/add_method.py +65 -65
  81. stubber/codemod/board.py +317 -317
  82. stubber/codemod/enrich.py +151 -145
  83. stubber/codemod/merge_docstub.py +284 -284
  84. stubber/codemod/modify_list.py +54 -54
  85. stubber/codemod/utils.py +56 -56
  86. stubber/commands/build_cmd.py +94 -94
  87. stubber/commands/cli.py +49 -49
  88. stubber/commands/clone_cmd.py +78 -78
  89. stubber/commands/config_cmd.py +29 -29
  90. stubber/commands/enrich_folder_cmd.py +71 -71
  91. stubber/commands/get_core_cmd.py +71 -71
  92. stubber/commands/get_docstubs_cmd.py +92 -92
  93. stubber/commands/get_frozen_cmd.py +117 -117
  94. stubber/commands/get_mcu_cmd.py +102 -102
  95. stubber/commands/merge_cmd.py +66 -66
  96. stubber/commands/publish_cmd.py +118 -118
  97. stubber/commands/stub_cmd.py +31 -31
  98. stubber/commands/switch_cmd.py +62 -62
  99. stubber/commands/variants_cmd.py +48 -48
  100. stubber/cst_transformer.py +178 -178
  101. stubber/data/board_info.csv +193 -193
  102. stubber/data/board_info.json +1729 -1729
  103. stubber/data/micropython_tags.csv +15 -15
  104. stubber/data/requirements-core-micropython.txt +38 -38
  105. stubber/data/requirements-core-pycopy.txt +39 -39
  106. stubber/downloader.py +37 -37
  107. stubber/freeze/common.py +72 -72
  108. stubber/freeze/freeze_folder.py +69 -69
  109. stubber/freeze/freeze_manifest_2.py +126 -126
  110. stubber/freeze/get_frozen.py +131 -131
  111. stubber/get_cpython.py +112 -112
  112. stubber/get_lobo.py +59 -59
  113. stubber/minify.py +423 -423
  114. stubber/publish/bump.py +86 -86
  115. stubber/publish/candidates.py +275 -275
  116. stubber/publish/database.py +18 -18
  117. stubber/publish/defaults.py +40 -40
  118. stubber/publish/enums.py +24 -24
  119. stubber/publish/helpers.py +29 -29
  120. stubber/publish/merge_docstubs.py +136 -132
  121. stubber/publish/missing_class_methods.py +51 -51
  122. stubber/publish/package.py +150 -150
  123. stubber/publish/pathnames.py +51 -51
  124. stubber/publish/publish.py +120 -120
  125. stubber/publish/pypi.py +42 -42
  126. stubber/publish/stubpackage.py +1055 -1051
  127. stubber/rst/__init__.py +9 -9
  128. stubber/rst/classsort.py +78 -78
  129. stubber/rst/lookup.py +533 -531
  130. stubber/rst/output_dict.py +401 -401
  131. stubber/rst/reader.py +814 -814
  132. stubber/rst/report_return.py +77 -77
  133. stubber/rst/rst_utils.py +541 -541
  134. stubber/stubber.py +38 -38
  135. stubber/stubs_from_docs.py +90 -90
  136. stubber/tools/manifestfile.py +654 -654
  137. stubber/tools/readme.md +6 -6
  138. stubber/update_fallback.py +117 -117
  139. stubber/update_module_list.py +123 -123
  140. stubber/utils/__init__.py +6 -6
  141. stubber/utils/config.py +137 -137
  142. stubber/utils/makeversionhdr.py +54 -54
  143. stubber/utils/manifest.py +90 -90
  144. stubber/utils/post.py +80 -80
  145. stubber/utils/repos.py +156 -156
  146. stubber/utils/stubmaker.py +139 -139
  147. stubber/utils/typed_config_toml.py +80 -80
  148. stubber/variants.py +106 -106
  149. micropython_stubber-1.23.1.post1.dist-info/RECORD +0 -159
  150. mpflash/basicgit.py +0 -288
  151. {micropython_stubber-1.23.1.post1.dist-info → micropython_stubber-1.23.2.dist-info}/WHEEL +0 -0
  152. {micropython_stubber-1.23.1.post1.dist-info → micropython_stubber-1.23.2.dist-info}/entry_points.txt +0 -0
@@ -1,654 +1,654 @@
1
- #!/usr/bin/env python3
2
- #
3
- # This file is part of the MicroPython project, http://micropython.org/
4
- #
5
- # The MIT License (MIT)
6
- #
7
- # Copyright (c) 2022 Jim Mussared
8
- # Copyright (c) 2019 Damien P. George
9
- #
10
- # Permission is hereby granted, free of charge, to any person obtaining a copy
11
- # of this software and associated documentation files (the "Software"), to deal
12
- # in the Software without restriction, including without limitation the rights
13
- # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- # copies of the Software, and to permit persons to whom the Software is
15
- # furnished to do so, subject to the following conditions:
16
- #
17
- # The above copyright notice and this permission notice shall be included in
18
- # all copies or substantial portions of the Software.
19
- #
20
- # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
- # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
- # THE SOFTWARE.
27
-
28
- from __future__ import print_function
29
- import contextlib
30
- import os
31
- import sys
32
- import tempfile
33
- from collections import namedtuple
34
-
35
- __all__ = ["ManifestFileError", "ManifestFile"]
36
-
37
- # Allow freeze*() etc.
38
- MODE_FREEZE = 1
39
- # Only allow include/require/module/package.
40
- MODE_COMPILE = 2
41
- # Same as compile, but handles require(..., pypi="name") as a requirements.txt entry.
42
- MODE_PYPROJECT = 3
43
-
44
- # In compile mode, .py -> KIND_COMPILE_AS_MPY
45
- # In freeze mode, .py -> KIND_FREEZE_AS_MPY, .mpy->KIND_FREEZE_MPY
46
- KIND_AUTO = 1
47
- # Freeze-mode only, .py -> KIND_FREEZE_AS_MPY, .mpy->KIND_FREEZE_MPY
48
- KIND_FREEZE_AUTO = 2
49
-
50
- # Freeze-mode only, The .py file will be frozen as text.
51
- KIND_FREEZE_AS_STR = 3
52
- # Freeze-mode only, The .py file will be compiled and frozen as bytecode.
53
- KIND_FREEZE_AS_MPY = 4
54
- # Freeze-mode only, The .mpy file will be frozen directly.
55
- KIND_FREEZE_MPY = 5
56
- # Compile mode only, the .py file should be compiled to .mpy.
57
- KIND_COMPILE_AS_MPY = 6
58
-
59
- # File on the local filesystem.
60
- FILE_TYPE_LOCAL = 1
61
- # URL to file. (TODO)
62
- FILE_TYPE_HTTP = 2
63
-
64
- # Default list of libraries in micropython-lib to search for library packages.
65
- BASE_LIBRARY_NAMES = ("micropython", "python-stdlib", "python-ecosys")
66
-
67
-
68
- class ManifestFileError(Exception):
69
- pass
70
-
71
-
72
- class ManifestIgnoreException(Exception):
73
- pass
74
-
75
-
76
- class ManifestUsePyPIException(Exception):
77
- def __init__(self, pypi_name):
78
- self.pypi_name = pypi_name
79
-
80
-
81
- # The set of files that this manifest references.
82
- ManifestOutput = namedtuple(
83
- "ManifestOutput",
84
- [
85
- "file_type", # FILE_TYPE_*.
86
- "full_path", # The input file full path.
87
- "target_path", # The target path on the device.
88
- "timestamp", # Last modified date of the input file.
89
- "kind", # KIND_*.
90
- "metadata", # Metadata for the containing package.
91
- "opt", # Optimisation level (or None).
92
- ],
93
- )
94
-
95
-
96
- # Represents the metadata for a package.
97
- class ManifestPackageMetadata:
98
- def __init__(self, is_require=False):
99
- self._is_require = is_require
100
- self._initialised = False
101
-
102
- self.version = None
103
- self.description = None
104
- self.license = None
105
- self.author = None
106
-
107
- # Annotate a package as being from the python standard library.
108
- self.stdlib = False
109
-
110
- # Allows a python-ecosys package to be annotated with the
111
- # corresponding name in PyPI. e.g. micropython-lib/requests is based
112
- # on pypi/requests.
113
- self.pypi = None
114
- # For a micropython package, this is the name that we will publish it
115
- # to PyPI as. e.g. micropython-lib/senml publishes as
116
- # pypi/micropython-senml.
117
- self.pypi_publish = None
118
-
119
- def update(
120
- self,
121
- mode,
122
- description=None,
123
- version=None,
124
- license=None,
125
- author=None,
126
- stdlib=False,
127
- pypi=None,
128
- pypi_publish=None,
129
- ):
130
- if self._initialised:
131
- raise ManifestFileError("Duplicate call to metadata().")
132
-
133
- # In MODE_PYPROJECT, if this manifest is being evaluated as a result
134
- # of a require(), then figure out if it should be replaced by a PyPI
135
- # dependency instead.
136
- if mode == MODE_PYPROJECT and self._is_require:
137
- if stdlib:
138
- # No dependency required at all for CPython.
139
- raise ManifestIgnoreException
140
- if pypi_publish or pypi:
141
- # In the case where a package is both based on a PyPI package and
142
- # provides one, preference depending on the published one.
143
- # (This should be pretty rare).
144
- raise ManifestUsePyPIException(pypi_publish or pypi)
145
-
146
- self.description = description
147
- self.version = version
148
- self.license = license
149
- self.author = author
150
- self.pypi = pypi
151
- self.pypi_publish = pypi_publish
152
- self._initialised = True
153
-
154
- def check_initialised(self, mode):
155
- # Ensure that metadata() is the first thing a manifest.py does.
156
- # This is to ensure that we early-exit if it should be replaced by a pypi dependency.
157
- if mode in (MODE_COMPILE, MODE_PYPROJECT):
158
- if not self._initialised:
159
- raise ManifestFileError("metadata() must be the first command in a manifest file.")
160
-
161
- def __str__(self):
162
- return "version={} description={} license={} author={} pypi={} pypi_publish={}".format(
163
- self.version, self.description, self.license, self.author, self.pypi, self.pypi_publish
164
- )
165
-
166
-
167
- # Turns a dict of options into a object with attributes used to turn the
168
- # kwargs passed to include() and require into the "options" global in the
169
- # included manifest.
170
- # options = IncludeOptions(foo="bar", blah="stuff")
171
- # options.foo # "bar"
172
- # options.blah # "stuff"
173
- class IncludeOptions:
174
- def __init__(self, **kwargs):
175
- self._kwargs = kwargs
176
- self._defaults = {}
177
-
178
- def defaults(self, **kwargs):
179
- self._defaults = kwargs
180
-
181
- def __getattr__(self, name):
182
- return self._kwargs.get(name, self._defaults.get(name, None))
183
-
184
-
185
- class ManifestFile:
186
- def __init__(self, mode, path_vars=None):
187
- # See MODE_* constants above.
188
- self._mode = mode
189
- # Path substitution variables.
190
- self._path_vars = path_vars or {}
191
- # List of files (as ManifestFileResult) references by this manifest.
192
- self._manifest_files = []
193
- # List of PyPI dependencies (when mode=MODE_PYPROJECT).
194
- self._pypi_dependencies = []
195
- # Don't allow including the same file twice.
196
- self._visited = set()
197
- # Stack of metadata for each level.
198
- self._metadata = [ManifestPackageMetadata()]
199
- # Registered external libraries.
200
- self._libraries = {}
201
- # List of directories to search for packages.
202
- self._library_dirs = []
203
- # Add default micropython-lib libraries if $(MPY_LIB_DIR) has been specified.
204
- if self._path_vars["MPY_LIB_DIR"]:
205
- for lib in BASE_LIBRARY_NAMES:
206
- self.add_library(lib, os.path.join("$(MPY_LIB_DIR)", lib))
207
-
208
- def _resolve_path(self, path):
209
- # Convert path to an absolute path, applying variable substitutions.
210
- for name, value in self._path_vars.items():
211
- if value is not None:
212
- path = path.replace("$({})".format(name), value)
213
- return os.path.abspath(path)
214
-
215
- def _manifest_globals(self, kwargs):
216
- # This is the "API" available to a manifest file.
217
- g = {
218
- "metadata": self.metadata,
219
- "include": self.include,
220
- "require": self.require,
221
- "add_library": self.add_library,
222
- "package": self.package,
223
- "module": self.module,
224
- "options": IncludeOptions(**kwargs),
225
- }
226
-
227
- # Extra legacy functions only for freeze mode.
228
- if self._mode == MODE_FREEZE:
229
- g.update(
230
- {
231
- "freeze": self.freeze,
232
- "freeze_as_str": self.freeze_as_str,
233
- "freeze_as_mpy": self.freeze_as_mpy,
234
- "freeze_mpy": self.freeze_mpy,
235
- }
236
- )
237
-
238
- return g
239
-
240
- def files(self):
241
- return self._manifest_files
242
-
243
- def pypi_dependencies(self):
244
- # In MODE_PYPROJECT, this will return a list suitable for requirements.txt.
245
- return self._pypi_dependencies
246
-
247
- def execute(self, manifest_file):
248
- if manifest_file.endswith(".py"):
249
- # Execute file from filesystem.
250
- self.include(manifest_file)
251
- else:
252
- # Execute manifest code snippet.
253
- try:
254
- exec(manifest_file, self._manifest_globals({}))
255
- except Exception as er:
256
- raise ManifestFileError("Error in manifest: {}".format(er))
257
-
258
- def _add_file(self, full_path, target_path, kind=KIND_AUTO, opt=None):
259
- # Check file exists and get timestamp.
260
- try:
261
- stat = os.stat(full_path)
262
- timestamp = stat.st_mtime
263
- except OSError:
264
- raise ManifestFileError("Cannot stat {}".format(full_path))
265
-
266
- # Map the AUTO kinds to their actual kind based on mode and extension.
267
- _, ext = os.path.splitext(full_path)
268
- if self._mode == MODE_FREEZE:
269
- if kind in (
270
- KIND_AUTO,
271
- KIND_FREEZE_AUTO,
272
- ):
273
- if ext.lower() == ".py":
274
- kind = KIND_FREEZE_AS_MPY
275
- elif ext.lower() == ".mpy":
276
- kind = KIND_FREEZE_MPY
277
- else:
278
- if kind != KIND_AUTO:
279
- raise ManifestFileError("Not in freeze mode")
280
- if ext.lower() != ".py":
281
- raise ManifestFileError("Expected .py file")
282
- kind = KIND_COMPILE_AS_MPY
283
-
284
- self._manifest_files.append(
285
- ManifestOutput(
286
- FILE_TYPE_LOCAL, full_path, target_path, timestamp, kind, self._metadata[-1], opt
287
- )
288
- )
289
-
290
- def _search(self, base_path, package_path, files, exts, kind, opt=None, strict=False):
291
- base_path = self._resolve_path(base_path)
292
-
293
- if files is not None:
294
- # Use explicit list of files (relative to package_path).
295
- for file in files:
296
- if package_path:
297
- file = os.path.join(package_path, file)
298
- self._add_file(os.path.join(base_path, file), file, kind=kind, opt=opt)
299
- else:
300
- if base_path:
301
- prev_cwd = os.getcwd()
302
- os.chdir(self._resolve_path(base_path))
303
-
304
- # Find all candidate files.
305
- for dirpath, _, filenames in os.walk(package_path or ".", followlinks=True):
306
- for file in filenames:
307
- file = os.path.relpath(os.path.join(dirpath, file), ".")
308
- _, ext = os.path.splitext(file)
309
- if ext.lower() in exts:
310
- self._add_file(
311
- os.path.join(base_path, file),
312
- file,
313
- kind=kind,
314
- opt=opt,
315
- )
316
- elif strict:
317
- raise ManifestFileError("Unexpected file type")
318
-
319
- if base_path:
320
- os.chdir(prev_cwd)
321
-
322
- def metadata(self, **kwargs):
323
- """
324
- From within a manifest file, use this to set the metadata for the
325
- package described by current manifest.
326
-
327
- After executing a manifest file (via execute()), call this
328
- to obtain the metadata for the top-level manifest file.
329
-
330
- See ManifestPackageMetadata.update() for valid kwargs.
331
- """
332
- if kwargs:
333
- self._metadata[-1].update(self._mode, **kwargs)
334
- return self._metadata[-1]
335
-
336
- def include(self, manifest_path, is_require=False, **kwargs):
337
- """
338
- Include another manifest.
339
-
340
- The manifest argument can be a string (filename) or an iterable of
341
- strings.
342
-
343
- Relative paths are resolved with respect to the current manifest file.
344
-
345
- If the path is to a directory, then it implicitly includes the
346
- manifest.py file inside that directory.
347
-
348
- Optional kwargs can be provided which will be available to the
349
- included script via the `options` variable.
350
-
351
- e.g. include("path.py", extra_features=True)
352
-
353
- in path.py:
354
- options.defaults(standard_features=True)
355
-
356
- # freeze minimal modules.
357
- if options.standard_features:
358
- # freeze standard modules.
359
- if options.extra_features:
360
- # freeze extra modules.
361
- """
362
- if is_require:
363
- self._metadata[-1].check_initialised(self._mode)
364
-
365
- if not isinstance(manifest_path, str):
366
- for m in manifest_path:
367
- self.include(m, **kwargs)
368
- else:
369
- manifest_path = self._resolve_path(manifest_path)
370
- # Including a directory grabs the manifest.py inside it.
371
- if os.path.isdir(manifest_path):
372
- manifest_path = os.path.join(manifest_path, "manifest.py")
373
- if manifest_path in self._visited:
374
- return
375
- self._visited.add(manifest_path)
376
- if is_require:
377
- # This include is the result of require("name"), so push a new
378
- # package metadata onto the stack.
379
- self._metadata.append(ManifestPackageMetadata(is_require=True))
380
- try:
381
- with open(manifest_path) as f:
382
- # Make paths relative to this manifest file while processing it.
383
- # Applies to includes and input files.
384
- prev_cwd = os.getcwd()
385
- os.chdir(os.path.dirname(manifest_path))
386
- try:
387
- exec(f.read(), self._manifest_globals(kwargs))
388
- finally:
389
- os.chdir(prev_cwd)
390
- except ManifestIgnoreException:
391
- # e.g. MODE_PYPROJECT and this was a stdlib dependency. No-op.
392
- pass
393
- except ManifestUsePyPIException as e:
394
- # e.g. MODE_PYPROJECT and this was a package from
395
- # python-ecosys. Add PyPI dependency instead.
396
- self._pypi_dependencies.append(e.pypi_name)
397
- except Exception as e:
398
- raise ManifestFileError("Error in manifest file: {}: {}".format(manifest_path, e))
399
- if is_require:
400
- self._metadata.pop()
401
-
402
- def _require_from_path(self, library_path, name, version, extra_kwargs):
403
- for root, dirnames, filenames in os.walk(library_path): # type: ignore
404
- if os.path.basename(root) == name and "manifest.py" in filenames:
405
- self.include(root, is_require=True, **extra_kwargs)
406
- return True
407
- return False
408
-
409
- def require(self, name, version=None, pypi=None, library=None, **kwargs):
410
- """
411
- Require a package by name from micropython-lib.
412
-
413
- Optionally specify pipy="package-name" to indicate that this should
414
- use the named package from PyPI when building for CPython.
415
-
416
- Optionally specify library="name" to reference a package from a
417
- library that has been previously registered with add_library(). Otherwise
418
- the list of library paths will be used.
419
- """
420
- self._metadata[-1].check_initialised(self._mode)
421
-
422
- if self._mode == MODE_PYPROJECT and pypi:
423
- # In PYPROJECT mode, allow overriding the PyPI dependency name
424
- # explicitly. Otherwise if the dependent package has metadata
425
- # (pypi_publish) or metadata(pypi) we will use that.
426
- self._pypi_dependencies.append(pypi)
427
- return
428
-
429
- if library is not None:
430
- # Find package in external library.
431
- if library not in self._libraries:
432
- raise ValueError("Unknown library '{}' for require('{}').".format(library, name))
433
- library_path = self._libraries[library]
434
- # Search for {library_path}/**/{name}/manifest.py.
435
- if self._require_from_path(library_path, name, version, kwargs):
436
- return
437
- raise ValueError(
438
- "Package '{}' not found in external library '{}' ({}).".format(
439
- name, library, library_path
440
- )
441
- )
442
-
443
- for lib_dir in self._library_dirs:
444
- # Search for {lib_dir}/**/{name}/manifest.py.
445
- if self._require_from_path(lib_dir, name, version, kwargs):
446
- return
447
-
448
- raise ValueError("Package '{}' not found in any known library.".format(name))
449
-
450
- def add_library(self, library, library_path, prepend=False):
451
- """
452
- Register the path to an external named library.
453
-
454
- The path will be automatically searched when using require(). By default the
455
- added library is added to the end of the list of libraries to search. Pass
456
- `prepend=True` to add it to the start of the list.
457
-
458
- Additionally, the added library can be explicitly requested by using
459
- `require("name", library="library")`.
460
- """
461
- library_path = self._resolve_path(library_path)
462
- self._libraries[library] = library_path
463
- self._library_dirs.insert(0 if prepend else len(self._library_dirs), library_path)
464
-
465
- def package(self, package_path, files=None, base_path=".", opt=None):
466
- """
467
- Define a package, optionally restricting to a set of files.
468
-
469
- Simple case, a package in the current directory:
470
- package("foo")
471
- will include all .py files in foo, and will be stored as foo/bar/baz.py.
472
-
473
- If the package isn't in the current directory, use base_path:
474
- package("foo", base_path="src")
475
-
476
- To restrict to certain files in the package use files (note: paths should be relative to the package):
477
- package("foo", files=["bar/baz.py"])
478
- """
479
- self._metadata[-1].check_initialised(self._mode)
480
-
481
- # Include "base_path/package_path/**/*.py" --> "package_path/**/*.py"
482
- self._search(base_path, package_path, files, exts=(".py",), kind=KIND_AUTO, opt=opt)
483
-
484
- def module(self, module_path, base_path=".", opt=None):
485
- """
486
- Include a single Python file as a module.
487
-
488
- If the file is in the current directory:
489
- module("foo.py")
490
-
491
- Otherwise use base_path to locate the file:
492
- module("foo.py", "src/drivers")
493
- """
494
- self._metadata[-1].check_initialised(self._mode)
495
-
496
- # Include "base_path/module_path" --> "module_path"
497
- base_path = self._resolve_path(base_path)
498
- _, ext = os.path.splitext(module_path)
499
- if ext.lower() != ".py":
500
- raise ManifestFileError("module must be .py file")
501
- # TODO: version None
502
- self._add_file(os.path.join(base_path, module_path), module_path, opt=opt)
503
-
504
- def _freeze_internal(self, path, script, exts, kind, opt):
505
- if script is None:
506
- self._search(path, None, None, exts=exts, kind=kind, opt=opt)
507
- elif isinstance(script, str) and os.path.isdir(os.path.join(path, script)):
508
- self._search(path, script, None, exts=exts, kind=kind, opt=opt)
509
- elif not isinstance(script, str):
510
- self._search(path, None, script, exts=exts, kind=kind, opt=opt)
511
- else:
512
- self._search(path, None, (script,), exts=exts, kind=kind, opt=opt)
513
-
514
- def freeze(self, path, script=None, opt=None):
515
- """
516
- Freeze the input, automatically determining its type. A .py script
517
- will be compiled to a .mpy first then frozen, and a .mpy file will be
518
- frozen directly.
519
-
520
- `path` must be a directory, which is the base directory to _search for
521
- files from. When importing the resulting frozen modules, the name of
522
- the module will start after `path`, ie `path` is excluded from the
523
- module name.
524
-
525
- If `path` is relative, it is resolved to the current manifest.py.
526
- Use $(MPY_DIR), $(MPY_LIB_DIR), $(PORT_DIR), $(BOARD_DIR) if you need
527
- to access specific paths.
528
-
529
- If `script` is None all files in `path` will be frozen.
530
-
531
- If `script` is an iterable then freeze() is called on all items of the
532
- iterable (with the same `path` and `opt` passed through).
533
-
534
- If `script` is a string then it specifies the file or directory to
535
- freeze, and can include extra directories before the file or last
536
- directory. The file or directory will be _searched for in `path`. If
537
- `script` is a directory then all files in that directory will be frozen.
538
-
539
- `opt` is the optimisation level to pass to mpy-cross when compiling .py
540
- to .mpy.
541
- """
542
- self._freeze_internal(
543
- path,
544
- script,
545
- exts=(
546
- ".py",
547
- ".mpy",
548
- ),
549
- kind=KIND_FREEZE_AUTO,
550
- opt=opt,
551
- )
552
-
553
- def freeze_as_str(self, path):
554
- """
555
- Freeze the given `path` and all .py scripts within it as a string,
556
- which will be compiled upon import.
557
- """
558
- self._search(path, None, None, exts=(".py",), kind=KIND_FREEZE_AS_STR)
559
-
560
- def freeze_as_mpy(self, path, script=None, opt=None):
561
- """
562
- Freeze the input (see above) by first compiling the .py scripts to
563
- .mpy files, then freezing the resulting .mpy files.
564
- """
565
- self._freeze_internal(path, script, exts=(".py",), kind=KIND_FREEZE_AS_MPY, opt=opt)
566
-
567
- def freeze_mpy(self, path, script=None, opt=None):
568
- """
569
- Freeze the input (see above), which must be .mpy files that are
570
- frozen directly.
571
- """
572
- self._freeze_internal(path, script, exts=(".mpy",), kind=KIND_FREEZE_MPY, opt=opt)
573
-
574
-
575
- # Generate a temporary file with a line appended to the end that adds __version__.
576
- @contextlib.contextmanager
577
- def tagged_py_file(path, metadata):
578
- dest_fd, dest_path = tempfile.mkstemp(suffix=".py", text=True)
579
- try:
580
- with os.fdopen(dest_fd, "w") as dest:
581
- with open(path, "r") as src:
582
- contents = src.read()
583
- dest.write(contents)
584
-
585
- # Don't overwrite a version definition if the file already has one in it.
586
- if metadata.version and "__version__ =" not in contents:
587
- dest.write("\n\n__version__ = {}\n".format(repr(metadata.version)))
588
- yield dest_path
589
- finally:
590
- os.unlink(dest_path)
591
-
592
-
593
- def main():
594
- import argparse
595
-
596
- cmd_parser = argparse.ArgumentParser(description="List the files referenced by a manifest.")
597
- cmd_parser.add_argument("--freeze", action="store_true", help="freeze mode")
598
- cmd_parser.add_argument("--compile", action="store_true", help="compile mode")
599
- cmd_parser.add_argument("--pyproject", action="store_true", help="pyproject mode")
600
- cmd_parser.add_argument(
601
- "--lib",
602
- default=os.path.join(os.path.dirname(__file__), "../lib/micropython-lib"),
603
- help="path to micropython-lib repo",
604
- )
605
- cmd_parser.add_argument(
606
- "--unix-ffi", action="store_true", help="prepend unix-ffi to the library path"
607
- )
608
- cmd_parser.add_argument("--port", default=None, help="path to port dir")
609
- cmd_parser.add_argument("--board", default=None, help="path to board dir")
610
- cmd_parser.add_argument(
611
- "--top",
612
- default=os.path.join(os.path.dirname(__file__), ".."),
613
- help="path to micropython repo",
614
- )
615
- cmd_parser.add_argument("files", nargs="+", help="input manifest.py")
616
- args = cmd_parser.parse_args()
617
-
618
- path_vars = {
619
- "MPY_DIR": os.path.abspath(args.top) if args.top else None,
620
- "BOARD_DIR": os.path.abspath(args.board) if args.board else None,
621
- "PORT_DIR": os.path.abspath(args.port) if args.port else None,
622
- "MPY_LIB_DIR": os.path.abspath(args.lib) if args.lib else None,
623
- }
624
-
625
- mode = None
626
- if args.freeze:
627
- mode = MODE_FREEZE
628
- elif args.compile:
629
- mode = MODE_COMPILE
630
- elif args.pyproject:
631
- mode = MODE_PYPROJECT
632
- else:
633
- print("Error: No mode specified.", file=sys.stderr)
634
- exit(1)
635
-
636
- m = ManifestFile(mode, path_vars)
637
- if args.unix_ffi:
638
- m.add_library("unix-ffi", os.path.join("$(MPY_LIB_DIR)", "unix-ffi"), prepend=True)
639
- for manifest_file in args.files:
640
- try:
641
- m.execute(manifest_file)
642
- except ManifestFileError as er:
643
- print(er, file=sys.stderr)
644
- exit(1)
645
- print(m.metadata())
646
- for f in m.files():
647
- print(f)
648
- if mode == MODE_PYPROJECT:
649
- for r in m.pypi_dependencies():
650
- print("pypi-require:", r)
651
-
652
-
653
- if __name__ == "__main__":
654
- main()
1
+ #!/usr/bin/env python3
2
+ #
3
+ # This file is part of the MicroPython project, http://micropython.org/
4
+ #
5
+ # The MIT License (MIT)
6
+ #
7
+ # Copyright (c) 2022 Jim Mussared
8
+ # Copyright (c) 2019 Damien P. George
9
+ #
10
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ # of this software and associated documentation files (the "Software"), to deal
12
+ # in the Software without restriction, including without limitation the rights
13
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ # copies of the Software, and to permit persons to whom the Software is
15
+ # furnished to do so, subject to the following conditions:
16
+ #
17
+ # The above copyright notice and this permission notice shall be included in
18
+ # all copies or substantial portions of the Software.
19
+ #
20
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26
+ # THE SOFTWARE.
27
+
28
+ from __future__ import print_function
29
+ import contextlib
30
+ import os
31
+ import sys
32
+ import tempfile
33
+ from collections import namedtuple
34
+
35
+ __all__ = ["ManifestFileError", "ManifestFile"]
36
+
37
+ # Allow freeze*() etc.
38
+ MODE_FREEZE = 1
39
+ # Only allow include/require/module/package.
40
+ MODE_COMPILE = 2
41
+ # Same as compile, but handles require(..., pypi="name") as a requirements.txt entry.
42
+ MODE_PYPROJECT = 3
43
+
44
+ # In compile mode, .py -> KIND_COMPILE_AS_MPY
45
+ # In freeze mode, .py -> KIND_FREEZE_AS_MPY, .mpy->KIND_FREEZE_MPY
46
+ KIND_AUTO = 1
47
+ # Freeze-mode only, .py -> KIND_FREEZE_AS_MPY, .mpy->KIND_FREEZE_MPY
48
+ KIND_FREEZE_AUTO = 2
49
+
50
+ # Freeze-mode only, The .py file will be frozen as text.
51
+ KIND_FREEZE_AS_STR = 3
52
+ # Freeze-mode only, The .py file will be compiled and frozen as bytecode.
53
+ KIND_FREEZE_AS_MPY = 4
54
+ # Freeze-mode only, The .mpy file will be frozen directly.
55
+ KIND_FREEZE_MPY = 5
56
+ # Compile mode only, the .py file should be compiled to .mpy.
57
+ KIND_COMPILE_AS_MPY = 6
58
+
59
+ # File on the local filesystem.
60
+ FILE_TYPE_LOCAL = 1
61
+ # URL to file. (TODO)
62
+ FILE_TYPE_HTTP = 2
63
+
64
+ # Default list of libraries in micropython-lib to search for library packages.
65
+ BASE_LIBRARY_NAMES = ("micropython", "python-stdlib", "python-ecosys")
66
+
67
+
68
+ class ManifestFileError(Exception):
69
+ pass
70
+
71
+
72
+ class ManifestIgnoreException(Exception):
73
+ pass
74
+
75
+
76
+ class ManifestUsePyPIException(Exception):
77
+ def __init__(self, pypi_name):
78
+ self.pypi_name = pypi_name
79
+
80
+
81
+ # The set of files that this manifest references.
82
+ ManifestOutput = namedtuple(
83
+ "ManifestOutput",
84
+ [
85
+ "file_type", # FILE_TYPE_*.
86
+ "full_path", # The input file full path.
87
+ "target_path", # The target path on the device.
88
+ "timestamp", # Last modified date of the input file.
89
+ "kind", # KIND_*.
90
+ "metadata", # Metadata for the containing package.
91
+ "opt", # Optimisation level (or None).
92
+ ],
93
+ )
94
+
95
+
96
+ # Represents the metadata for a package.
97
+ class ManifestPackageMetadata:
98
+ def __init__(self, is_require=False):
99
+ self._is_require = is_require
100
+ self._initialised = False
101
+
102
+ self.version = None
103
+ self.description = None
104
+ self.license = None
105
+ self.author = None
106
+
107
+ # Annotate a package as being from the python standard library.
108
+ self.stdlib = False
109
+
110
+ # Allows a python-ecosys package to be annotated with the
111
+ # corresponding name in PyPI. e.g. micropython-lib/requests is based
112
+ # on pypi/requests.
113
+ self.pypi = None
114
+ # For a micropython package, this is the name that we will publish it
115
+ # to PyPI as. e.g. micropython-lib/senml publishes as
116
+ # pypi/micropython-senml.
117
+ self.pypi_publish = None
118
+
119
+ def update(
120
+ self,
121
+ mode,
122
+ description=None,
123
+ version=None,
124
+ license=None,
125
+ author=None,
126
+ stdlib=False,
127
+ pypi=None,
128
+ pypi_publish=None,
129
+ ):
130
+ if self._initialised:
131
+ raise ManifestFileError("Duplicate call to metadata().")
132
+
133
+ # In MODE_PYPROJECT, if this manifest is being evaluated as a result
134
+ # of a require(), then figure out if it should be replaced by a PyPI
135
+ # dependency instead.
136
+ if mode == MODE_PYPROJECT and self._is_require:
137
+ if stdlib:
138
+ # No dependency required at all for CPython.
139
+ raise ManifestIgnoreException
140
+ if pypi_publish or pypi:
141
+ # In the case where a package is both based on a PyPI package and
142
+ # provides one, preference depending on the published one.
143
+ # (This should be pretty rare).
144
+ raise ManifestUsePyPIException(pypi_publish or pypi)
145
+
146
+ self.description = description
147
+ self.version = version
148
+ self.license = license
149
+ self.author = author
150
+ self.pypi = pypi
151
+ self.pypi_publish = pypi_publish
152
+ self._initialised = True
153
+
154
+ def check_initialised(self, mode):
155
+ # Ensure that metadata() is the first thing a manifest.py does.
156
+ # This is to ensure that we early-exit if it should be replaced by a pypi dependency.
157
+ if mode in (MODE_COMPILE, MODE_PYPROJECT):
158
+ if not self._initialised:
159
+ raise ManifestFileError("metadata() must be the first command in a manifest file.")
160
+
161
+ def __str__(self):
162
+ return "version={} description={} license={} author={} pypi={} pypi_publish={}".format(
163
+ self.version, self.description, self.license, self.author, self.pypi, self.pypi_publish
164
+ )
165
+
166
+
167
+ # Turns a dict of options into a object with attributes used to turn the
168
+ # kwargs passed to include() and require into the "options" global in the
169
+ # included manifest.
170
+ # options = IncludeOptions(foo="bar", blah="stuff")
171
+ # options.foo # "bar"
172
+ # options.blah # "stuff"
173
+ class IncludeOptions:
174
+ def __init__(self, **kwargs):
175
+ self._kwargs = kwargs
176
+ self._defaults = {}
177
+
178
+ def defaults(self, **kwargs):
179
+ self._defaults = kwargs
180
+
181
+ def __getattr__(self, name):
182
+ return self._kwargs.get(name, self._defaults.get(name, None))
183
+
184
+
185
+ class ManifestFile:
186
+ def __init__(self, mode, path_vars=None):
187
+ # See MODE_* constants above.
188
+ self._mode = mode
189
+ # Path substitution variables.
190
+ self._path_vars = path_vars or {}
191
+ # List of files (as ManifestFileResult) references by this manifest.
192
+ self._manifest_files = []
193
+ # List of PyPI dependencies (when mode=MODE_PYPROJECT).
194
+ self._pypi_dependencies = []
195
+ # Don't allow including the same file twice.
196
+ self._visited = set()
197
+ # Stack of metadata for each level.
198
+ self._metadata = [ManifestPackageMetadata()]
199
+ # Registered external libraries.
200
+ self._libraries = {}
201
+ # List of directories to search for packages.
202
+ self._library_dirs = []
203
+ # Add default micropython-lib libraries if $(MPY_LIB_DIR) has been specified.
204
+ if self._path_vars["MPY_LIB_DIR"]:
205
+ for lib in BASE_LIBRARY_NAMES:
206
+ self.add_library(lib, os.path.join("$(MPY_LIB_DIR)", lib))
207
+
208
+ def _resolve_path(self, path):
209
+ # Convert path to an absolute path, applying variable substitutions.
210
+ for name, value in self._path_vars.items():
211
+ if value is not None:
212
+ path = path.replace("$({})".format(name), value)
213
+ return os.path.abspath(path)
214
+
215
+ def _manifest_globals(self, kwargs):
216
+ # This is the "API" available to a manifest file.
217
+ g = {
218
+ "metadata": self.metadata,
219
+ "include": self.include,
220
+ "require": self.require,
221
+ "add_library": self.add_library,
222
+ "package": self.package,
223
+ "module": self.module,
224
+ "options": IncludeOptions(**kwargs),
225
+ }
226
+
227
+ # Extra legacy functions only for freeze mode.
228
+ if self._mode == MODE_FREEZE:
229
+ g.update(
230
+ {
231
+ "freeze": self.freeze,
232
+ "freeze_as_str": self.freeze_as_str,
233
+ "freeze_as_mpy": self.freeze_as_mpy,
234
+ "freeze_mpy": self.freeze_mpy,
235
+ }
236
+ )
237
+
238
+ return g
239
+
240
+ def files(self):
241
+ return self._manifest_files
242
+
243
+ def pypi_dependencies(self):
244
+ # In MODE_PYPROJECT, this will return a list suitable for requirements.txt.
245
+ return self._pypi_dependencies
246
+
247
+ def execute(self, manifest_file):
248
+ if manifest_file.endswith(".py"):
249
+ # Execute file from filesystem.
250
+ self.include(manifest_file)
251
+ else:
252
+ # Execute manifest code snippet.
253
+ try:
254
+ exec(manifest_file, self._manifest_globals({}))
255
+ except Exception as er:
256
+ raise ManifestFileError("Error in manifest: {}".format(er))
257
+
258
+ def _add_file(self, full_path, target_path, kind=KIND_AUTO, opt=None):
259
+ # Check file exists and get timestamp.
260
+ try:
261
+ stat = os.stat(full_path)
262
+ timestamp = stat.st_mtime
263
+ except OSError:
264
+ raise ManifestFileError("Cannot stat {}".format(full_path))
265
+
266
+ # Map the AUTO kinds to their actual kind based on mode and extension.
267
+ _, ext = os.path.splitext(full_path)
268
+ if self._mode == MODE_FREEZE:
269
+ if kind in (
270
+ KIND_AUTO,
271
+ KIND_FREEZE_AUTO,
272
+ ):
273
+ if ext.lower() == ".py":
274
+ kind = KIND_FREEZE_AS_MPY
275
+ elif ext.lower() == ".mpy":
276
+ kind = KIND_FREEZE_MPY
277
+ else:
278
+ if kind != KIND_AUTO:
279
+ raise ManifestFileError("Not in freeze mode")
280
+ if ext.lower() != ".py":
281
+ raise ManifestFileError("Expected .py file")
282
+ kind = KIND_COMPILE_AS_MPY
283
+
284
+ self._manifest_files.append(
285
+ ManifestOutput(
286
+ FILE_TYPE_LOCAL, full_path, target_path, timestamp, kind, self._metadata[-1], opt
287
+ )
288
+ )
289
+
290
+ def _search(self, base_path, package_path, files, exts, kind, opt=None, strict=False):
291
+ base_path = self._resolve_path(base_path)
292
+
293
+ if files is not None:
294
+ # Use explicit list of files (relative to package_path).
295
+ for file in files:
296
+ if package_path:
297
+ file = os.path.join(package_path, file)
298
+ self._add_file(os.path.join(base_path, file), file, kind=kind, opt=opt)
299
+ else:
300
+ if base_path:
301
+ prev_cwd = os.getcwd()
302
+ os.chdir(self._resolve_path(base_path))
303
+
304
+ # Find all candidate files.
305
+ for dirpath, _, filenames in os.walk(package_path or ".", followlinks=True):
306
+ for file in filenames:
307
+ file = os.path.relpath(os.path.join(dirpath, file), ".")
308
+ _, ext = os.path.splitext(file)
309
+ if ext.lower() in exts:
310
+ self._add_file(
311
+ os.path.join(base_path, file),
312
+ file,
313
+ kind=kind,
314
+ opt=opt,
315
+ )
316
+ elif strict:
317
+ raise ManifestFileError("Unexpected file type")
318
+
319
+ if base_path:
320
+ os.chdir(prev_cwd)
321
+
322
+ def metadata(self, **kwargs):
323
+ """
324
+ From within a manifest file, use this to set the metadata for the
325
+ package described by current manifest.
326
+
327
+ After executing a manifest file (via execute()), call this
328
+ to obtain the metadata for the top-level manifest file.
329
+
330
+ See ManifestPackageMetadata.update() for valid kwargs.
331
+ """
332
+ if kwargs:
333
+ self._metadata[-1].update(self._mode, **kwargs)
334
+ return self._metadata[-1]
335
+
336
+ def include(self, manifest_path, is_require=False, **kwargs):
337
+ """
338
+ Include another manifest.
339
+
340
+ The manifest argument can be a string (filename) or an iterable of
341
+ strings.
342
+
343
+ Relative paths are resolved with respect to the current manifest file.
344
+
345
+ If the path is to a directory, then it implicitly includes the
346
+ manifest.py file inside that directory.
347
+
348
+ Optional kwargs can be provided which will be available to the
349
+ included script via the `options` variable.
350
+
351
+ e.g. include("path.py", extra_features=True)
352
+
353
+ in path.py:
354
+ options.defaults(standard_features=True)
355
+
356
+ # freeze minimal modules.
357
+ if options.standard_features:
358
+ # freeze standard modules.
359
+ if options.extra_features:
360
+ # freeze extra modules.
361
+ """
362
+ if is_require:
363
+ self._metadata[-1].check_initialised(self._mode)
364
+
365
+ if not isinstance(manifest_path, str):
366
+ for m in manifest_path:
367
+ self.include(m, **kwargs)
368
+ else:
369
+ manifest_path = self._resolve_path(manifest_path)
370
+ # Including a directory grabs the manifest.py inside it.
371
+ if os.path.isdir(manifest_path):
372
+ manifest_path = os.path.join(manifest_path, "manifest.py")
373
+ if manifest_path in self._visited:
374
+ return
375
+ self._visited.add(manifest_path)
376
+ if is_require:
377
+ # This include is the result of require("name"), so push a new
378
+ # package metadata onto the stack.
379
+ self._metadata.append(ManifestPackageMetadata(is_require=True))
380
+ try:
381
+ with open(manifest_path) as f:
382
+ # Make paths relative to this manifest file while processing it.
383
+ # Applies to includes and input files.
384
+ prev_cwd = os.getcwd()
385
+ os.chdir(os.path.dirname(manifest_path))
386
+ try:
387
+ exec(f.read(), self._manifest_globals(kwargs))
388
+ finally:
389
+ os.chdir(prev_cwd)
390
+ except ManifestIgnoreException:
391
+ # e.g. MODE_PYPROJECT and this was a stdlib dependency. No-op.
392
+ pass
393
+ except ManifestUsePyPIException as e:
394
+ # e.g. MODE_PYPROJECT and this was a package from
395
+ # python-ecosys. Add PyPI dependency instead.
396
+ self._pypi_dependencies.append(e.pypi_name)
397
+ except Exception as e:
398
+ raise ManifestFileError("Error in manifest file: {}: {}".format(manifest_path, e))
399
+ if is_require:
400
+ self._metadata.pop()
401
+
402
+ def _require_from_path(self, library_path, name, version, extra_kwargs):
403
+ for root, dirnames, filenames in os.walk(library_path): # type: ignore
404
+ if os.path.basename(root) == name and "manifest.py" in filenames:
405
+ self.include(root, is_require=True, **extra_kwargs)
406
+ return True
407
+ return False
408
+
409
+ def require(self, name, version=None, pypi=None, library=None, **kwargs):
410
+ """
411
+ Require a package by name from micropython-lib.
412
+
413
+ Optionally specify pipy="package-name" to indicate that this should
414
+ use the named package from PyPI when building for CPython.
415
+
416
+ Optionally specify library="name" to reference a package from a
417
+ library that has been previously registered with add_library(). Otherwise
418
+ the list of library paths will be used.
419
+ """
420
+ self._metadata[-1].check_initialised(self._mode)
421
+
422
+ if self._mode == MODE_PYPROJECT and pypi:
423
+ # In PYPROJECT mode, allow overriding the PyPI dependency name
424
+ # explicitly. Otherwise if the dependent package has metadata
425
+ # (pypi_publish) or metadata(pypi) we will use that.
426
+ self._pypi_dependencies.append(pypi)
427
+ return
428
+
429
+ if library is not None:
430
+ # Find package in external library.
431
+ if library not in self._libraries:
432
+ raise ValueError("Unknown library '{}' for require('{}').".format(library, name))
433
+ library_path = self._libraries[library]
434
+ # Search for {library_path}/**/{name}/manifest.py.
435
+ if self._require_from_path(library_path, name, version, kwargs):
436
+ return
437
+ raise ValueError(
438
+ "Package '{}' not found in external library '{}' ({}).".format(
439
+ name, library, library_path
440
+ )
441
+ )
442
+
443
+ for lib_dir in self._library_dirs:
444
+ # Search for {lib_dir}/**/{name}/manifest.py.
445
+ if self._require_from_path(lib_dir, name, version, kwargs):
446
+ return
447
+
448
+ raise ValueError("Package '{}' not found in any known library.".format(name))
449
+
450
+ def add_library(self, library, library_path, prepend=False):
451
+ """
452
+ Register the path to an external named library.
453
+
454
+ The path will be automatically searched when using require(). By default the
455
+ added library is added to the end of the list of libraries to search. Pass
456
+ `prepend=True` to add it to the start of the list.
457
+
458
+ Additionally, the added library can be explicitly requested by using
459
+ `require("name", library="library")`.
460
+ """
461
+ library_path = self._resolve_path(library_path)
462
+ self._libraries[library] = library_path
463
+ self._library_dirs.insert(0 if prepend else len(self._library_dirs), library_path)
464
+
465
+ def package(self, package_path, files=None, base_path=".", opt=None):
466
+ """
467
+ Define a package, optionally restricting to a set of files.
468
+
469
+ Simple case, a package in the current directory:
470
+ package("foo")
471
+ will include all .py files in foo, and will be stored as foo/bar/baz.py.
472
+
473
+ If the package isn't in the current directory, use base_path:
474
+ package("foo", base_path="src")
475
+
476
+ To restrict to certain files in the package use files (note: paths should be relative to the package):
477
+ package("foo", files=["bar/baz.py"])
478
+ """
479
+ self._metadata[-1].check_initialised(self._mode)
480
+
481
+ # Include "base_path/package_path/**/*.py" --> "package_path/**/*.py"
482
+ self._search(base_path, package_path, files, exts=(".py",), kind=KIND_AUTO, opt=opt)
483
+
484
+ def module(self, module_path, base_path=".", opt=None):
485
+ """
486
+ Include a single Python file as a module.
487
+
488
+ If the file is in the current directory:
489
+ module("foo.py")
490
+
491
+ Otherwise use base_path to locate the file:
492
+ module("foo.py", "src/drivers")
493
+ """
494
+ self._metadata[-1].check_initialised(self._mode)
495
+
496
+ # Include "base_path/module_path" --> "module_path"
497
+ base_path = self._resolve_path(base_path)
498
+ _, ext = os.path.splitext(module_path)
499
+ if ext.lower() != ".py":
500
+ raise ManifestFileError("module must be .py file")
501
+ # TODO: version None
502
+ self._add_file(os.path.join(base_path, module_path), module_path, opt=opt)
503
+
504
+ def _freeze_internal(self, path, script, exts, kind, opt):
505
+ if script is None:
506
+ self._search(path, None, None, exts=exts, kind=kind, opt=opt)
507
+ elif isinstance(script, str) and os.path.isdir(os.path.join(path, script)):
508
+ self._search(path, script, None, exts=exts, kind=kind, opt=opt)
509
+ elif not isinstance(script, str):
510
+ self._search(path, None, script, exts=exts, kind=kind, opt=opt)
511
+ else:
512
+ self._search(path, None, (script,), exts=exts, kind=kind, opt=opt)
513
+
514
+ def freeze(self, path, script=None, opt=None):
515
+ """
516
+ Freeze the input, automatically determining its type. A .py script
517
+ will be compiled to a .mpy first then frozen, and a .mpy file will be
518
+ frozen directly.
519
+
520
+ `path` must be a directory, which is the base directory to _search for
521
+ files from. When importing the resulting frozen modules, the name of
522
+ the module will start after `path`, ie `path` is excluded from the
523
+ module name.
524
+
525
+ If `path` is relative, it is resolved to the current manifest.py.
526
+ Use $(MPY_DIR), $(MPY_LIB_DIR), $(PORT_DIR), $(BOARD_DIR) if you need
527
+ to access specific paths.
528
+
529
+ If `script` is None all files in `path` will be frozen.
530
+
531
+ If `script` is an iterable then freeze() is called on all items of the
532
+ iterable (with the same `path` and `opt` passed through).
533
+
534
+ If `script` is a string then it specifies the file or directory to
535
+ freeze, and can include extra directories before the file or last
536
+ directory. The file or directory will be _searched for in `path`. If
537
+ `script` is a directory then all files in that directory will be frozen.
538
+
539
+ `opt` is the optimisation level to pass to mpy-cross when compiling .py
540
+ to .mpy.
541
+ """
542
+ self._freeze_internal(
543
+ path,
544
+ script,
545
+ exts=(
546
+ ".py",
547
+ ".mpy",
548
+ ),
549
+ kind=KIND_FREEZE_AUTO,
550
+ opt=opt,
551
+ )
552
+
553
+ def freeze_as_str(self, path):
554
+ """
555
+ Freeze the given `path` and all .py scripts within it as a string,
556
+ which will be compiled upon import.
557
+ """
558
+ self._search(path, None, None, exts=(".py",), kind=KIND_FREEZE_AS_STR)
559
+
560
+ def freeze_as_mpy(self, path, script=None, opt=None):
561
+ """
562
+ Freeze the input (see above) by first compiling the .py scripts to
563
+ .mpy files, then freezing the resulting .mpy files.
564
+ """
565
+ self._freeze_internal(path, script, exts=(".py",), kind=KIND_FREEZE_AS_MPY, opt=opt)
566
+
567
+ def freeze_mpy(self, path, script=None, opt=None):
568
+ """
569
+ Freeze the input (see above), which must be .mpy files that are
570
+ frozen directly.
571
+ """
572
+ self._freeze_internal(path, script, exts=(".mpy",), kind=KIND_FREEZE_MPY, opt=opt)
573
+
574
+
575
+ # Generate a temporary file with a line appended to the end that adds __version__.
576
+ @contextlib.contextmanager
577
+ def tagged_py_file(path, metadata):
578
+ dest_fd, dest_path = tempfile.mkstemp(suffix=".py", text=True)
579
+ try:
580
+ with os.fdopen(dest_fd, "w") as dest:
581
+ with open(path, "r") as src:
582
+ contents = src.read()
583
+ dest.write(contents)
584
+
585
+ # Don't overwrite a version definition if the file already has one in it.
586
+ if metadata.version and "__version__ =" not in contents:
587
+ dest.write("\n\n__version__ = {}\n".format(repr(metadata.version)))
588
+ yield dest_path
589
+ finally:
590
+ os.unlink(dest_path)
591
+
592
+
593
+ def main():
594
+ import argparse
595
+
596
+ cmd_parser = argparse.ArgumentParser(description="List the files referenced by a manifest.")
597
+ cmd_parser.add_argument("--freeze", action="store_true", help="freeze mode")
598
+ cmd_parser.add_argument("--compile", action="store_true", help="compile mode")
599
+ cmd_parser.add_argument("--pyproject", action="store_true", help="pyproject mode")
600
+ cmd_parser.add_argument(
601
+ "--lib",
602
+ default=os.path.join(os.path.dirname(__file__), "../lib/micropython-lib"),
603
+ help="path to micropython-lib repo",
604
+ )
605
+ cmd_parser.add_argument(
606
+ "--unix-ffi", action="store_true", help="prepend unix-ffi to the library path"
607
+ )
608
+ cmd_parser.add_argument("--port", default=None, help="path to port dir")
609
+ cmd_parser.add_argument("--board", default=None, help="path to board dir")
610
+ cmd_parser.add_argument(
611
+ "--top",
612
+ default=os.path.join(os.path.dirname(__file__), ".."),
613
+ help="path to micropython repo",
614
+ )
615
+ cmd_parser.add_argument("files", nargs="+", help="input manifest.py")
616
+ args = cmd_parser.parse_args()
617
+
618
+ path_vars = {
619
+ "MPY_DIR": os.path.abspath(args.top) if args.top else None,
620
+ "BOARD_DIR": os.path.abspath(args.board) if args.board else None,
621
+ "PORT_DIR": os.path.abspath(args.port) if args.port else None,
622
+ "MPY_LIB_DIR": os.path.abspath(args.lib) if args.lib else None,
623
+ }
624
+
625
+ mode = None
626
+ if args.freeze:
627
+ mode = MODE_FREEZE
628
+ elif args.compile:
629
+ mode = MODE_COMPILE
630
+ elif args.pyproject:
631
+ mode = MODE_PYPROJECT
632
+ else:
633
+ print("Error: No mode specified.", file=sys.stderr)
634
+ exit(1)
635
+
636
+ m = ManifestFile(mode, path_vars)
637
+ if args.unix_ffi:
638
+ m.add_library("unix-ffi", os.path.join("$(MPY_LIB_DIR)", "unix-ffi"), prepend=True)
639
+ for manifest_file in args.files:
640
+ try:
641
+ m.execute(manifest_file)
642
+ except ManifestFileError as er:
643
+ print(er, file=sys.stderr)
644
+ exit(1)
645
+ print(m.metadata())
646
+ for f in m.files():
647
+ print(f)
648
+ if mode == MODE_PYPROJECT:
649
+ for r in m.pypi_dependencies():
650
+ print("pypi-require:", r)
651
+
652
+
653
+ if __name__ == "__main__":
654
+ main()