Skip to content

Commit 4af6ade

Browse files
authored
Refactor: using Path instead of join (#281)
1 parent a806056 commit 4af6ade

File tree

9 files changed

+615
-512
lines changed

9 files changed

+615
-512
lines changed

builder/frameworks/_embed_files.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
import shutil
1616
from os import SEEK_CUR, SEEK_END
17-
from os.path import basename, isfile, join
17+
from os.path import basename, isfile
18+
from pathlib import Path
1819

1920
from SCons.Script import Builder
2021

@@ -24,6 +25,14 @@
2425
mcu = board.get("build.mcu", "esp32")
2526
is_xtensa = mcu in ("esp32", "esp32s2", "esp32s3")
2627

28+
cmake_dir = str(env.PioPlatform().get_package_dir("tool-cmake"))
29+
cmake_cmd = f'"{Path(cmake_dir) / "bin" / "cmake"}"'
30+
31+
idf_dir = str(env.PioPlatform().get_package_dir("framework-espidf"))
32+
data_embed_script = (
33+
f'"{Path(idf_dir) / "tools" / "cmake" / "scripts" / "data_file_embed_asm.cmake"}"'
34+
)
35+
2736
#
2837
# Embedded files helpers
2938
#
@@ -33,7 +42,7 @@ def extract_files(cppdefines, files_type):
3342
result = []
3443
files = env.GetProjectOption("board_build.%s" % files_type, "").splitlines()
3544
if files:
36-
result.extend([join("$PROJECT_DIR", f.strip()) for f in files if f])
45+
result.extend([str(Path("$PROJECT_DIR") / f.strip()) for f in files if f.strip()])
3746
else:
3847
files_define = "COMPONENT_" + files_type.upper()
3948
for define in cppdefines:
@@ -53,9 +62,10 @@ def extract_files(cppdefines, files_type):
5362
return []
5463

5564
for f in value.split(":"):
65+
f = f.strip()
5666
if not f:
5767
continue
58-
result.append(join("$PROJECT_DIR", f))
68+
result.append(str(Path("$PROJECT_DIR") / f))
5969

6070
for f in result:
6171
if not isfile(env.subst(f)):
@@ -76,10 +86,14 @@ def prepare_file(source, target, env):
7686
shutil.copy(filepath, filepath + ".piobkp")
7787

7888
with open(filepath, "rb+") as fp:
79-
fp.seek(-1, SEEK_END)
80-
if fp.read(1) != "\0":
81-
fp.seek(0, SEEK_CUR)
89+
fp.seek(0, SEEK_END)
90+
size = fp.tell()
91+
if size == 0:
8292
fp.write(b"\0")
93+
else:
94+
fp.seek(-1, SEEK_END)
95+
if fp.read(1) != b"\0":
96+
fp.write(b"\0")
8397

8498

8599
def revert_original_file(source, target, env):
@@ -91,17 +105,17 @@ def revert_original_file(source, target, env):
91105
def embed_files(files, files_type):
92106
for f in files:
93107
filename = basename(f) + ".txt.o"
94-
file_target = env.TxtToBin(join("$BUILD_DIR", filename), f)
108+
file_target = env.TxtToBin(str(Path("$BUILD_DIR") / filename), f)
95109
env.Depends("$PIOMAINPROG", file_target)
96110
if files_type == "embed_txtfiles":
97111
env.AddPreAction(file_target, prepare_file)
98112
env.AddPostAction(file_target, revert_original_file)
99-
env.AppendUnique(PIOBUILDFILES=[env.File(join("$BUILD_DIR", filename))])
113+
env.AppendUnique(PIOBUILDFILES=[env.File(str(Path("$BUILD_DIR") / filename))])
100114

101115

102116
def transform_to_asm(target, source, env):
103-
files = [join("$BUILD_DIR", s.name + ".S") for s in source]
104-
return files, source
117+
asm_targets = [str(Path("$BUILD_DIR") / (s.name + ".S")) for s in source]
118+
return asm_targets, source
105119

106120

107121
env.Append(
@@ -133,22 +147,12 @@ def transform_to_asm(target, source, env):
133147
action=env.VerboseAction(
134148
" ".join(
135149
[
136-
join(
137-
env.PioPlatform().get_package_dir("tool-cmake") or "",
138-
"bin",
139-
"cmake",
140-
),
150+
cmake_cmd,
141151
"-DDATA_FILE=$SOURCE",
142152
"-DSOURCE_FILE=$TARGET",
143153
"-DFILE_TYPE=$FILE_TYPE",
144154
"-P",
145-
join(
146-
env.PioPlatform().get_package_dir("framework-espidf") or "",
147-
"tools",
148-
"cmake",
149-
"scripts",
150-
"data_file_embed_asm.cmake",
151-
),
155+
data_embed_script,
152156
]
153157
),
154158
"Generating assembly for $TARGET",
@@ -171,7 +175,7 @@ def transform_to_asm(target, source, env):
171175
files = extract_files(flags, files_type)
172176
if "espidf" in env.subst("$PIOFRAMEWORK"):
173177
env.Requires(
174-
join("$BUILD_DIR", "${PROGNAME}.elf"),
178+
str(Path("$BUILD_DIR") / "${PROGNAME}.elf"),
175179
env.FileToAsm(
176180
files,
177181
FILE_TYPE="TEXT" if files_type == "embed_txtfiles" else "BINARY",

builder/frameworks/arduino.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@
3535
from SCons.Script import DefaultEnvironment, SConscript
3636
from platformio import fs
3737
from platformio.package.manager.tool import ToolPackageManager
38-
39-
IS_WINDOWS = sys.platform.startswith("win")
38+
from platformio.compat import IS_WINDOWS
4039

4140
# Constants for better performance
4241
UNICORE_FLAGS = {
@@ -73,7 +72,7 @@ def get_platform_default_threshold(mcu):
7372
"esp32": 32000, # Standard ESP32
7473
"esp32s2": 32000, # ESP32-S2
7574
"esp32s3": 32766, # ESP32-S3
76-
"esp32c3": 30000, # ESP32-C3
75+
"esp32c3": 32000, # ESP32-C3
7776
"esp32c2": 32000, # ESP32-C2
7877
"esp32c6": 31600, # ESP32-C6
7978
"esp32h2": 32000, # ESP32-H2
@@ -311,7 +310,7 @@ def framework_lib_dir(self):
311310
def sdk_dir(self):
312311
if self._sdk_dir is None:
313312
self._sdk_dir = fs.to_unix_path(
314-
join(self.framework_lib_dir, self.mcu, "include")
313+
str(Path(self.framework_lib_dir) / self.mcu / "include")
315314
)
316315
return self._sdk_dir
317316

@@ -507,7 +506,7 @@ def safe_remove_sdkconfig_files():
507506
envs = [section.replace("env:", "") for section in config.sections()
508507
if section.startswith("env:")]
509508
for env_name in envs:
510-
file_path = join(project_dir, f"sdkconfig.{env_name}")
509+
file_path = str(Path(project_dir) / f"sdkconfig.{env_name}")
511510
if exists(file_path):
512511
safe_delete_file(file_path)
513512

@@ -566,9 +565,7 @@ def safe_remove_sdkconfig_files():
566565

567566
SConscript("_embed_files.py", exports="env")
568567

569-
flag_any_custom_sdkconfig = exists(join(
570-
platform.get_package_dir("framework-arduinoespressif32-libs"),
571-
"sdkconfig"))
568+
flag_any_custom_sdkconfig = exists(str(Path(FRAMEWORK_LIB_DIR) / "sdkconfig"))
572569

573570

574571
def has_unicore_flags():
@@ -599,7 +596,7 @@ def matching_custom_sdkconfig():
599596
if not flag_any_custom_sdkconfig:
600597
return True, cust_sdk_is_present
601598

602-
last_sdkconfig_path = join(project_dir, "sdkconfig.defaults")
599+
last_sdkconfig_path = str(Path(project_dir) / "sdkconfig.defaults")
603600
if not exists(last_sdkconfig_path):
604601
return False, cust_sdk_is_present
605602

@@ -901,12 +898,12 @@ def get_frameworks_in_current_env():
901898
component_manager = ComponentManager(env)
902899
component_manager.handle_component_settings()
903900
silent_action = env.Action(component_manager.restore_pioarduino_build_py)
904-
# hack to silence scons command output
901+
# silence scons command output
905902
silent_action.strfunction = lambda target, source, env: ''
906903
env.AddPostAction("checkprogsize", silent_action)
907904

908905
if IS_WINDOWS:
909906
env.AddBuildMiddleware(smart_include_length_shorten)
910907

911-
build_script_path = join(FRAMEWORK_DIR, "tools", "pioarduino-build.py")
908+
build_script_path = str(Path(FRAMEWORK_DIR) / "tools" / "pioarduino-build.py")
912909
SConscript(build_script_path)

builder/frameworks/component_manager.py

Lines changed: 43 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import re
1414
import yaml
1515
from yaml import SafeLoader
16-
from os.path import join
16+
from pathlib import Path
1717
from typing import Set, Optional, Dict, Any, List, Tuple
1818

1919

@@ -49,8 +49,12 @@ def __init__(self, env):
4949
self.project_src_dir = env.subst("$PROJECT_SRC_DIR")
5050
# Get Arduino framework installation directory
5151
self.arduino_framework_dir = self.platform.get_package_dir("framework-arduinoespressif32")
52+
# Get Arduino libraries installation directory
53+
ald = self.platform.get_package_dir("framework-arduinoespressif32-libs")
5254
# Get MCU-specific Arduino libraries directory
53-
self.arduino_libs_mcu = join(self.platform.get_package_dir("framework-arduinoespressif32-libs"), self.mcu)
55+
self.arduino_libs_mcu = (
56+
str(Path(ald) / self.mcu) if ald else ""
57+
)
5458

5559

5660
class ComponentLogger:
@@ -228,13 +232,14 @@ def _get_or_create_component_yml(self) -> str:
228232
Absolute path to the component YAML file
229233
"""
230234
# Try Arduino framework first
231-
framework_yml = join(self.config.arduino_framework_dir, "idf_component.yml")
232-
if os.path.exists(framework_yml):
235+
afd = self.config.arduino_framework_dir
236+
framework_yml = str(Path(afd) / "idf_component.yml") if afd else ""
237+
if framework_yml and os.path.exists(framework_yml):
233238
self._create_backup(framework_yml)
234239
return framework_yml
235240

236241
# Try project source directory
237-
project_yml = join(self.config.project_src_dir, "idf_component.yml")
242+
project_yml = str(Path(self.config.project_src_dir) / "idf_component.yml")
238243
if os.path.exists(project_yml):
239244
self._create_backup(project_yml)
240245
return project_yml
@@ -416,9 +421,12 @@ def _backup_pioarduino_build_py(self) -> None:
416421
"""
417422
if "arduino" not in self.config.env.subst("$PIOFRAMEWORK"):
418423
return
419-
420-
build_py_path = join(self.config.arduino_libs_mcu, "pioarduino-build.py")
421-
backup_path = join(self.config.arduino_libs_mcu, f"pioarduino-build.py.{self.config.mcu}")
424+
425+
if not self.config.arduino_libs_mcu:
426+
return
427+
428+
build_py_path = str(Path(self.config.arduino_libs_mcu) / "pioarduino-build.py")
429+
backup_path = str(Path(self.config.arduino_libs_mcu) / f"pioarduino-build.py.{self.config.mcu}")
422430

423431
if os.path.exists(build_py_path) and not os.path.exists(backup_path):
424432
shutil.copy2(build_py_path, backup_path)
@@ -446,7 +454,7 @@ def _remove_include_directory(self, component: str) -> None:
446454
Args:
447455
component: Component name in filesystem format
448456
"""
449-
include_path = join(self.config.arduino_libs_mcu, "include", component)
457+
include_path = str(Path(self.config.arduino_libs_mcu) / "include" / component)
450458

451459
if os.path.exists(include_path):
452460
shutil.rmtree(include_path)
@@ -459,7 +467,7 @@ def _remove_cpppath_entries(self) -> None:
459467
for all components that were removed from the project. Uses
460468
multiple regex patterns to catch different include path formats.
461469
"""
462-
build_py_path = join(self.config.arduino_libs_mcu, "pioarduino-build.py")
470+
build_py_path = str(Path(self.config.arduino_libs_mcu) / "pioarduino-build.py")
463471

464472
if not os.path.exists(build_py_path):
465473
return
@@ -667,14 +675,17 @@ def _get_arduino_core_libraries(self) -> Dict[str, str]:
667675
libraries_mapping = {}
668676

669677
# Path to Arduino Core Libraries
670-
arduino_libs_dir = join(self.config.arduino_framework_dir, "libraries")
678+
afd = self.config.arduino_framework_dir
679+
if not afd:
680+
return libraries_mapping
681+
arduino_libs_dir = str(Path(afd).resolve() / "libraries")
671682

672683
if not os.path.exists(arduino_libs_dir):
673684
return libraries_mapping
674685

675686
try:
676687
for entry in os.listdir(arduino_libs_dir):
677-
lib_path = join(arduino_libs_dir, entry)
688+
lib_path = str(Path(arduino_libs_dir) / entry)
678689
if os.path.isdir(lib_path):
679690
lib_name = self._get_library_name_from_properties(lib_path)
680691
if lib_name:
@@ -699,7 +710,7 @@ def _get_library_name_from_properties(self, lib_dir: str) -> Optional[str]:
699710
Returns:
700711
Official library name or None if not found or readable
701712
"""
702-
prop_path = join(lib_dir, "library.properties")
713+
prop_path = str(Path(lib_dir) / "library.properties")
703714
if not os.path.isfile(prop_path):
704715
return None
705716

@@ -891,7 +902,7 @@ def _remove_ignored_lib_includes(self) -> None:
891902
components when dependencies are detected. Uses multiple regex
892903
patterns to catch different include path formats.
893904
"""
894-
build_py_path = join(self.config.arduino_libs_mcu, "pioarduino-build.py")
905+
build_py_path = str(Path(self.config.arduino_libs_mcu) / "pioarduino-build.py")
895906

896907
if not os.path.exists(build_py_path):
897908
self.logger.log_change("Build file not found")
@@ -930,7 +941,10 @@ def _remove_ignored_lib_includes(self) -> None:
930941
rf'.*"[^"]*{re.escape(lib_name)}[^"]*include[^"]*"[^,\n]*,?\n',
931942
rf'.*join\([^)]*"include"[^)]*"{re.escape(lib_name)}"[^)]*\),?\n',
932943
rf'.*"{re.escape(lib_name)}/include"[^,\n]*,?\n',
933-
rf'\s*"[^"]*/{re.escape(lib_name)}/[^"]*",?\n'
944+
rf'\s*"[^"]*[\\/]{re.escape(lib_name)}[\\/][^"]*",?\n',
945+
# pathlib-style: Path(...)/"include"/"<name>"
946+
rf'.*Path\([^)]*\)\s*/\s*"include"\s*/\s*"{re.escape(lib_name)}"[^,\n]*,?\n',
947+
rf'.*Path\([^)]*{re.escape(lib_name)}[^)]*\)\s*/\s*"include"[^,\n]*,?\n'
934948
]
935949

936950
removed_count = 0
@@ -992,8 +1006,10 @@ def _backup_pioarduino_build_py(self) -> None:
9921006
if "arduino" not in self.config.env.subst("$PIOFRAMEWORK"):
9931007
return
9941008

995-
build_py_path = join(self.config.arduino_libs_mcu, "pioarduino-build.py")
996-
backup_path = join(self.config.arduino_libs_mcu, f"pioarduino-build.py.{self.config.mcu}")
1009+
if not self.config.arduino_libs_mcu:
1010+
return
1011+
build_py_path = str(Path(self.config.arduino_libs_mcu) / "pioarduino-build.py")
1012+
backup_path = str(Path(self.config.arduino_libs_mcu) / f"pioarduino-build.py.{self.config.mcu}")
9971013

9981014
if os.path.exists(build_py_path) and not os.path.exists(backup_path):
9991015
shutil.copy2(build_py_path, backup_path)
@@ -1007,7 +1023,7 @@ class BackupManager:
10071023
framework build scripts, ensuring that original files can be restored
10081024
when needed or when builds are cleaned.
10091025
"""
1010-
1026+
10111027
def __init__(self, config: ComponentManagerConfig):
10121028
"""
10131029
Initialize the backup manager with configuration access.
@@ -1019,7 +1035,7 @@ def __init__(self, config: ComponentManagerConfig):
10191035
config: Configuration manager instance providing access to paths
10201036
"""
10211037
self.config = config
1022-
1038+
10231039
def backup_pioarduino_build_py(self) -> None:
10241040
"""
10251041
Create backup of the original pioarduino-build.py file.
@@ -1030,13 +1046,13 @@ def backup_pioarduino_build_py(self) -> None:
10301046
"""
10311047
if "arduino" not in self.config.env.subst("$PIOFRAMEWORK"):
10321048
return
1033-
1034-
build_py_path = join(self.config.arduino_libs_mcu, "pioarduino-build.py")
1035-
backup_path = join(self.config.arduino_libs_mcu, f"pioarduino-build.py.{self.config.mcu}")
1036-
1049+
1050+
build_py_path = str(Path(self.config.arduino_libs_mcu) / "pioarduino-build.py")
1051+
backup_path = str(Path(self.config.arduino_libs_mcu) / f"pioarduino-build.py.{self.config.mcu}")
1052+
10371053
if os.path.exists(build_py_path) and not os.path.exists(backup_path):
10381054
shutil.copy2(build_py_path, backup_path)
1039-
1055+
10401056
def restore_pioarduino_build_py(self, target=None, source=None, env=None) -> None:
10411057
"""
10421058
Restore the original pioarduino-build.py from backup.
@@ -1050,9 +1066,9 @@ def restore_pioarduino_build_py(self, target=None, source=None, env=None) -> Non
10501066
source: Build source (unused, for PlatformIO compatibility)
10511067
env: Environment (unused, for PlatformIO compatibility)
10521068
"""
1053-
build_py_path = join(self.config.arduino_libs_mcu, "pioarduino-build.py")
1054-
backup_path = join(self.config.arduino_libs_mcu, f"pioarduino-build.py.{self.config.mcu}")
1055-
1069+
build_py_path = str(Path(self.config.arduino_libs_mcu) / "pioarduino-build.py")
1070+
backup_path = str(Path(self.config.arduino_libs_mcu) / f"pioarduino-build.py.{self.config.mcu}")
1071+
10561072
if os.path.exists(backup_path):
10571073
shutil.copy2(backup_path, build_py_path)
10581074
os.remove(backup_path)

0 commit comments

Comments
 (0)