🔨 Simplify scripts with pathlib (#24574)

This commit is contained in:
Scott Lahteine 2022-08-01 01:14:58 -05:00
parent c3f2586445
commit 3b30951e83
14 changed files with 182 additions and 196 deletions

View File

@ -12,7 +12,7 @@ if pioutil.is_pio_build():
target_filename = "FIRMWARE.CUR" target_filename = "FIRMWARE.CUR"
target_drive = "REARM" target_drive = "REARM"
import os,getpass,platform import platform
current_OS = platform.system() current_OS = platform.system()
Import("env") Import("env")
@ -26,7 +26,8 @@ if pioutil.is_pio_build():
def before_upload(source, target, env): def before_upload(source, target, env):
try: try:
# from pathlib import Path
#
# Find a disk for upload # Find a disk for upload
# #
upload_disk = 'Disk not found' upload_disk = 'Disk not found'
@ -38,6 +39,7 @@ if pioutil.is_pio_build():
# Windows - doesn't care about the disk's name, only cares about the drive letter # Windows - doesn't care about the disk's name, only cares about the drive letter
import subprocess,string import subprocess,string
from ctypes import windll from ctypes import windll
from pathlib import PureWindowsPath
# getting list of drives # getting list of drives
# https://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python # https://stackoverflow.com/questions/827371/is-there-a-way-to-list-all-the-available-drive-letters-in-python
@ -49,7 +51,7 @@ if pioutil.is_pio_build():
bitmask >>= 1 bitmask >>= 1
for drive in drives: for drive in drives:
final_drive_name = drive + ':\\' final_drive_name = drive + ':'
# print ('disc check: {}'.format(final_drive_name)) # print ('disc check: {}'.format(final_drive_name))
try: try:
volume_info = str(subprocess.check_output('cmd /C dir ' + final_drive_name, stderr=subprocess.STDOUT)) volume_info = str(subprocess.check_output('cmd /C dir ' + final_drive_name, stderr=subprocess.STDOUT))
@ -59,29 +61,33 @@ if pioutil.is_pio_build():
else: else:
if target_drive in volume_info and not target_file_found: # set upload if not found target file yet if target_drive in volume_info and not target_file_found: # set upload if not found target file yet
target_drive_found = True target_drive_found = True
upload_disk = final_drive_name upload_disk = PureWindowsPath(final_drive_name)
if target_filename in volume_info: if target_filename in volume_info:
if not target_file_found: if not target_file_found:
upload_disk = final_drive_name upload_disk = PureWindowsPath(final_drive_name)
target_file_found = True target_file_found = True
elif current_OS == 'Linux': elif current_OS == 'Linux':
# #
# platformio.ini will accept this for a Linux upload port designation: 'upload_port = /media/media_name/drive' # platformio.ini will accept this for a Linux upload port designation: 'upload_port = /media/media_name/drive'
# #
drives = os.listdir(os.path.join(os.sep, 'media', getpass.getuser())) import getpass
user = getpass.getuser()
mpath = Path('media', user)
drives = [ x for x in mpath.iterdir() if x.is_dir() ]
if target_drive in drives: # If target drive is found, use it. if target_drive in drives: # If target drive is found, use it.
target_drive_found = True target_drive_found = True
upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), target_drive) + os.sep upload_disk = mpath / target_drive
else: else:
for drive in drives: for drive in drives:
try: try:
files = os.listdir(os.path.join(os.sep, 'media', getpass.getuser(), drive)) fpath = mpath / drive
files = [ x for x in fpath.iterdir() if x.is_file() ]
except: except:
continue continue
else: else:
if target_filename in files: if target_filename in files:
upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), drive) + os.sep upload_disk = mpath / drive
target_file_found = True target_file_found = True
break break
# #
@ -97,26 +103,28 @@ if pioutil.is_pio_build():
# #
# platformio.ini will accept this for a OSX upload port designation: 'upload_port = /media/media_name/drive' # platformio.ini will accept this for a OSX upload port designation: 'upload_port = /media/media_name/drive'
# #
drives = os.listdir('/Volumes') # human readable names dpath = Path('/Volumes') # human readable names
drives = [ x for x in dpath.iterdir() ]
if target_drive in drives and not target_file_found: # set upload if not found target file yet if target_drive in drives and not target_file_found: # set upload if not found target file yet
target_drive_found = True target_drive_found = True
upload_disk = '/Volumes/' + target_drive + '/' upload_disk = dpath / target_drive
for drive in drives: for drive in drives:
try: try:
filenames = os.listdir('/Volumes/' + drive + '/') # will get an error if the drive is protected fpath = dpath / drive # will get an error if the drive is protected
files = [ x for x in fpath.iterdir() ]
except: except:
continue continue
else: else:
if target_filename in filenames: if target_filename in files:
if not target_file_found: if not target_file_found:
upload_disk = '/Volumes/' + drive + '/' upload_disk = dpath / drive
target_file_found = True target_file_found = True
# #
# Set upload_port to drive if found # Set upload_port to drive if found
# #
if target_file_found or target_drive_found: if target_file_found or target_drive_found:
env.Replace(UPLOAD_PORT=upload_disk) env.Replace(UPLOAD_PORT=str(upload_disk))
print('\nUpload disk: ', upload_disk, '\n') print('\nUpload disk: ', upload_disk, '\n')
else: else:
print_error('Autodetect Error') print_error('Autodetect Error')

View File

@ -3,30 +3,29 @@
# #
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,shutil,marlin import shutil,marlin
from SCons.Script import DefaultEnvironment from pathlib import Path
from platformio import util
env = DefaultEnvironment() Import("env")
platform = env.PioPlatform() platform = env.PioPlatform()
board = env.BoardConfig() board = env.BoardConfig()
FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoststm32-maple") FRAMEWORK_DIR = Path(platform.get_package_dir("framework-arduinoststm32-maple"))
assert os.path.isdir(FRAMEWORK_DIR) assert FRAMEWORK_DIR.is_dir()
source_root = os.path.join("buildroot", "share", "PlatformIO", "variants") source_root = Path("buildroot/share/PlatformIO/variants")
assert os.path.isdir(source_root) assert source_root.is_dir()
variant = board.get("build.variant") variant = board.get("build.variant")
variant_dir = os.path.join(FRAMEWORK_DIR, "STM32F1", "variants", variant) variant_dir = FRAMEWORK_DIR / "STM32F1/variants" / variant
source_dir = os.path.join(source_root, variant) source_dir = source_root / variant
assert os.path.isdir(source_dir) assert source_dir.is_dir()
if os.path.isdir(variant_dir): if variant_dir.is_dir():
shutil.rmtree(variant_dir) shutil.rmtree(variant_dir)
if not os.path.isdir(variant_dir): if not variant_dir.is_dir():
os.mkdir(variant_dir) variant_dir.mkdir()
marlin.copytree(source_dir, variant_dir) marlin.copytree(source_dir, variant_dir)

View File

@ -4,9 +4,7 @@
# #
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,random,struct,uuid,marlin import struct,uuid
# Relocate firmware from 0x08000000 to 0x08008800
marlin.relocate_firmware("0x08008800")
def calculate_crc(contents, seed): def calculate_crc(contents, seed):
accumulating_xor_value = seed; accumulating_xor_value = seed;
@ -105,13 +103,13 @@ if pioutil.is_pio_build():
# Encrypt ${PROGNAME}.bin and save it as 'update.cbd' # Encrypt ${PROGNAME}.bin and save it as 'update.cbd'
def encrypt(source, target, env): def encrypt(source, target, env):
firmware = open(target[0].path, "rb") from pathlib import Path
update = open(target[0].dir.path + '/update.cbd', "wb") fwpath = Path(target[0].path)
length = os.path.getsize(target[0].path) fwsize = fwpath.stat().st_size
fwfile = fwpath.open("rb")
encrypt_file(firmware, update, length) upfile = Path(target[0].dir.path, 'update.cbd').open("wb")
encrypt_file(fwfile, upfile, fwsize)
firmware.close()
update.close()
import marlin
marlin.relocate_firmware("0x08008800")
marlin.add_post_action(encrypt); marlin.add_post_action(encrypt);

View File

@ -5,45 +5,49 @@
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
Import("env") Import("env")
import os,requests,zipfile,tempfile,shutil import requests,zipfile,tempfile,shutil
from pathlib import Path
url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip" url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip"
deps_path = env.Dictionary("PROJECT_LIBDEPS_DIR") deps_path = Path(env.Dictionary("PROJECT_LIBDEPS_DIR"))
zip_path = os.path.join(deps_path, "mks-assets.zip") zip_path = deps_path / "mks-assets.zip"
assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets") assets_path = Path(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
def download_mks_assets(): def download_mks_assets():
print("Downloading MKS Assets") print("Downloading MKS Assets")
r = requests.get(url, stream=True) r = requests.get(url, stream=True)
# the user may have a very clean workspace, # the user may have a very clean workspace,
# so create the PROJECT_LIBDEPS_DIR directory if not exits # so create the PROJECT_LIBDEPS_DIR directory if not exits
if os.path.exists(deps_path) == False: if not deps_path.exists():
os.mkdir(deps_path) deps_path.mkdir()
with open(zip_path, 'wb') as fd: with zip_path.open('wb') as fd:
for chunk in r.iter_content(chunk_size=128): for chunk in r.iter_content(chunk_size=128):
fd.write(chunk) fd.write(chunk)
def copy_mks_assets(): def copy_mks_assets():
print("Copying MKS Assets") print("Copying MKS Assets")
output_path = tempfile.mkdtemp() output_path = Path(tempfile.mkdtemp())
zip_obj = zipfile.ZipFile(zip_path, 'r') zip_obj = zipfile.ZipFile(zip_path, 'r')
zip_obj.extractall(output_path) zip_obj.extractall(output_path)
zip_obj.close() zip_obj.close()
if os.path.exists(assets_path) == True and os.path.isdir(assets_path) == False: if assets_path.exists() and not assets_path.is_dir():
os.unlink(assets_path) assets_path.unlink()
if os.path.exists(assets_path) == False: if not assets_path.exists():
os.mkdir(assets_path) assets_path.mkdir()
base_path = '' base_path = ''
for filename in os.listdir(output_path): for filename in output_path.iterdir():
base_path = filename base_path = filename
for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_font')): fw_path = (output_path / base_path / 'Firmware')
shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_font', filename), assets_path) font_path = fw_path / 'mks_font'
for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_pic')): for filename in font_path.iterdir():
shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path) shutil.copy(font_path / filename, assets_path)
pic_path = fw_path / 'mks_pic'
for filename in pic_path.iterdir():
shutil.copy(pic_path / filename, assets_path)
shutil.rmtree(output_path, ignore_errors=True) shutil.rmtree(output_path, ignore_errors=True)
if os.path.exists(zip_path) == False: if not zip_path.exists():
download_mks_assets() download_mks_assets()
if os.path.exists(assets_path) == False: if not assets_path.exists():
copy_mks_assets() copy_mks_assets()

View File

@ -7,16 +7,14 @@
# #
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,shutil,marlin import shutil,marlin
from SCons.Script import DefaultEnvironment from pathlib import Path
from platformio import util
env = DefaultEnvironment()
# #
# Get the platform name from the 'platform_packages' option, # Get the platform name from the 'platform_packages' option,
# or look it up by the platform.class.name. # or look it up by the platform.class.name.
# #
env = marlin.env
platform = env.PioPlatform() platform = env.PioPlatform()
from platformio.package.meta import PackageSpec from platformio.package.meta import PackageSpec
@ -37,8 +35,8 @@ if pioutil.is_pio_build():
if platform_name in [ "usb-host-msc", "usb-host-msc-cdc-msc", "usb-host-msc-cdc-msc-2", "usb-host-msc-cdc-msc-3", "tool-stm32duino", "biqu-bx-workaround", "main" ]: if platform_name in [ "usb-host-msc", "usb-host-msc-cdc-msc", "usb-host-msc-cdc-msc-2", "usb-host-msc-cdc-msc-3", "tool-stm32duino", "biqu-bx-workaround", "main" ]:
platform_name = "framework-arduinoststm32" platform_name = "framework-arduinoststm32"
FRAMEWORK_DIR = platform.get_package_dir(platform_name) FRAMEWORK_DIR = Path(platform.get_package_dir(platform_name))
assert os.path.isdir(FRAMEWORK_DIR) assert FRAMEWORK_DIR.is_dir()
board = env.BoardConfig() board = env.BoardConfig()
@ -47,14 +45,14 @@ if pioutil.is_pio_build():
#series = mcu_type[:7].upper() + "xx" #series = mcu_type[:7].upper() + "xx"
# Prepare a new empty folder at the destination # Prepare a new empty folder at the destination
variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant) variant_dir = FRAMEWORK_DIR / "variants" / variant
if os.path.isdir(variant_dir): if variant_dir.is_dir():
shutil.rmtree(variant_dir) shutil.rmtree(variant_dir)
if not os.path.isdir(variant_dir): if not variant_dir.is_dir():
os.mkdir(variant_dir) variant_dir.mkdir()
# Source dir is a local variant sub-folder # Source dir is a local variant sub-folder
source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant) source_dir = Path("buildroot/share/PlatformIO/variants", variant)
assert os.path.isdir(source_dir) assert source_dir.is_dir()
marlin.copytree(source_dir, variant_dir) marlin.copytree(source_dir, variant_dir)

View File

@ -4,37 +4,32 @@
# #
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,marlin
# Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin' # Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin'
def addboot(source, target, env): def addboot(source, target, env):
firmware = open(target[0].path, "rb") from pathlib import Path
lengthfirmware = os.path.getsize(target[0].path)
bootloader_bin = "buildroot/share/PlatformIO/scripts/" + "jgaurora_bootloader.bin"
bootloader = open(bootloader_bin, "rb")
lengthbootloader = os.path.getsize(bootloader_bin)
firmware_with_boothloader_bin = target[0].dir.path + '/firmware_with_bootloader.bin' fw_path = Path(target[0].path)
if os.path.exists(firmware_with_boothloader_bin): fwb_path = fw_path.parent / 'firmware_with_bootloader.bin'
os.remove(firmware_with_boothloader_bin) with fwb_path.open("wb") as fwb_file:
firmwareimage = open(firmware_with_boothloader_bin, "wb") bl_path = Path("buildroot/share/PlatformIO/scripts/jgaurora_bootloader.bin")
position = 0 bl_file = bl_path.open("rb")
while position < lengthbootloader: while True:
byte = bootloader.read(1) b = bl_file.read(1)
firmwareimage.write(byte) if b == b'': break
position += 1 else: fwb_file.write(b)
position = 0
while position < lengthfirmware:
byte = firmware.read(1)
firmwareimage.write(byte)
position += 1
bootloader.close()
firmware.close()
firmwareimage.close()
firmware_without_bootloader_bin = target[0].dir.path + '/firmware_for_sd_upload.bin' with fw_path.open("rb") as fw_file:
if os.path.exists(firmware_without_bootloader_bin): while True:
os.remove(firmware_without_bootloader_bin) b = fw_file.read(1)
os.rename(target[0].path, firmware_without_bootloader_bin) if b == b'': break
#os.rename(target[0].dir.path+'/firmware_with_bootloader.bin', target[0].dir.path+'/firmware.bin') else: fwb_file.write(b)
fws_path = Path(target[0].dir.path, 'firmware_for_sd_upload.bin')
if fws_path.exists():
fws_path.unlink()
fw_path.rename(fws_path)
import marlin
marlin.add_post_action(addboot); marlin.add_post_action(addboot);

View File

@ -8,10 +8,8 @@
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,marlin import os,marlin
Import("env")
from SCons.Script import DefaultEnvironment board = marlin.env.BoardConfig()
board = DefaultEnvironment().BoardConfig()
def encryptByte(byte): def encryptByte(byte):
byte = 0xFF & ((byte << 6) | (byte >> 2)) byte = 0xFF & ((byte << 6) | (byte >> 2))

View File

@ -2,21 +2,18 @@
# marlin.py # marlin.py
# Helper module with some commonly-used functions # Helper module with some commonly-used functions
# #
import os,shutil import shutil
from pathlib import Path
from SCons.Script import DefaultEnvironment from SCons.Script import DefaultEnvironment
env = DefaultEnvironment() env = DefaultEnvironment()
from os.path import join
def copytree(src, dst, symlinks=False, ignore=None): def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src): for item in src.iterdir():
s = join(src, item) if item.is_dir():
d = join(dst, item) shutil.copytree(item, dst / item.name, symlinks, ignore)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else: else:
shutil.copy2(s, d) shutil.copy2(item, dst / item.name)
def replace_define(field, value): def replace_define(field, value):
for define in env['CPPDEFINES']: for define in env['CPPDEFINES']:
@ -34,7 +31,7 @@ def relocate_vtab(address):
# Replace the existing -Wl,-T with the given ldscript path # Replace the existing -Wl,-T with the given ldscript path
def custom_ld_script(ldname): def custom_ld_script(ldname):
apath = os.path.abspath("buildroot/share/PlatformIO/ldscripts/" + ldname) apath = str(Path("buildroot/share/PlatformIO/ldscripts", ldname).resolve())
for i, flag in enumerate(env["LINKFLAGS"]): for i, flag in enumerate(env["LINKFLAGS"]):
if "-Wl,-T" in flag: if "-Wl,-T" in flag:
env["LINKFLAGS"][i] = "-Wl,-T" + apath env["LINKFLAGS"][i] = "-Wl,-T" + apath
@ -52,15 +49,15 @@ def encrypt_mks(source, target, env, new_name):
mf = env["MARLIN_FEATURES"] mf = env["MARLIN_FEATURES"]
if "FIRMWARE_BIN" in mf: new_name = mf["FIRMWARE_BIN"] if "FIRMWARE_BIN" in mf: new_name = mf["FIRMWARE_BIN"]
fwpath = target[0].path fwpath = Path(target[0].path)
fwfile = open(fwpath, "rb") fwfile = fwpath.open("rb")
enfile = open(target[0].dir.path + "/" + new_name, "wb") enfile = Path(target[0].dir.path, new_name).open("wb")
length = os.path.getsize(fwpath) length = fwpath.stat().st_size
position = 0 position = 0
try: try:
while position < length: while position < length:
byte = fwfile.read(1) byte = fwfile.read(1)
if position >= 320 and position < 31040: if 320 <= position < 31040:
byte = chr(ord(byte) ^ key[position & 31]) byte = chr(ord(byte) ^ key[position & 31])
if sys.version_info[0] > 2: if sys.version_info[0] > 2:
byte = bytes(byte, 'latin1') byte = bytes(byte, 'latin1')
@ -69,7 +66,7 @@ def encrypt_mks(source, target, env, new_name):
finally: finally:
fwfile.close() fwfile.close()
enfile.close() enfile.close()
os.remove(fwpath) fwpath.unlink()
def add_post_action(action): def add_post_action(action):
env.AddPostAction(join("$BUILD_DIR", "${PROGNAME}.bin"), action); env.AddPostAction(str(Path("$BUILD_DIR", "${PROGNAME}.bin")), action);

View File

@ -10,12 +10,10 @@
# #
import pioutil import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,sys,marlin import sys,marlin
Import("env")
from SCons.Script import DefaultEnvironment
board = DefaultEnvironment().BoardConfig()
env = marlin.env
board = env.BoardConfig()
board_keys = board.get("build").keys() board_keys = board.get("build").keys()
# #
@ -56,7 +54,7 @@ if pioutil.is_pio_build():
if 'rename' in board_keys: if 'rename' in board_keys:
def rename_target(source, target, env): def rename_target(source, target, env):
firmware = os.path.join(target[0].dir.path, board.get("build.rename")) from pathlib import Path
os.replace(target[0].path, firmware) Path(target[0].path).replace(Path(target[0].dir.path, board.get("build.rename")))
marlin.add_post_action(rename_target) marlin.add_post_action(rename_target)

View File

@ -6,10 +6,12 @@ import pioutil
if pioutil.is_pio_build(): if pioutil.is_pio_build():
import os,re,sys import os,re,sys
from pathlib import Path
Import("env") Import("env")
def get_envs_for_board(board): def get_envs_for_board(board):
with open(os.path.join("Marlin", "src", "pins", "pins.h"), "r") as file: ppath = Path("Marlin/src/pins/pins.h")
with ppath.open() as file:
if sys.platform == 'win32': if sys.platform == 'win32':
envregex = r"(?:env|win):" envregex = r"(?:env|win):"
@ -77,9 +79,10 @@ if pioutil.is_pio_build():
# #
# Check for Config files in two common incorrect places # Check for Config files in two common incorrect places
# #
for p in [ env['PROJECT_DIR'], os.path.join(env['PROJECT_DIR'], "config") ]: epath = Path(env['PROJECT_DIR'])
for f in [ "Configuration.h", "Configuration_adv.h" ]: for p in [ epath, epath / "config" ]:
if os.path.isfile(os.path.join(p, f)): for f in ("Configuration.h", "Configuration_adv.h"):
if (p / f).is_file():
err = "ERROR: Config files found in directory %s. Please move them into the Marlin subfolder." % p err = "ERROR: Config files found in directory %s. Please move them into the Marlin subfolder." % p
raise SystemExit(err) raise SystemExit(err)
@ -87,12 +90,12 @@ if pioutil.is_pio_build():
# Find the name.cpp.o or name.o and remove it # Find the name.cpp.o or name.o and remove it
# #
def rm_ofile(subdir, name): def rm_ofile(subdir, name):
build_dir = os.path.join(env['PROJECT_BUILD_DIR'], build_env); build_dir = Path(env['PROJECT_BUILD_DIR'], build_env);
for outdir in [ build_dir, os.path.join(build_dir, "debug") ]: for outdir in (build_dir, build_dir / "debug"):
for ext in [ ".cpp.o", ".o" ]: for ext in (".cpp.o", ".o"):
fpath = os.path.join(outdir, "src", "src", subdir, name + ext) fpath = outdir / "src/src" / subdir / (name + ext)
if os.path.exists(fpath): if fpath.exists():
os.remove(fpath) fpath.unlink()
# #
# Give warnings on every build # Give warnings on every build
@ -109,13 +112,13 @@ if pioutil.is_pio_build():
# Check for old files indicating an entangled Marlin (mixing old and new code) # Check for old files indicating an entangled Marlin (mixing old and new code)
# #
mixedin = [] mixedin = []
p = os.path.join(env['PROJECT_DIR'], "Marlin", "src", "lcd", "dogm") p = Path(env['PROJECT_DIR'], "Marlin/src/lcd/dogm")
for f in [ "ultralcd_DOGM.cpp", "ultralcd_DOGM.h" ]: for f in [ "ultralcd_DOGM.cpp", "ultralcd_DOGM.h" ]:
if os.path.isfile(os.path.join(p, f)): if (p / f).is_file():
mixedin += [ f ] mixedin += [ f ]
p = os.path.join(env['PROJECT_DIR'], "Marlin", "src", "feature", "bedlevel", "abl") p = Path(env['PROJECT_DIR'], "Marlin/src/feature/bedlevel/abl")
for f in [ "abl.cpp", "abl.h" ]: for f in [ "abl.cpp", "abl.h" ]:
if os.path.isfile(os.path.join(p, f)): if (p / f).is_file():
mixedin += [ f ] mixedin += [ f ]
if mixedin: if mixedin:
err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin) err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin)

View File

@ -1,7 +1,7 @@
# #
# preprocessor.py # preprocessor.py
# #
import subprocess,os,re import subprocess,re
nocache = 1 nocache = 1
verbose = 0 verbose = 0
@ -54,51 +54,41 @@ def run_preprocessor(env, fn=None):
# #
def search_compiler(env): def search_compiler(env):
ENV_BUILD_PATH = os.path.join(env['PROJECT_BUILD_DIR'], env['PIOENV']) from pathlib import Path, PurePath
GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
ENV_BUILD_PATH = Path(env['PROJECT_BUILD_DIR'], env['PIOENV'])
GCC_PATH_CACHE = ENV_BUILD_PATH / ".gcc_path"
try: try:
filepath = env.GetProjectOption('custom_gcc') gccpath = env.GetProjectOption('custom_gcc')
blab("Getting compiler from env") blab("Getting compiler from env")
return filepath return gccpath
except: except:
pass pass
# Warning: The cached .gcc_path will obscure a newly-installed toolkit # Warning: The cached .gcc_path will obscure a newly-installed toolkit
if not nocache and os.path.exists(GCC_PATH_CACHE): if not nocache and GCC_PATH_CACHE.exists():
blab("Getting g++ path from cache") blab("Getting g++ path from cache")
with open(GCC_PATH_CACHE, 'r') as f: return GCC_PATH_CACHE.read_text()
return f.read()
# Find the current platform compiler by searching the $PATH # Use any item in $PATH corresponding to a platformio toolchain bin folder
# which will be in a platformio toolchain bin folder path_separator = ':'
path_regex = re.escape(env['PROJECT_PACKAGES_DIR']) gcc_exe = '*g++'
gcc = "g++"
if env['PLATFORM'] == 'win32': if env['PLATFORM'] == 'win32':
path_separator = ';' path_separator = ';'
path_regex += r'.*\\bin' gcc_exe += ".exe"
gcc += ".exe"
else:
path_separator = ':'
path_regex += r'/.+/bin'
# Search for the compiler # Search for the compiler in PATH
for pathdir in env['ENV']['PATH'].split(path_separator): for ppath in map(Path, env['ENV']['PATH'].split(path_separator)):
if not re.search(path_regex, pathdir, re.IGNORECASE): if ppath.match(env['PROJECT_PACKAGES_DIR'] + "/**/bin"):
continue for gpath in ppath.glob(gcc_exe):
for filepath in os.listdir(pathdir): gccpath = str(gpath.resolve())
if not filepath.endswith(gcc): # Cache the g++ path to no search always
continue if not nocache and ENV_BUILD_PATH.exists():
# Use entire path to not rely on env PATH blab("Caching g++ for current env")
filepath = os.path.sep.join([pathdir, filepath]) GCC_PATH_CACHE.write_text(gccpath)
# Cache the g++ path to no search always return gccpath
if not nocache and os.path.exists(ENV_BUILD_PATH):
blab("Caching g++ for current env")
with open(GCC_PATH_CACHE, 'w+') as f:
f.write(filepath)
return filepath gccpath = env.get('CXX')
blab("Couldn't find a compiler! Fallback to %s" % gccpath)
filepath = env.get('CXX') return gccpath
blab("Couldn't find a compiler! Fallback to %s" % filepath)
return filepath

View File

@ -144,7 +144,7 @@ class DWIN_ICO_File():
# process each file: # process each file:
try: try:
index = int(dirEntry.name[0:3]) index = int(dirEntry.name[0:3])
if (index < 0) or (index > 255): if not (0 <= index <= 255):
print('...Ignoring invalid index on', dirEntry.path) print('...Ignoring invalid index on', dirEntry.path)
continue continue
#dirEntry.path is iconDir/name #dirEntry.path is iconDir/name

View File

@ -22,7 +22,7 @@
# 2020-06-05 SRL style tweaks # 2020-06-05 SRL style tweaks
#----------------------------------- #-----------------------------------
# #
import sys,os import sys
from pathlib import Path from pathlib import Path
from distutils.dir_util import copy_tree # for copy_tree, because shutil.copytree can't handle existing files, dirs from distutils.dir_util import copy_tree # for copy_tree, because shutil.copytree can't handle existing files, dirs
@ -58,10 +58,10 @@ def process_file(subdir: str, filename: str):
# Read file # Read file
#------------------------ #------------------------
lines = [] lines = []
infilepath = os.path.join(input_examples_dir, subdir, filename) infilepath = Path(input_examples_dir, subdir, filename)
try: try:
# UTF-8 because some files contain unicode chars # UTF-8 because some files contain unicode chars
with open(infilepath, 'rt', encoding="utf-8") as infile: with infilepath.open('rt', encoding="utf-8") as infile:
lines = infile.readlines() lines = infile.readlines()
except Exception as e: except Exception as e:
@ -123,25 +123,24 @@ def process_file(subdir: str, filename: str):
#------------------------- #-------------------------
# Output file # Output file
#------------------------- #-------------------------
outdir = os.path.join(output_examples_dir, subdir) outdir = Path(output_examples_dir, subdir)
outfilepath = os.path.join(outdir, filename) outfilepath = outdir / filename
if file_modified: if file_modified:
# Note: no need to create output dirs, as the initial copy_tree # Note: no need to create output dirs, as the initial copy_tree
# will do that. # will do that.
print(' writing ' + str(outfilepath)) print(' writing ' + outfilepath)
try: try:
# Preserve unicode chars; Avoid CR-LF on Windows. # Preserve unicode chars; Avoid CR-LF on Windows.
with open(outfilepath, "w", encoding="utf-8", newline='\n') as outfile: with outfilepath.open("w", encoding="utf-8", newline='\n') as outfile:
outfile.write("\n".join(outlines)) outfile.write("\n".join(outlines) + "\n")
outfile.write("\n")
except Exception as e: except Exception as e:
print('Failed to write file: ' + str(e) ) print('Failed to write file: ' + str(e) )
raise Exception raise Exception
else: else:
print(' no change for ' + str(outfilepath)) print(' no change for ' + outfilepath)
#---------- #----------
def main(): def main():
@ -159,8 +158,8 @@ def main():
output_examples_dir = output_examples_dir.strip() output_examples_dir = output_examples_dir.strip()
output_examples_dir = output_examples_dir.rstrip('\\/') output_examples_dir = output_examples_dir.rstrip('\\/')
for dir in [input_examples_dir, output_examples_dir]: for dir in (input_examples_dir, output_examples_dir):
if not (os.path.exists(dir)): if not Path(dir).exists():
print('Directory not found: ' + dir) print('Directory not found: ' + dir)
sys.exit(1) sys.exit(1)
@ -181,8 +180,7 @@ def main():
#----------------------------- #-----------------------------
# Find and process files # Find and process files
#----------------------------- #-----------------------------
len_input_examples_dir = len(input_examples_dir); len_input_examples_dir = 1 + len(input_examples_dir)
len_input_examples_dir += 1
for filename in files_to_mod: for filename in files_to_mod:
input_path = Path(input_examples_dir) input_path = Path(input_examples_dir)

View File

@ -252,7 +252,7 @@ def resolve_path(path):
while 0 <= path.find('../'): while 0 <= path.find('../'):
end = path.find('../') - 1 end = path.find('../') - 1
start = path.find('/') start = path.find('/')
while 0 <= path.find('/', start) and end > path.find('/', start): while 0 <= path.find('/', start) < end:
start = path.find('/', start) + 1 start = path.find('/', start) + 1
path = path[0:start] + path[end + 4:] path = path[0:start] + path[end + 4:]
@ -674,7 +674,7 @@ def line_print(line_input):
if 0 == highlight[1]: if 0 == highlight[1]:
found_1 = text.find(' ') found_1 = text.find(' ')
found_tab = text.find('\t') found_tab = text.find('\t')
if found_1 < 0 or found_1 > found_tab: if not (0 <= found_1 <= found_tab):
found_1 = found_tab found_1 = found_tab
write_to_screen_queue(text[:found_1 + 1]) write_to_screen_queue(text[:found_1 + 1])
for highlight_2 in highlights: for highlight_2 in highlights:
@ -684,7 +684,7 @@ def line_print(line_input):
if found >= 0: if found >= 0:
found_space = text.find(' ', found_1 + 1) found_space = text.find(' ', found_1 + 1)
found_tab = text.find('\t', found_1 + 1) found_tab = text.find('\t', found_1 + 1)
if found_space < 0 or found_space > found_tab: if not (0 <= found_space <= found_tab):
found_space = found_tab found_space = found_tab
found_right = text.find(']', found + 1) found_right = text.find(']', found + 1)
write_to_screen_queue(text[found_1 + 1:found_space + 1], highlight[2]) write_to_screen_queue(text[found_1 + 1:found_space + 1], highlight[2])
@ -701,7 +701,7 @@ def line_print(line_input):
break break
if did_something == False: if did_something == False:
r_loc = text.find('\r') + 1 r_loc = text.find('\r') + 1
if r_loc > 0 and r_loc < len(text): # need to split this line if 0 < r_loc < len(text): # need to split this line
text = text.split('\r') text = text.split('\r')
for line in text: for line in text:
if line != '': if line != '':