[core] Fix importing ltchiptool after updating

This commit is contained in:
Kuba Szczodrzyński
2023-01-02 17:05:35 +01:00
parent db0ab41ea4
commit f9967ff990

View File

@@ -14,31 +14,50 @@ from platformio.package.manager.base import BasePackageManager
from platformio.package.meta import PackageItem, PackageSpec from platformio.package.meta import PackageItem, PackageSpec
from platformio.platform.base import PlatformBase from platformio.platform.base import PlatformBase
from platformio.platform.board import PlatformBoardConfig from platformio.platform.board import PlatformBoardConfig
from semantic_version import Version from semantic_version import SimpleSpec, Version
LTCHIPTOOL_VERSION = "^2.0.2"
# Install & import tools # Install & import tools
def check_ltchiptool(): def check_ltchiptool(install: bool):
global ltchiptool ltchiptool = importlib.import_module("ltchiptool")
import ltchiptool
importlib.reload(ltchiptool) if Version(ltchiptool.get_version()) in SimpleSpec(LTCHIPTOOL_VERSION):
if Version(ltchiptool.get_version()) < Version("2.0.2"): return
if not install:
raise ImportError("Version too old") raise ImportError("Version too old")
# update ltchiptool to a supported version
try:
check_ltchiptool()
except (ImportError, AttributeError):
print("Installing/updating ltchiptool") print("Installing/updating ltchiptool")
system(" ".join([sys.executable, "-m", "pip install -U ltchiptool"])) system(f"{sys.executable} -m pip install -U ltchiptool=={LTCHIPTOOL_VERSION}")
try:
check_ltchiptool() # unload all modules from the old version
except (ImportError, AttributeError) as e: for name, module in list(sorted(sys.modules.items())):
print( if not name.startswith("ltchiptool"):
f"!!! Installing ltchiptool failed, or version outdated. Cannot continue: {e}" continue
) del sys.modules[name]
raise e del module
def try_check_ltchiptool():
install_modes = [True, False]
exception = None
for install in install_modes:
try:
check_ltchiptool(install)
return
except (ImportError, AttributeError) as ex:
exception = ex
print(
"!!! Installing ltchiptool failed, or version outdated. "
"Please install ltchiptool manually using pip. "
f"Cannot continue: {exception}"
)
raise exception
try_check_ltchiptool()
import ltchiptool
# Remove current dir so it doesn't conflict with PIO # Remove current dir so it doesn't conflict with PIO
if dirname(__file__) in sys.path: if dirname(__file__) in sys.path: