micropython-stubber 1.23.1__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 (153) hide show
  1. {micropython_stubber-1.23.1.dist-info → micropython_stubber-1.23.2.dist-info}/LICENSE +30 -30
  2. {micropython_stubber-1.23.1.dist-info → micropython_stubber-1.23.2.dist-info}/METADATA +32 -15
  3. micropython_stubber-1.23.2.dist-info/RECORD +158 -0
  4. micropython_stubber-1.23.2.dist-info/entry_points.txt +5 -0
  5. mpflash/README.md +220 -194
  6. mpflash/libusb_flash.ipynb +203 -203
  7. mpflash/mpflash/add_firmware.py +98 -98
  8. mpflash/mpflash/ask_input.py +236 -236
  9. mpflash/mpflash/basicgit.py +284 -284
  10. mpflash/mpflash/bootloader/__init__.py +2 -2
  11. mpflash/mpflash/bootloader/activate.py +60 -60
  12. mpflash/mpflash/bootloader/detect.py +82 -82
  13. mpflash/mpflash/bootloader/manual.py +101 -101
  14. mpflash/mpflash/bootloader/micropython.py +12 -12
  15. mpflash/mpflash/bootloader/touch1200.py +36 -36
  16. mpflash/mpflash/cli_download.py +129 -129
  17. mpflash/mpflash/cli_flash.py +224 -219
  18. mpflash/mpflash/cli_group.py +111 -111
  19. mpflash/mpflash/cli_list.py +87 -81
  20. mpflash/mpflash/cli_main.py +39 -39
  21. mpflash/mpflash/common.py +210 -165
  22. mpflash/mpflash/config.py +44 -44
  23. mpflash/mpflash/connected.py +96 -78
  24. mpflash/mpflash/download.py +364 -364
  25. mpflash/mpflash/downloaded.py +130 -130
  26. mpflash/mpflash/errors.py +9 -9
  27. mpflash/mpflash/flash/__init__.py +55 -55
  28. mpflash/mpflash/flash/esp.py +59 -59
  29. mpflash/mpflash/flash/stm32.py +19 -19
  30. mpflash/mpflash/flash/stm32_dfu.py +104 -104
  31. mpflash/mpflash/flash/uf2/__init__.py +88 -88
  32. mpflash/mpflash/flash/uf2/boardid.py +15 -15
  33. mpflash/mpflash/flash/uf2/linux.py +136 -130
  34. mpflash/mpflash/flash/uf2/macos.py +42 -42
  35. mpflash/mpflash/flash/uf2/uf2disk.py +12 -12
  36. mpflash/mpflash/flash/uf2/windows.py +43 -43
  37. mpflash/mpflash/flash/worklist.py +170 -170
  38. mpflash/mpflash/list.py +106 -99
  39. mpflash/mpflash/logger.py +41 -41
  40. mpflash/mpflash/mpboard_id/__init__.py +93 -93
  41. mpflash/mpflash/mpboard_id/add_boards.py +251 -251
  42. mpflash/mpflash/mpboard_id/board.py +37 -37
  43. mpflash/mpflash/mpboard_id/board_id.py +86 -86
  44. mpflash/mpflash/mpboard_id/store.py +43 -43
  45. mpflash/mpflash/mpremoteboard/__init__.py +266 -222
  46. mpflash/mpflash/mpremoteboard/mpy_fw_info.py +141 -141
  47. mpflash/mpflash/mpremoteboard/runner.py +140 -140
  48. mpflash/mpflash/vendor/click_aliases.py +91 -91
  49. mpflash/mpflash/vendor/dfu.py +165 -165
  50. mpflash/mpflash/vendor/pydfu.py +605 -605
  51. mpflash/mpflash/vendor/readme.md +2 -2
  52. mpflash/mpflash/versions.py +135 -135
  53. mpflash/poetry.lock +1599 -1599
  54. mpflash/pyproject.toml +65 -65
  55. mpflash/stm32_udev_rules.md +62 -62
  56. stubber/__init__.py +3 -3
  57. stubber/board/board_info.csv +193 -193
  58. stubber/board/boot.py +34 -34
  59. stubber/board/createstubs.py +1004 -986
  60. stubber/board/createstubs_db.py +826 -825
  61. stubber/board/createstubs_db_min.py +332 -331
  62. stubber/board/createstubs_db_mpy.mpy +0 -0
  63. stubber/board/createstubs_lvgl.py +741 -741
  64. stubber/board/createstubs_lvgl_min.py +741 -741
  65. stubber/board/createstubs_mem.py +767 -766
  66. stubber/board/createstubs_mem_min.py +307 -306
  67. stubber/board/createstubs_mem_mpy.mpy +0 -0
  68. stubber/board/createstubs_min.py +295 -294
  69. stubber/board/createstubs_mpy.mpy +0 -0
  70. stubber/board/fw_info.py +141 -141
  71. stubber/board/info.py +183 -183
  72. stubber/board/main.py +19 -19
  73. stubber/board/modulelist.txt +247 -247
  74. stubber/board/pyrightconfig.json +34 -34
  75. stubber/bulk/mcu_stubber.py +437 -454
  76. stubber/codemod/_partials/__init__.py +48 -48
  77. stubber/codemod/_partials/db_main.py +147 -147
  78. stubber/codemod/_partials/lvgl_main.py +77 -77
  79. stubber/codemod/_partials/modules_reader.py +80 -80
  80. stubber/codemod/add_comment.py +53 -53
  81. stubber/codemod/add_method.py +65 -65
  82. stubber/codemod/board.py +317 -317
  83. stubber/codemod/enrich.py +151 -145
  84. stubber/codemod/merge_docstub.py +284 -284
  85. stubber/codemod/modify_list.py +54 -54
  86. stubber/codemod/utils.py +56 -56
  87. stubber/commands/build_cmd.py +94 -94
  88. stubber/commands/cli.py +49 -55
  89. stubber/commands/clone_cmd.py +78 -78
  90. stubber/commands/config_cmd.py +29 -29
  91. stubber/commands/enrich_folder_cmd.py +71 -71
  92. stubber/commands/get_core_cmd.py +71 -71
  93. stubber/commands/get_docstubs_cmd.py +92 -89
  94. stubber/commands/get_frozen_cmd.py +117 -114
  95. stubber/commands/get_mcu_cmd.py +102 -61
  96. stubber/commands/merge_cmd.py +66 -66
  97. stubber/commands/publish_cmd.py +118 -118
  98. stubber/commands/stub_cmd.py +31 -31
  99. stubber/commands/switch_cmd.py +62 -62
  100. stubber/commands/variants_cmd.py +48 -48
  101. stubber/cst_transformer.py +178 -178
  102. stubber/data/board_info.csv +193 -193
  103. stubber/data/board_info.json +1729 -1729
  104. stubber/data/micropython_tags.csv +15 -15
  105. stubber/data/requirements-core-micropython.txt +38 -38
  106. stubber/data/requirements-core-pycopy.txt +39 -39
  107. stubber/downloader.py +37 -36
  108. stubber/freeze/common.py +72 -68
  109. stubber/freeze/freeze_folder.py +69 -69
  110. stubber/freeze/freeze_manifest_2.py +126 -113
  111. stubber/freeze/get_frozen.py +131 -127
  112. stubber/get_cpython.py +112 -101
  113. stubber/get_lobo.py +59 -59
  114. stubber/minify.py +423 -419
  115. stubber/publish/bump.py +86 -86
  116. stubber/publish/candidates.py +275 -256
  117. stubber/publish/database.py +18 -18
  118. stubber/publish/defaults.py +40 -40
  119. stubber/publish/enums.py +24 -24
  120. stubber/publish/helpers.py +29 -29
  121. stubber/publish/merge_docstubs.py +136 -130
  122. stubber/publish/missing_class_methods.py +51 -49
  123. stubber/publish/package.py +150 -146
  124. stubber/publish/pathnames.py +51 -51
  125. stubber/publish/publish.py +120 -120
  126. stubber/publish/pypi.py +42 -38
  127. stubber/publish/stubpackage.py +1055 -1027
  128. stubber/rst/__init__.py +9 -9
  129. stubber/rst/classsort.py +78 -77
  130. stubber/rst/lookup.py +533 -530
  131. stubber/rst/output_dict.py +401 -401
  132. stubber/rst/reader.py +814 -814
  133. stubber/rst/report_return.py +77 -69
  134. stubber/rst/rst_utils.py +541 -540
  135. stubber/stubber.py +38 -38
  136. stubber/stubs_from_docs.py +90 -90
  137. stubber/tools/manifestfile.py +654 -654
  138. stubber/tools/readme.md +6 -6
  139. stubber/update_fallback.py +117 -117
  140. stubber/update_module_list.py +123 -123
  141. stubber/utils/__init__.py +6 -6
  142. stubber/utils/config.py +137 -125
  143. stubber/utils/makeversionhdr.py +54 -54
  144. stubber/utils/manifest.py +90 -90
  145. stubber/utils/post.py +80 -79
  146. stubber/utils/repos.py +156 -150
  147. stubber/utils/stubmaker.py +139 -139
  148. stubber/utils/typed_config_toml.py +80 -77
  149. stubber/variants.py +106 -106
  150. micropython_stubber-1.23.1.dist-info/RECORD +0 -159
  151. micropython_stubber-1.23.1.dist-info/entry_points.txt +0 -3
  152. mpflash/basicgit.py +0 -288
  153. {micropython_stubber-1.23.1.dist-info → micropython_stubber-1.23.2.dist-info}/WHEEL +0 -0
@@ -1,139 +1,139 @@
1
- """Generate stub files for micropython modules using mypy/stubgen"""
2
-
3
- import re
4
- import sys
5
- from pathlib import Path
6
-
7
- import mypy.stubgen as stubgen
8
- from loguru import logger as log
9
- from mypy.errors import CompileError
10
-
11
- # default stubgen options
12
- STUBGEN_OPT = stubgen.Options(
13
- pyversion=(
14
- 3,
15
- 8,
16
- ), # documentation uses position-only argument indicator which requires 3.8 or higher
17
- no_import=False,
18
- include_private=True,
19
- doc_dir="",
20
- search_path=[],
21
- interpreter=sys.executable,
22
- parse_only=False,
23
- ignore_errors=True,
24
- modules=[],
25
- packages=[],
26
- files=[],
27
- output_dir="",
28
- verbose=True,
29
- quiet=False,
30
- export_less=False,
31
- inspect=False, # inspect needs to import the module in CPython, which is not possible for frozen modules
32
- include_docstrings=True, # include existing docstrings with the stubs
33
- )
34
-
35
-
36
- def generate_pyi_from_file(file: Path) -> bool:
37
- """Generate a .pyi stubfile from a single .py module using mypy/stubgen"""
38
-
39
- sg_opt = STUBGEN_OPT
40
- # Deal with generator passed in
41
- assert isinstance(file, Path)
42
-
43
- sg_opt.files = [str(file)]
44
- sg_opt.output_dir = str(file.parent)
45
- try:
46
- log.debug(f"Calling stubgen on {str(file)}")
47
- # TDOD: Stubgen.generate_stubs does not provide a way to return the errors
48
- # such as `cannot perform relative import`
49
-
50
- stubgen.generate_stubs(sg_opt)
51
- return True
52
- except (Exception, CompileError, SystemExit) as e:
53
- # the only way to know if an error was encountered by generate_stubs
54
- # TODO: Extract info from e.code or e.args[0] and add that to the manifest ?
55
- log.warning(e.args[0])
56
- return False
57
-
58
-
59
- def generate_pyi_files(modules_folder: Path) -> bool:
60
- """
61
- Generate typeshed files for all scripts in a folder using mypy/stubgen
62
-
63
- Returns: False if one or more files had an issue generating a stub
64
- """
65
- # stubgen cannot process folders with duplicate modules ( ie v1.14 and v1.15 )
66
- # NOTE: FIX 1 add __init__.py to umqtt
67
- if (modules_folder / "umqtt/robust.py").exists():
68
- log.debug("add missing : umqtt/__init__.py")
69
- with open(modules_folder / "umqtt" / "__init__.py", "a") as f:
70
- f.write("")
71
-
72
- # rx_const = re.compile(r"const\(([\w_\"']+)\)")
73
- rx_const = re.compile(r"const\(([-*<.,:/\(\) \w_\"']+)\)")
74
- # FIX 2 - replace `const(foo)` with `foo`
75
- for f in modules_folder.rglob("*.py"):
76
- if f.is_file():
77
- with open(f, "r") as file:
78
- data = file.read()
79
- # regex Search for const\(([\w_"']+)\) and replace with (\1)
80
- if rx_const.search(data):
81
- log.debug(f"replace const() in {f}")
82
- data = rx_const.sub(r"\1", data)
83
- with open(f, "w") as file:
84
- file.write(data)
85
-
86
- module_list = list(modules_folder.glob("**/modules.json"))
87
- r = True
88
- if len(module_list) > 1:
89
- # try to process each module separately
90
- for mod_manifest in module_list:
91
- ## generate fyi files for folder
92
- r = r and generate_pyi_files(mod_manifest.parent)
93
- else: # one or less module manifests
94
- ## generate fyi files for folder
95
- log.debug("::group::[stubgen] running stubgen on {0}".format(modules_folder))
96
-
97
- run_per_file = False
98
- sg_opt = STUBGEN_OPT
99
- sg_opt.files = [str(modules_folder)]
100
- sg_opt.output_dir = str(modules_folder)
101
- try:
102
- stubgen.generate_stubs(sg_opt)
103
- except (Exception, CompileError, SystemExit) as e:
104
- if isinstance(e, KeyboardInterrupt):
105
- raise e
106
- # the only way to know if an error was encountered by generate_stubs
107
- # mypy.errors.CompileError and others ?
108
- # TODO: Extract info from e.code or e.args[0]
109
- log.warning(e.args[0])
110
- run_per_file = True
111
-
112
- if run_per_file:
113
- # in case of failure ( duplicate module in subfolder) then Plan B
114
- # - run stubgen on each *.py
115
- log.debug("::group::[stubgen] Failure on folder, attempt to run stubgen per file")
116
- py_files = list(modules_folder.rglob("*.py"))
117
- for py in py_files:
118
- generate_pyi_from_file(py)
119
- # todo: report failures by adding to module manifest
120
-
121
- # for py missing pyi:
122
- py_files = list(modules_folder.rglob("*.py"))
123
- pyi_files = list(modules_folder.rglob("*.pyi"))
124
-
125
- work_list = pyi_files.copy()
126
- for pyi in work_list:
127
- # remove all py files that have been stubbed successfully from the list
128
- try:
129
- py_files.remove(pyi.with_suffix(".py"))
130
- pyi_files.remove(pyi)
131
- except ValueError:
132
- log.debug(f"no matching py for : {str(pyi)}")
133
-
134
- # note in some cases this will try a file twice - but that is better than failing
135
- for py in py_files:
136
- r = r and generate_pyi_from_file(py)
137
- # todo: report failures by adding to module manifest
138
-
139
- return r
1
+ """Generate stub files for micropython modules using mypy/stubgen"""
2
+
3
+ import re
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import mypy.stubgen as stubgen
8
+ from mpflash.logger import log
9
+ from mypy.errors import CompileError
10
+
11
+ # default stubgen options
12
+ STUBGEN_OPT = stubgen.Options(
13
+ pyversion=(
14
+ 3,
15
+ 8,
16
+ ), # documentation uses position-only argument indicator which requires 3.8 or higher
17
+ no_import=False,
18
+ include_private=True,
19
+ doc_dir="",
20
+ search_path=[],
21
+ interpreter=sys.executable,
22
+ parse_only=False,
23
+ ignore_errors=True,
24
+ modules=[],
25
+ packages=[],
26
+ files=[],
27
+ output_dir="",
28
+ verbose=True,
29
+ quiet=False,
30
+ export_less=False,
31
+ inspect=False, # inspect needs to import the module in CPython, which is not possible for frozen modules
32
+ include_docstrings=True, # include existing docstrings with the stubs
33
+ )
34
+
35
+
36
+ def generate_pyi_from_file(file: Path) -> bool:
37
+ """Generate a .pyi stubfile from a single .py module using mypy/stubgen"""
38
+
39
+ sg_opt = STUBGEN_OPT
40
+ # Deal with generator passed in
41
+ assert isinstance(file, Path)
42
+
43
+ sg_opt.files = [str(file)]
44
+ sg_opt.output_dir = str(file.parent)
45
+ try:
46
+ log.debug(f"Calling stubgen on {str(file)}")
47
+ # TDOD: Stubgen.generate_stubs does not provide a way to return the errors
48
+ # such as `cannot perform relative import`
49
+
50
+ stubgen.generate_stubs(sg_opt)
51
+ return True
52
+ except (Exception, CompileError, SystemExit) as e:
53
+ # the only way to know if an error was encountered by generate_stubs
54
+ # TODO: Extract info from e.code or e.args[0] and add that to the manifest ?
55
+ log.warning(e.args[0])
56
+ return False
57
+
58
+
59
+ def generate_pyi_files(modules_folder: Path) -> bool:
60
+ """
61
+ Generate typeshed files for all scripts in a folder using mypy/stubgen
62
+
63
+ Returns: False if one or more files had an issue generating a stub
64
+ """
65
+ # stubgen cannot process folders with duplicate modules ( ie v1.14 and v1.15 )
66
+ # NOTE: FIX 1 add __init__.py to umqtt
67
+ if (modules_folder / "umqtt/robust.py").exists():
68
+ log.debug("add missing : umqtt/__init__.py")
69
+ with open(modules_folder / "umqtt" / "__init__.py", "a") as f:
70
+ f.write("")
71
+
72
+ # rx_const = re.compile(r"const\(([\w_\"']+)\)")
73
+ rx_const = re.compile(r"const\(([-*<.,:/\(\) \w_\"']+)\)")
74
+ # FIX 2 - replace `const(foo)` with `foo`
75
+ for f in modules_folder.rglob("*.py"):
76
+ if f.is_file():
77
+ with open(f, "r") as file:
78
+ data = file.read()
79
+ # regex Search for const\(([\w_"']+)\) and replace with (\1)
80
+ if rx_const.search(data):
81
+ log.debug(f"replace const() in {f}")
82
+ data = rx_const.sub(r"\1", data)
83
+ with open(f, "w") as file:
84
+ file.write(data)
85
+
86
+ module_list = list(modules_folder.glob("**/modules.json"))
87
+ r = True
88
+ if len(module_list) > 1:
89
+ # try to process each module separately
90
+ for mod_manifest in module_list:
91
+ ## generate fyi files for folder
92
+ r = r and generate_pyi_files(mod_manifest.parent)
93
+ else: # one or less module manifests
94
+ ## generate fyi files for folder
95
+ log.debug("::group::[stubgen] running stubgen on {0}".format(modules_folder))
96
+
97
+ run_per_file = False
98
+ sg_opt = STUBGEN_OPT
99
+ sg_opt.files = [str(modules_folder)]
100
+ sg_opt.output_dir = str(modules_folder)
101
+ try:
102
+ stubgen.generate_stubs(sg_opt)
103
+ except (Exception, CompileError, SystemExit) as e:
104
+ if isinstance(e, KeyboardInterrupt):
105
+ raise e
106
+ # the only way to know if an error was encountered by generate_stubs
107
+ # mypy.errors.CompileError and others ?
108
+ # TODO: Extract info from e.code or e.args[0]
109
+ log.warning(e.args[0])
110
+ run_per_file = True
111
+
112
+ if run_per_file:
113
+ # in case of failure ( duplicate module in subfolder) then Plan B
114
+ # - run stubgen on each *.py
115
+ log.debug("::group::[stubgen] Failure on folder, attempt to run stubgen per file")
116
+ py_files = list(modules_folder.rglob("*.py"))
117
+ for py in py_files:
118
+ generate_pyi_from_file(py)
119
+ # todo: report failures by adding to module manifest
120
+
121
+ # for py missing pyi:
122
+ py_files = list(modules_folder.rglob("*.py"))
123
+ pyi_files = list(modules_folder.rglob("*.pyi"))
124
+
125
+ work_list = pyi_files.copy()
126
+ for pyi in work_list:
127
+ # remove all py files that have been stubbed successfully from the list
128
+ try:
129
+ py_files.remove(pyi.with_suffix(".py"))
130
+ pyi_files.remove(pyi)
131
+ except ValueError:
132
+ log.debug(f"no matching py for : {str(pyi)}")
133
+
134
+ # note in some cases this will try a file twice - but that is better than failing
135
+ for py in py_files:
136
+ r = r and generate_pyi_from_file(py)
137
+ # todo: report failures by adding to module manifest
138
+
139
+ return r
@@ -1,77 +1,80 @@
1
- """
2
- typed-config-toml
3
-
4
- Extend typed-config to read configuration from .toml files
5
-
6
- """
7
- # TODO : extend support for . notation in section names
8
-
9
- from pathlib import Path
10
- from typing import Dict, Optional
11
-
12
- try:
13
- import tomllib # type: ignore
14
- except ModuleNotFoundError:
15
- import tomli as tomllib # type: ignore
16
- assert tomllib
17
-
18
- from loguru import logger as log
19
- from typedconfig.source import ConfigSource
20
-
21
-
22
- class TomlConfigSource(ConfigSource):
23
- """Read configuration from a .toml file
24
-
25
- prefix is used to allow for toml nested configuration
26
- a common prefix = "tool."
27
-
28
- ```
29
- #pyproject.toml
30
- [tool.deadparrot]
31
- species = "Norwegian Blue"
32
- state = "resting"
33
- details = ["pinging","Lovely plumage","3"]
34
- ```
35
- Use the below code to retrieve:
36
- ```
37
- # TODO sample code
38
- ```
39
- """
40
-
41
- def __init__(self, filename: str, prefix: Optional[str] = None, must_exist: bool = True):
42
- self.filename = filename
43
- toml_dict = {}
44
- if Path(self.filename).exists():
45
- # Read data - will raise an exception if problem with file
46
- try:
47
- with open(filename, "rb") as f:
48
- toml_dict = tomllib.load(f)
49
- except tomllib.TOMLDecodeError: # pragma: no cover
50
- log.warning("unable to read ")
51
- elif must_exist:
52
- raise FileNotFoundError(f"Could not find config file {self.filename}")
53
- if not prefix or len(prefix) == 0:
54
- self.data = toml_dict
55
- else:
56
- # common prefix = "tool."
57
- try:
58
- self.data = toml_dict[prefix.rstrip(".")]
59
- except KeyError: # pragma: no cover
60
- self.data = {}
61
-
62
- # Quick checks on data format
63
- assert isinstance(self.data, Dict)
64
- for k, v in self.data.items():
65
- assert isinstance(k, str)
66
- assert isinstance(v, Dict)
67
- for v_k, v_v in v.items(): # type: ignore
68
- assert isinstance(v_k, str)
69
- # do not assume/require that all values are strings
70
- # assert isinstance(v_v, str)
71
- # Convert all keys to lowercase
72
- self.data = {k.lower(): {v_k.lower(): v_v for v_k, v_v in v.items()} for k, v in self.data.items()}
73
-
74
- def get_config_value(self, section_name: str, key_name: str) -> Optional[str]:
75
- # Extract info from data which we read in during __init__
76
- section = self.data.get(section_name.lower(), None)
77
- return None if section is None else section.get(key_name.lower(), None)
1
+ """
2
+ typed-config-toml
3
+
4
+ Extend typed-config to read configuration from .toml files
5
+
6
+ """
7
+
8
+ # TODO : extend support for . notation in section names
9
+
10
+ from pathlib import Path
11
+ from typing import Dict, Optional
12
+
13
+ try:
14
+ import tomllib # type: ignore
15
+ except ModuleNotFoundError:
16
+ import tomli as tomllib # type: ignore
17
+ assert tomllib
18
+
19
+ from mpflash.logger import log
20
+ from typedconfig.source import ConfigSource
21
+
22
+
23
+ class TomlConfigSource(ConfigSource):
24
+ """Read configuration from a .toml file
25
+
26
+ prefix is used to allow for toml nested configuration
27
+ a common prefix = "tool."
28
+
29
+ ```
30
+ #pyproject.toml
31
+ [tool.deadparrot]
32
+ species = "Norwegian Blue"
33
+ state = "resting"
34
+ details = ["pinging","Lovely plumage","3"]
35
+ ```
36
+ Use the below code to retrieve:
37
+ ```
38
+ # TODO sample code
39
+ ```
40
+ """
41
+
42
+ def __init__(self, filename: str, prefix: Optional[str] = None, must_exist: bool = True):
43
+ self.filename = filename
44
+ toml_dict = {}
45
+ if Path(self.filename).exists():
46
+ # Read data - will raise an exception if problem with file
47
+ try:
48
+ with open(filename, "rb") as f:
49
+ toml_dict = tomllib.load(f)
50
+ except tomllib.TOMLDecodeError: # pragma: no cover
51
+ log.warning("unable to read ")
52
+ elif must_exist:
53
+ raise FileNotFoundError(f"Could not find config file {self.filename}")
54
+ if not prefix or len(prefix) == 0:
55
+ self.data = toml_dict
56
+ else:
57
+ # common prefix = "tool."
58
+ try:
59
+ self.data = toml_dict[prefix.rstrip(".")]
60
+ except KeyError: # pragma: no cover
61
+ self.data = {}
62
+
63
+ # Quick checks on data format
64
+ assert isinstance(self.data, Dict)
65
+ for k, v in self.data.items():
66
+ assert isinstance(k, str)
67
+ assert isinstance(v, Dict)
68
+ for v_k, v_v in v.items(): # type: ignore
69
+ assert isinstance(v_k, str)
70
+ # do not assume/require that all values are strings
71
+ # assert isinstance(v_v, str)
72
+ # Convert all keys to lowercase
73
+ self.data = {
74
+ k.lower(): {v_k.lower(): v_v for v_k, v_v in v.items()} for k, v in self.data.items()
75
+ }
76
+
77
+ def get_config_value(self, section_name: str, key_name: str) -> Optional[str]:
78
+ # Extract info from data which we read in during __init__
79
+ section = self.data.get(section_name.lower(), None)
80
+ return None if section is None else section.get(key_name.lower(), None)
stubber/variants.py CHANGED
@@ -1,106 +1,106 @@
1
- """
2
- Create all variants of createstubs.py
3
- - and minify them
4
- - and cross compile them
5
- """
6
-
7
- import shutil
8
- from pathlib import Path
9
- from typing import List, Optional
10
-
11
- import libcst as cst
12
- import libcst.codemod as codemod
13
- from loguru import logger as log
14
-
15
- from stubber.codemod.board import CreateStubsCodemod, CreateStubsVariant
16
- from stubber.codemod.modify_list import ListChangeSet # type: ignore
17
- from stubber.minify import cross_compile, minify
18
- from stubber.update_module_list import update_module_list
19
- from stubber.utils.post import run_black
20
-
21
- ALL_VARIANTS = list(CreateStubsVariant)
22
-
23
-
24
- def create_variants(
25
- base_path: Path,
26
- *,
27
- target_path: Optional[Path] = None,
28
- version: str = "",
29
- make_variants: List[CreateStubsVariant] = ALL_VARIANTS[:3],
30
- update_modules: bool = True,
31
- ):
32
- """
33
- Create variants of createstubs.py and optionally minify and cross compile them.
34
-
35
- Parameters
36
- ----------
37
- base_path : Path
38
- Path to the base createstubs.py file
39
- target_path : Path, optional
40
- Path to write the variants to, by default None
41
- version : str, optional
42
- Version of mpy-cross to use, by default uses the latest published version
43
-
44
- """
45
- if target_path is None:
46
- target_path = base_path
47
- if update_modules:
48
- update_module_list()
49
-
50
- ctx = codemod.CodemodContext()
51
- base_file = base_path / "createstubs.py"
52
- log.info(f"Reading : {base_file}")
53
- base_txt = (base_path / "createstubs.py").read_text(encoding="utf-8")
54
- base_module = cst.parse_module(base_txt)
55
-
56
- for var in make_variants:
57
- # Transform base to createstubs.py variant
58
-
59
- suffix = "" if var == CreateStubsVariant.BASE else f"_{var.value}"
60
-
61
- variant_path = target_path / f"createstubs{suffix}.py"
62
- minified_path = target_path / f"createstubs{suffix}_min.py"
63
- mpy_path = target_path / f"createstubs{suffix}_mpy.mpy" # intentional
64
-
65
- if var == CreateStubsVariant.BASE and target_path != base_path:
66
- log.info(f"Copying base file to {variant_path}")
67
- variant_path.write_text(base_txt)
68
- # copy modules.txt to target_path
69
- shutil.copyfile(base_path / "modulelist.txt", target_path / "modulelist.txt")
70
-
71
- if var != CreateStubsVariant.BASE:
72
- # No need to create base variant as it is the same as the base file
73
- log.info(f"Transforming to {var.value} variant")
74
- cm = CreateStubsCodemod(ctx, variant=var)
75
- variant = cm.transform_module(base_module)
76
-
77
- # write low_mem_variant.code to file
78
- log.info(f"Write variant {var.value} to {variant_path}")
79
- with open(variant_path, "w") as f:
80
- f.write(variant.code)
81
-
82
- # format file with black
83
- run_black(variant_path, capture_output=True)
84
- # TODO: check with pyright if it is valid python
85
-
86
- # Minify file with pyminifier
87
- log.info(f"Minifying to {minified_path.name}")
88
- minify(variant_path, minified_path, keep_report=False, diff=False)
89
-
90
- # str -> path
91
- # read minified file
92
- minified_txt = minified_path.read_text(encoding="utf-8")
93
- cross_compile(minified_txt, mpy_path, version=version)
94
-
95
-
96
- if __name__ == "__main__":
97
- # read base createstubs.py
98
- base_path = Path.cwd() / "src" / "stubber" / "board"
99
- create_variants(base_path)
100
-
101
- # if 0:
102
- # # custom modules (and skip defaults).
103
- # custom_stubs = ListChangeSet.from_strings(add=["mycoolpackage", "othermodule"], replace=True)
104
- # custom_variant = CreateStubsCodemod(ctx, modules=custom_stubs).transform_module(base_module)
105
-
106
- # print(custom_variant.code)
1
+ """
2
+ Create all variants of createstubs.py
3
+ - and minify them
4
+ - and cross compile them
5
+ """
6
+
7
+ import shutil
8
+ from pathlib import Path
9
+ from typing import List, Optional
10
+
11
+ import libcst as cst
12
+ import libcst.codemod as codemod
13
+ from mpflash.logger import log
14
+
15
+ from stubber.codemod.board import CreateStubsCodemod, CreateStubsVariant
16
+ from stubber.codemod.modify_list import ListChangeSet # type: ignore
17
+ from stubber.minify import cross_compile, minify
18
+ from stubber.update_module_list import update_module_list
19
+ from stubber.utils.post import run_black
20
+
21
+ ALL_VARIANTS = list(CreateStubsVariant)
22
+
23
+
24
+ def create_variants(
25
+ base_path: Path,
26
+ *,
27
+ target_path: Optional[Path] = None,
28
+ version: str = "",
29
+ make_variants: List[CreateStubsVariant] = ALL_VARIANTS[:3],
30
+ update_modules: bool = True,
31
+ ):
32
+ """
33
+ Create variants of createstubs.py and optionally minify and cross compile them.
34
+
35
+ Parameters
36
+ ----------
37
+ base_path : Path
38
+ Path to the base createstubs.py file
39
+ target_path : Path, optional
40
+ Path to write the variants to, by default None
41
+ version : str, optional
42
+ Version of mpy-cross to use, by default uses the latest published version
43
+
44
+ """
45
+ if target_path is None:
46
+ target_path = base_path
47
+ if update_modules:
48
+ update_module_list()
49
+
50
+ ctx = codemod.CodemodContext()
51
+ base_file = base_path / "createstubs.py"
52
+ log.info(f"Reading : {base_file}")
53
+ base_txt = (base_path / "createstubs.py").read_text(encoding="utf-8")
54
+ base_module = cst.parse_module(base_txt)
55
+
56
+ for var in make_variants:
57
+ # Transform base to createstubs.py variant
58
+
59
+ suffix = "" if var == CreateStubsVariant.BASE else f"_{var.value}"
60
+
61
+ variant_path = target_path / f"createstubs{suffix}.py"
62
+ minified_path = target_path / f"createstubs{suffix}_min.py"
63
+ mpy_path = target_path / f"createstubs{suffix}_mpy.mpy" # intentional
64
+
65
+ if var == CreateStubsVariant.BASE and target_path != base_path:
66
+ log.info(f"Copying base file to {variant_path}")
67
+ variant_path.write_text(base_txt)
68
+ # copy modules.txt to target_path
69
+ shutil.copyfile(base_path / "modulelist.txt", target_path / "modulelist.txt")
70
+
71
+ if var != CreateStubsVariant.BASE:
72
+ # No need to create base variant as it is the same as the base file
73
+ log.info(f"Transforming to {var.value} variant")
74
+ cm = CreateStubsCodemod(ctx, variant=var)
75
+ variant = cm.transform_module(base_module)
76
+
77
+ # write low_mem_variant.code to file
78
+ log.info(f"Write variant {var.value} to {variant_path}")
79
+ with open(variant_path, "w") as f:
80
+ f.write(variant.code)
81
+
82
+ # format file with black
83
+ run_black(variant_path, capture_output=True)
84
+ # TODO: check with pyright if it is valid python
85
+
86
+ # Minify file with pyminifier
87
+ log.info(f"Minifying to {minified_path.name}")
88
+ minify(variant_path, minified_path, keep_report=False, diff=False)
89
+
90
+ # str -> path
91
+ # read minified file
92
+ minified_txt = minified_path.read_text(encoding="utf-8")
93
+ cross_compile(minified_txt, mpy_path, version=version)
94
+
95
+
96
+ if __name__ == "__main__":
97
+ # read base createstubs.py
98
+ base_path = Path.cwd() / "src" / "stubber" / "board"
99
+ create_variants(base_path)
100
+
101
+ # if 0:
102
+ # # custom modules (and skip defaults).
103
+ # custom_stubs = ListChangeSet.from_strings(add=["mycoolpackage", "othermodule"], replace=True)
104
+ # custom_variant = CreateStubsCodemod(ctx, modules=custom_stubs).transform_module(base_module)
105
+
106
+ # print(custom_variant.code)