Browse Source

🔨 Simplify scripts with pathlib (#24574)

Scott Lahteine 1 year ago
parent
commit
7f72e78520
No account linked to committer's email address

+ 23
- 15
Marlin/src/HAL/LPC1768/upload_extra_script.py View File

@@ -12,7 +12,7 @@ if pioutil.is_pio_build():
12 12
 	target_filename = "FIRMWARE.CUR"
13 13
 	target_drive = "REARM"
14 14
 
15
-	import os,getpass,platform
15
+	import platform
16 16
 
17 17
 	current_OS = platform.system()
18 18
 	Import("env")
@@ -26,7 +26,8 @@ if pioutil.is_pio_build():
26 26
 
27 27
 	def before_upload(source, target, env):
28 28
 		try:
29
-			#
29
+			from pathlib import Path
30
+  			#
30 31
 			# Find a disk for upload
31 32
 			#
32 33
 			upload_disk = 'Disk not found'
@@ -38,6 +39,7 @@ if pioutil.is_pio_build():
38 39
 				#   Windows - doesn't care about the disk's name, only cares about the drive letter
39 40
 				import subprocess,string
40 41
 				from ctypes import windll
42
+				from pathlib import PureWindowsPath
41 43
 
42 44
 				# getting list of drives
43 45
 				# 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():
49 51
 					bitmask >>= 1
50 52
 
51 53
 				for drive in drives:
52
-					final_drive_name = drive + ':\\'
54
+					final_drive_name = drive + ':'
53 55
 					# print ('disc check: {}'.format(final_drive_name))
54 56
 					try:
55 57
 						volume_info = str(subprocess.check_output('cmd /C dir ' + final_drive_name, stderr=subprocess.STDOUT))
@@ -59,29 +61,33 @@ if pioutil.is_pio_build():
59 61
 					else:
60 62
 						if target_drive in volume_info and not target_file_found:  # set upload if not found target file yet
61 63
 							target_drive_found = True
62
-							upload_disk = final_drive_name
64
+							upload_disk = PureWindowsPath(final_drive_name)
63 65
 						if target_filename in volume_info:
64 66
 							if not target_file_found:
65
-								upload_disk = final_drive_name
67
+								upload_disk = PureWindowsPath(final_drive_name)
66 68
 							target_file_found = True
67 69
 
68 70
 			elif current_OS == 'Linux':
69 71
 				#
70 72
 				# platformio.ini will accept this for a Linux upload port designation: 'upload_port = /media/media_name/drive'
71 73
 				#
72
-				drives = os.listdir(os.path.join(os.sep, 'media', getpass.getuser()))
74
+				import getpass
75
+				user = getpass.getuser()
76
+				mpath = Path('media', user)
77
+				drives = [ x for x in mpath.iterdir() if x.is_dir() ]
73 78
 				if target_drive in drives:  # If target drive is found, use it.
74 79
 					target_drive_found = True
75
-					upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), target_drive) + os.sep
80
+					upload_disk = mpath / target_drive
76 81
 				else:
77 82
 					for drive in drives:
78 83
 						try:
79
-							files = os.listdir(os.path.join(os.sep, 'media', getpass.getuser(), drive))
84
+							fpath = mpath / drive
85
+							files = [ x for x in fpath.iterdir() if x.is_file() ]
80 86
 						except:
81 87
 							continue
82 88
 						else:
83 89
 							if target_filename in files:
84
-								upload_disk = os.path.join(os.sep, 'media', getpass.getuser(), drive) + os.sep
90
+								upload_disk = mpath / drive
85 91
 								target_file_found = True
86 92
 								break
87 93
 				#
@@ -97,26 +103,28 @@ if pioutil.is_pio_build():
97 103
 				#
98 104
 				# platformio.ini will accept this for a OSX upload port designation: 'upload_port = /media/media_name/drive'
99 105
 				#
100
-				drives = os.listdir('/Volumes')  # human readable names
106
+				dpath = Path('/Volumes')  # human readable names
107
+				drives = [ x for x in dpath.iterdir() ]
101 108
 				if target_drive in drives and not target_file_found:  # set upload if not found target file yet
102 109
 					target_drive_found = True
103
-					upload_disk = '/Volumes/' + target_drive + '/'
110
+					upload_disk = dpath / target_drive
104 111
 				for drive in drives:
105 112
 					try:
106
-						filenames = os.listdir('/Volumes/' + drive + '/')   # will get an error if the drive is protected
113
+						fpath = dpath / drive   # will get an error if the drive is protected
114
+						files = [ x for x in fpath.iterdir() ]
107 115
 					except:
108 116
 						continue
109 117
 					else:
110
-						if target_filename in filenames:
118
+						if target_filename in files:
111 119
 							if not target_file_found:
112
-								upload_disk = '/Volumes/' + drive + '/'
120
+								upload_disk = dpath / drive
113 121
 							target_file_found = True
114 122
 
115 123
 			#
116 124
 			# Set upload_port to drive if found
117 125
 			#
118 126
 			if target_file_found or target_drive_found:
119
-				env.Replace(UPLOAD_PORT=upload_disk)
127
+				env.Replace(UPLOAD_PORT=str(upload_disk))
120 128
 				print('\nUpload disk: ', upload_disk, '\n')
121 129
 			else:
122 130
 				print_error('Autodetect Error')

+ 13
- 14
buildroot/share/PlatformIO/scripts/STM32F1_create_variant.py View File

@@ -3,30 +3,29 @@
3 3
 #
4 4
 import pioutil
5 5
 if pioutil.is_pio_build():
6
-	import os,shutil,marlin
7
-	from SCons.Script import DefaultEnvironment
8
-	from platformio import util
6
+	import shutil,marlin
7
+	from pathlib import Path
9 8
 
10
-	env = DefaultEnvironment()
9
+	Import("env")
11 10
 	platform = env.PioPlatform()
12 11
 	board = env.BoardConfig()
13 12
 
14
-	FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoststm32-maple")
15
-	assert os.path.isdir(FRAMEWORK_DIR)
13
+	FRAMEWORK_DIR = Path(platform.get_package_dir("framework-arduinoststm32-maple"))
14
+	assert FRAMEWORK_DIR.is_dir()
16 15
 
17
-	source_root = os.path.join("buildroot", "share", "PlatformIO", "variants")
18
-	assert os.path.isdir(source_root)
16
+	source_root = Path("buildroot/share/PlatformIO/variants")
17
+	assert source_root.is_dir()
19 18
 
20 19
 	variant = board.get("build.variant")
21
-	variant_dir = os.path.join(FRAMEWORK_DIR, "STM32F1", "variants", variant)
20
+	variant_dir = FRAMEWORK_DIR / "STM32F1/variants" / variant
22 21
 
23
-	source_dir = os.path.join(source_root, variant)
24
-	assert os.path.isdir(source_dir)
22
+	source_dir = source_root / variant
23
+	assert source_dir.is_dir()
25 24
 
26
-	if os.path.isdir(variant_dir):
25
+	if variant_dir.is_dir():
27 26
 		shutil.rmtree(variant_dir)
28 27
 
29
-	if not os.path.isdir(variant_dir):
30
-		os.mkdir(variant_dir)
28
+	if not variant_dir.is_dir():
29
+		variant_dir.mkdir()
31 30
 
32 31
 	marlin.copytree(source_dir, variant_dir)

+ 10
- 12
buildroot/share/PlatformIO/scripts/chitu_crypt.py View File

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

+ 23
- 19
buildroot/share/PlatformIO/scripts/download_mks_assets.py View File

@@ -5,45 +5,49 @@
5 5
 import pioutil
6 6
 if pioutil.is_pio_build():
7 7
 	Import("env")
8
-	import os,requests,zipfile,tempfile,shutil
8
+	import requests,zipfile,tempfile,shutil
9
+	from pathlib import Path
9 10
 
10 11
 	url = "https://github.com/makerbase-mks/Mks-Robin-Nano-Marlin2.0-Firmware/archive/0263cdaccf.zip"
11
-	deps_path = env.Dictionary("PROJECT_LIBDEPS_DIR")
12
-	zip_path = os.path.join(deps_path, "mks-assets.zip")
13
-	assets_path = os.path.join(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
12
+	deps_path = Path(env.Dictionary("PROJECT_LIBDEPS_DIR"))
13
+	zip_path = deps_path / "mks-assets.zip"
14
+	assets_path = Path(env.Dictionary("PROJECT_BUILD_DIR"), env.Dictionary("PIOENV"), "assets")
14 15
 
15 16
 	def download_mks_assets():
16 17
 		print("Downloading MKS Assets")
17 18
 		r = requests.get(url, stream=True)
18 19
 		# the user may have a very clean workspace,
19 20
 		# so create the PROJECT_LIBDEPS_DIR directory if not exits
20
-		if os.path.exists(deps_path) == False:
21
-			os.mkdir(deps_path)
22
-		with open(zip_path, 'wb') as fd:
21
+		if not deps_path.exists():
22
+			deps_path.mkdir()
23
+		with zip_path.open('wb') as fd:
23 24
 			for chunk in r.iter_content(chunk_size=128):
24 25
 				fd.write(chunk)
25 26
 
26 27
 	def copy_mks_assets():
27 28
 		print("Copying MKS Assets")
28
-		output_path = tempfile.mkdtemp()
29
+		output_path = Path(tempfile.mkdtemp())
29 30
 		zip_obj = zipfile.ZipFile(zip_path, 'r')
30 31
 		zip_obj.extractall(output_path)
31 32
 		zip_obj.close()
32
-		if os.path.exists(assets_path) == True and os.path.isdir(assets_path) == False:
33
-			os.unlink(assets_path)
34
-		if os.path.exists(assets_path) == False:
35
-			os.mkdir(assets_path)
33
+		if assets_path.exists() and not assets_path.is_dir():
34
+			assets_path.unlink()
35
+		if not assets_path.exists():
36
+			assets_path.mkdir()
36 37
 		base_path = ''
37
-		for filename in os.listdir(output_path):
38
+		for filename in output_path.iterdir():
38 39
 			base_path = filename
39
-		for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_font')):
40
-			shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_font', filename), assets_path)
41
-		for filename in os.listdir(os.path.join(output_path, base_path, 'Firmware', 'mks_pic')):
42
-			shutil.copy(os.path.join(output_path, base_path, 'Firmware', 'mks_pic', filename), assets_path)
40
+		fw_path = (output_path / base_path / 'Firmware')
41
+		font_path = fw_path / 'mks_font'
42
+		for filename in font_path.iterdir():
43
+			shutil.copy(font_path / filename, assets_path)
44
+		pic_path = fw_path / 'mks_pic'
45
+		for filename in pic_path.iterdir():
46
+			shutil.copy(pic_path / filename, assets_path)
43 47
 		shutil.rmtree(output_path, ignore_errors=True)
44 48
 
45
-	if os.path.exists(zip_path) == False:
49
+	if not zip_path.exists():
46 50
 		download_mks_assets()
47 51
 
48
-	if os.path.exists(assets_path) == False:
52
+	if not assets_path.exists():
49 53
 		copy_mks_assets()

+ 11
- 13
buildroot/share/PlatformIO/scripts/generic_create_variant.py View File

@@ -7,16 +7,14 @@
7 7
 #
8 8
 import pioutil
9 9
 if pioutil.is_pio_build():
10
-	import os,shutil,marlin
11
-	from SCons.Script import DefaultEnvironment
12
-	from platformio import util
13
-
14
-	env = DefaultEnvironment()
10
+	import shutil,marlin
11
+	from pathlib import Path
15 12
 
16 13
 	#
17 14
 	# Get the platform name from the 'platform_packages' option,
18 15
 	# or look it up by the platform.class.name.
19 16
 	#
17
+	env = marlin.env
20 18
 	platform = env.PioPlatform()
21 19
 
22 20
 	from platformio.package.meta import PackageSpec
@@ -37,8 +35,8 @@ if pioutil.is_pio_build():
37 35
 	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" ]:
38 36
 		platform_name = "framework-arduinoststm32"
39 37
 
40
-	FRAMEWORK_DIR = platform.get_package_dir(platform_name)
41
-	assert os.path.isdir(FRAMEWORK_DIR)
38
+	FRAMEWORK_DIR = Path(platform.get_package_dir(platform_name))
39
+	assert FRAMEWORK_DIR.is_dir()
42 40
 
43 41
 	board = env.BoardConfig()
44 42
 
@@ -47,14 +45,14 @@ if pioutil.is_pio_build():
47 45
 	#series = mcu_type[:7].upper() + "xx"
48 46
 
49 47
 	# Prepare a new empty folder at the destination
50
-	variant_dir = os.path.join(FRAMEWORK_DIR, "variants", variant)
51
-	if os.path.isdir(variant_dir):
48
+	variant_dir = FRAMEWORK_DIR / "variants" / variant
49
+	if variant_dir.is_dir():
52 50
 		shutil.rmtree(variant_dir)
53
-	if not os.path.isdir(variant_dir):
54
-		os.mkdir(variant_dir)
51
+	if not variant_dir.is_dir():
52
+		variant_dir.mkdir()
55 53
 
56 54
 	# Source dir is a local variant sub-folder
57
-	source_dir = os.path.join("buildroot/share/PlatformIO/variants", variant)
58
-	assert os.path.isdir(source_dir)
55
+	source_dir = Path("buildroot/share/PlatformIO/variants", variant)
56
+	assert source_dir.is_dir()
59 57
 
60 58
 	marlin.copytree(source_dir, variant_dir)

+ 23
- 28
buildroot/share/PlatformIO/scripts/jgaurora_a5s_a1_with_bootloader.py View File

@@ -4,37 +4,32 @@
4 4
 #
5 5
 import pioutil
6 6
 if pioutil.is_pio_build():
7
-	import os,marlin
7
+
8 8
 	# Append ${PROGNAME}.bin firmware after bootloader and save it as 'jgaurora_firmware.bin'
9 9
 	def addboot(source, target, env):
10
-		firmware = open(target[0].path, "rb")
11
-		lengthfirmware = os.path.getsize(target[0].path)
12
-		bootloader_bin = "buildroot/share/PlatformIO/scripts/" + "jgaurora_bootloader.bin"
13
-		bootloader = open(bootloader_bin, "rb")
14
-		lengthbootloader = os.path.getsize(bootloader_bin)
10
+		from pathlib import Path
11
+
12
+		fw_path = Path(target[0].path)
13
+		fwb_path = fw_path.parent / 'firmware_with_bootloader.bin'
14
+		with fwb_path.open("wb") as fwb_file:
15
+			bl_path = Path("buildroot/share/PlatformIO/scripts/jgaurora_bootloader.bin")
16
+			bl_file = bl_path.open("rb")
17
+			while True:
18
+				b = bl_file.read(1)
19
+				if b == b'': break
20
+				else: fwb_file.write(b)
21
+
22
+			with fw_path.open("rb") as fw_file:
23
+				while True:
24
+					b = fw_file.read(1)
25
+					if b == b'': break
26
+					else: fwb_file.write(b)
15 27
 
16
-		firmware_with_boothloader_bin = target[0].dir.path + '/firmware_with_bootloader.bin'
17
-		if os.path.exists(firmware_with_boothloader_bin):
18
-			os.remove(firmware_with_boothloader_bin)
19
-		firmwareimage = open(firmware_with_boothloader_bin, "wb")
20
-		position = 0
21
-		while position < lengthbootloader:
22
-			byte = bootloader.read(1)
23
-			firmwareimage.write(byte)
24
-			position += 1
25
-		position = 0
26
-		while position < lengthfirmware:
27
-			byte = firmware.read(1)
28
-			firmwareimage.write(byte)
29
-			position += 1
30
-		bootloader.close()
31
-		firmware.close()
32
-		firmwareimage.close()
28
+		fws_path = Path(target[0].dir.path, 'firmware_for_sd_upload.bin')
29
+		if fws_path.exists():
30
+			fws_path.unlink()
33 31
 
34
-		firmware_without_bootloader_bin = target[0].dir.path + '/firmware_for_sd_upload.bin'
35
-		if os.path.exists(firmware_without_bootloader_bin):
36
-			os.remove(firmware_without_bootloader_bin)
37
-		os.rename(target[0].path, firmware_without_bootloader_bin)
38
-		#os.rename(target[0].dir.path+'/firmware_with_bootloader.bin', target[0].dir.path+'/firmware.bin')
32
+		fw_path.rename(fws_path)
39 33
 
34
+	import marlin
40 35
 	marlin.add_post_action(addboot);

+ 1
- 3
buildroot/share/PlatformIO/scripts/lerdge.py View File

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

+ 14
- 17
buildroot/share/PlatformIO/scripts/marlin.py View File

@@ -2,21 +2,18 @@
2 2
 # marlin.py
3 3
 # Helper module with some commonly-used functions
4 4
 #
5
-import os,shutil
5
+import shutil
6
+from pathlib import Path
6 7
 
7 8
 from SCons.Script import DefaultEnvironment
8 9
 env = DefaultEnvironment()
9 10
 
10
-from os.path import join
11
-
12 11
 def copytree(src, dst, symlinks=False, ignore=None):
13
-	for item in os.listdir(src):
14
-		s = join(src, item)
15
-		d = join(dst, item)
16
-		if os.path.isdir(s):
17
-			shutil.copytree(s, d, symlinks, ignore)
12
+	for item in src.iterdir():
13
+		if item.is_dir():
14
+			shutil.copytree(item, dst / item.name, symlinks, ignore)
18 15
 		else:
19
-			shutil.copy2(s, d)
16
+			shutil.copy2(item, dst / item.name)
20 17
 
21 18
 def replace_define(field, value):
22 19
 	for define in env['CPPDEFINES']:
@@ -34,7 +31,7 @@ def relocate_vtab(address):
34 31
 
35 32
 # Replace the existing -Wl,-T with the given ldscript path
36 33
 def custom_ld_script(ldname):
37
-	apath = os.path.abspath("buildroot/share/PlatformIO/ldscripts/" + ldname)
34
+	apath = str(Path("buildroot/share/PlatformIO/ldscripts", ldname).resolve())
38 35
 	for i, flag in enumerate(env["LINKFLAGS"]):
39 36
 		if "-Wl,-T" in flag:
40 37
 			env["LINKFLAGS"][i] = "-Wl,-T" + apath
@@ -52,15 +49,15 @@ def encrypt_mks(source, target, env, new_name):
52 49
 	mf = env["MARLIN_FEATURES"]
53 50
 	if "FIRMWARE_BIN" in mf: new_name = mf["FIRMWARE_BIN"]
54 51
 
55
-	fwpath = target[0].path
56
-	fwfile = open(fwpath, "rb")
57
-	enfile = open(target[0].dir.path + "/" + new_name, "wb")
58
-	length = os.path.getsize(fwpath)
52
+	fwpath = Path(target[0].path)
53
+	fwfile = fwpath.open("rb")
54
+	enfile = Path(target[0].dir.path, new_name).open("wb")
55
+	length = fwpath.stat().st_size
59 56
 	position = 0
60 57
 	try:
61 58
 		while position < length:
62 59
 			byte = fwfile.read(1)
63
-			if position >= 320 and position < 31040:
60
+			if 320 <= position < 31040:
64 61
 				byte = chr(ord(byte) ^ key[position & 31])
65 62
 				if sys.version_info[0] > 2:
66 63
 					byte = bytes(byte, 'latin1')
@@ -69,7 +66,7 @@ def encrypt_mks(source, target, env, new_name):
69 66
 	finally:
70 67
 		fwfile.close()
71 68
 		enfile.close()
72
-		os.remove(fwpath)
69
+		fwpath.unlink()
73 70
 
74 71
 def add_post_action(action):
75
-	env.AddPostAction(join("$BUILD_DIR", "${PROGNAME}.bin"), action);
72
+	env.AddPostAction(str(Path("$BUILD_DIR", "${PROGNAME}.bin")), action);

+ 5
- 7
buildroot/share/PlatformIO/scripts/offset_and_rename.py View File

@@ -10,12 +10,10 @@
10 10
 #
11 11
 import pioutil
12 12
 if pioutil.is_pio_build():
13
-	import os,sys,marlin
14
-	Import("env")
15
-
16
-	from SCons.Script import DefaultEnvironment
17
-	board = DefaultEnvironment().BoardConfig()
13
+	import sys,marlin
18 14
 
15
+	env = marlin.env
16
+	board = env.BoardConfig()
19 17
 	board_keys = board.get("build").keys()
20 18
 
21 19
 	#
@@ -56,7 +54,7 @@ if pioutil.is_pio_build():
56 54
 	if 'rename' in board_keys:
57 55
 
58 56
 		def rename_target(source, target, env):
59
-			firmware = os.path.join(target[0].dir.path, board.get("build.rename"))
60
-			os.replace(target[0].path, firmware)
57
+			from pathlib import Path
58
+			Path(target[0].path).replace(Path(target[0].dir.path, board.get("build.rename")))
61 59
 
62 60
 		marlin.add_post_action(rename_target)

+ 17
- 14
buildroot/share/PlatformIO/scripts/preflight-checks.py View File

@@ -6,10 +6,12 @@ import pioutil
6 6
 if pioutil.is_pio_build():
7 7
 
8 8
 	import os,re,sys
9
+	from pathlib import Path
9 10
 	Import("env")
10 11
 
11 12
 	def get_envs_for_board(board):
12
-		with open(os.path.join("Marlin", "src", "pins", "pins.h"), "r") as file:
13
+		ppath = Path("Marlin/src/pins/pins.h")
14
+		with ppath.open() as file:
13 15
 
14 16
 			if sys.platform == 'win32':
15 17
 				envregex = r"(?:env|win):"
@@ -77,9 +79,10 @@ if pioutil.is_pio_build():
77 79
 		#
78 80
 		# Check for Config files in two common incorrect places
79 81
 		#
80
-		for p in [ env['PROJECT_DIR'], os.path.join(env['PROJECT_DIR'], "config") ]:
81
-			for f in [ "Configuration.h", "Configuration_adv.h" ]:
82
-				if os.path.isfile(os.path.join(p, f)):
82
+		epath = Path(env['PROJECT_DIR'])
83
+		for p in [ epath, epath / "config" ]:
84
+			for f in ("Configuration.h", "Configuration_adv.h"):
85
+				if (p / f).is_file():
83 86
 					err = "ERROR: Config files found in directory %s. Please move them into the Marlin subfolder." % p
84 87
 					raise SystemExit(err)
85 88
 
@@ -87,12 +90,12 @@ if pioutil.is_pio_build():
87 90
 		# Find the name.cpp.o or name.o and remove it
88 91
 		#
89 92
 		def rm_ofile(subdir, name):
90
-			build_dir = os.path.join(env['PROJECT_BUILD_DIR'], build_env);
91
-			for outdir in [ build_dir, os.path.join(build_dir, "debug") ]:
92
-				for ext in [ ".cpp.o", ".o" ]:
93
-					fpath = os.path.join(outdir, "src", "src", subdir, name + ext)
94
-					if os.path.exists(fpath):
95
-						os.remove(fpath)
93
+			build_dir = Path(env['PROJECT_BUILD_DIR'], build_env);
94
+			for outdir in (build_dir, build_dir / "debug"):
95
+				for ext in (".cpp.o", ".o"):
96
+					fpath = outdir / "src/src" / subdir / (name + ext)
97
+					if fpath.exists():
98
+						fpath.unlink()
96 99
 
97 100
 		#
98 101
 		# Give warnings on every build
@@ -109,13 +112,13 @@ if pioutil.is_pio_build():
109 112
 		# Check for old files indicating an entangled Marlin (mixing old and new code)
110 113
 		#
111 114
 		mixedin = []
112
-		p = os.path.join(env['PROJECT_DIR'], "Marlin", "src", "lcd", "dogm")
115
+		p = Path(env['PROJECT_DIR'], "Marlin/src/lcd/dogm")
113 116
 		for f in [ "ultralcd_DOGM.cpp", "ultralcd_DOGM.h" ]:
114
-			if os.path.isfile(os.path.join(p, f)):
117
+			if (p / f).is_file():
115 118
 				mixedin += [ f ]
116
-		p = os.path.join(env['PROJECT_DIR'], "Marlin", "src", "feature", "bedlevel", "abl")
119
+		p = Path(env['PROJECT_DIR'], "Marlin/src/feature/bedlevel/abl")
117 120
 		for f in [ "abl.cpp", "abl.h" ]:
118
-			if os.path.isfile(os.path.join(p, f)):
121
+			if (p / f).is_file():
119 122
 				mixedin += [ f ]
120 123
 		if mixedin:
121 124
 			err = "ERROR: Old files fell into your Marlin folder. Remove %s and try again" % ", ".join(mixedin)

+ 28
- 38
buildroot/share/PlatformIO/scripts/preprocessor.py View File

@@ -1,7 +1,7 @@
1 1
 #
2 2
 # preprocessor.py
3 3
 #
4
-import subprocess,os,re
4
+import subprocess,re
5 5
 
6 6
 nocache = 1
7 7
 verbose = 0
@@ -54,51 +54,41 @@ def run_preprocessor(env, fn=None):
54 54
 #
55 55
 def search_compiler(env):
56 56
 
57
-	ENV_BUILD_PATH = os.path.join(env['PROJECT_BUILD_DIR'], env['PIOENV'])
58
-	GCC_PATH_CACHE = os.path.join(ENV_BUILD_PATH, ".gcc_path")
57
+	from pathlib import Path, PurePath
58
+
59
+	ENV_BUILD_PATH = Path(env['PROJECT_BUILD_DIR'], env['PIOENV'])
60
+	GCC_PATH_CACHE = ENV_BUILD_PATH / ".gcc_path"
59 61
 
60 62
 	try:
61
-		filepath = env.GetProjectOption('custom_gcc')
63
+		gccpath = env.GetProjectOption('custom_gcc')
62 64
 		blab("Getting compiler from env")
63
-		return filepath
65
+		return gccpath
64 66
 	except:
65 67
 		pass
66 68
 
67 69
 	# Warning: The cached .gcc_path will obscure a newly-installed toolkit
68
-	if not nocache and os.path.exists(GCC_PATH_CACHE):
70
+	if not nocache and GCC_PATH_CACHE.exists():
69 71
 		blab("Getting g++ path from cache")
70
-		with open(GCC_PATH_CACHE, 'r') as f:
71
-			return f.read()
72
+		return GCC_PATH_CACHE.read_text()
72 73
 
73
-	# Find the current platform compiler by searching the $PATH
74
-	# which will be in a platformio toolchain bin folder
75
-	path_regex = re.escape(env['PROJECT_PACKAGES_DIR'])
76
-	gcc = "g++"
74
+	# Use any item in $PATH corresponding to a platformio toolchain bin folder
75
+	path_separator = ':'
76
+	gcc_exe = '*g++'
77 77
 	if env['PLATFORM'] == 'win32':
78 78
 		path_separator = ';'
79
-		path_regex += r'.*\\bin'
80
-		gcc += ".exe"
81
-	else:
82
-		path_separator = ':'
83
-		path_regex += r'/.+/bin'
84
-
85
-	# Search for the compiler
86
-	for pathdir in env['ENV']['PATH'].split(path_separator):
87
-		if not re.search(path_regex, pathdir, re.IGNORECASE):
88
-			continue
89
-		for filepath in os.listdir(pathdir):
90
-			if not filepath.endswith(gcc):
91
-				continue
92
-			# Use entire path to not rely on env PATH
93
-			filepath = os.path.sep.join([pathdir, filepath])
94
-			# Cache the g++ path to no search always
95
-			if not nocache and os.path.exists(ENV_BUILD_PATH):
96
-				blab("Caching g++ for current env")
97
-				with open(GCC_PATH_CACHE, 'w+') as f:
98
-					f.write(filepath)
99
-
100
-			return filepath
101
-
102
-	filepath = env.get('CXX')
103
-	blab("Couldn't find a compiler! Fallback to %s" % filepath)
104
-	return filepath
79
+		gcc_exe += ".exe"
80
+
81
+	# Search for the compiler in PATH
82
+	for ppath in map(Path, env['ENV']['PATH'].split(path_separator)):
83
+		if ppath.match(env['PROJECT_PACKAGES_DIR'] + "/**/bin"):
84
+			for gpath in ppath.glob(gcc_exe):
85
+				gccpath = str(gpath.resolve())
86
+				# Cache the g++ path to no search always
87
+				if not nocache and ENV_BUILD_PATH.exists():
88
+					blab("Caching g++ for current env")
89
+					GCC_PATH_CACHE.write_text(gccpath)
90
+				return gccpath
91
+
92
+	gccpath = env.get('CXX')
93
+	blab("Couldn't find a compiler! Fallback to %s" % gccpath)
94
+	return gccpath

+ 1
- 1
buildroot/share/dwin/bin/DWIN_ICO.py View File

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

+ 12
- 14
buildroot/share/scripts/config-labels.py View File

@@ -22,7 +22,7 @@
22 22
 # 2020-06-05 SRL style tweaks
23 23
 #-----------------------------------
24 24
 #
25
-import sys,os
25
+import sys
26 26
 from pathlib import Path
27 27
 from distutils.dir_util import copy_tree  # for copy_tree, because shutil.copytree can't handle existing files, dirs
28 28
 
@@ -58,10 +58,10 @@ def process_file(subdir: str, filename: str):
58 58
 	# Read file
59 59
 	#------------------------
60 60
 	lines = []
61
-	infilepath = os.path.join(input_examples_dir, subdir, filename)
61
+	infilepath = Path(input_examples_dir, subdir, filename)
62 62
 	try:
63 63
 		# UTF-8 because some files contain unicode chars
64
-		with open(infilepath, 'rt', encoding="utf-8") as infile:
64
+		with infilepath.open('rt', encoding="utf-8") as infile:
65 65
 			lines = infile.readlines()
66 66
 
67 67
 	except Exception as e:
@@ -123,25 +123,24 @@ def process_file(subdir: str, filename: str):
123 123
 	#-------------------------
124 124
 	#     Output file
125 125
 	#-------------------------
126
-	outdir      = os.path.join(output_examples_dir, subdir)
127
-	outfilepath = os.path.join(outdir, filename)
126
+	outdir      = Path(output_examples_dir, subdir)
127
+	outfilepath = outdir / filename
128 128
 
129 129
 	if file_modified:
130 130
 		# Note: no need to create output dirs, as the initial copy_tree
131 131
 		# will do that.
132 132
 
133
-		print('  writing ' + str(outfilepath))
133
+		print('  writing ' + outfilepath)
134 134
 		try:
135 135
 			# Preserve unicode chars; Avoid CR-LF on Windows.
136
-			with open(outfilepath, "w", encoding="utf-8", newline='\n') as outfile:
137
-				outfile.write("\n".join(outlines))
138
-				outfile.write("\n")
136
+			with outfilepath.open("w", encoding="utf-8", newline='\n') as outfile:
137
+				outfile.write("\n".join(outlines) + "\n")
139 138
 
140 139
 		except Exception as e:
141 140
 			print('Failed to write file: ' + str(e) )
142 141
 			raise Exception
143 142
 	else:
144
-		print('  no change for ' + str(outfilepath))
143
+		print('  no change for ' + outfilepath)
145 144
 
146 145
 #----------
147 146
 def main():
@@ -159,8 +158,8 @@ def main():
159 158
 	output_examples_dir = output_examples_dir.strip()
160 159
 	output_examples_dir = output_examples_dir.rstrip('\\/')
161 160
 
162
-	for dir in [input_examples_dir, output_examples_dir]:
163
-		if not (os.path.exists(dir)):
161
+	for dir in (input_examples_dir, output_examples_dir):
162
+		if not Path(dir).exists():
164 163
 			print('Directory not found: ' + dir)
165 164
 			sys.exit(1)
166 165
 
@@ -181,8 +180,7 @@ def main():
181 180
 	#-----------------------------
182 181
 	# Find and process files
183 182
 	#-----------------------------
184
-	len_input_examples_dir = len(input_examples_dir);
185
-	len_input_examples_dir += 1
183
+	len_input_examples_dir = 1 + len(input_examples_dir)
186 184
 
187 185
 	for filename in files_to_mod:
188 186
 		input_path = Path(input_examples_dir)

+ 4
- 4
buildroot/share/vscode/auto_build.py View File

@@ -252,7 +252,7 @@ def resolve_path(path):
252 252
     while 0 <= path.find('../'):
253 253
       end = path.find('../') - 1
254 254
       start = path.find('/')
255
-      while 0 <= path.find('/', start) and end > path.find('/', start):
255
+      while 0 <= path.find('/', start) < end:
256 256
         start = path.find('/', start) + 1
257 257
       path = path[0:start] + path[end + 4:]
258 258
 
@@ -674,7 +674,7 @@ def line_print(line_input):
674 674
         if 0 == highlight[1]:
675 675
           found_1 = text.find(' ')
676 676
           found_tab = text.find('\t')
677
-          if found_1 < 0 or found_1 > found_tab:
677
+          if not (0 <= found_1 <= found_tab):
678 678
             found_1 = found_tab
679 679
           write_to_screen_queue(text[:found_1 + 1])
680 680
           for highlight_2 in highlights:
@@ -684,7 +684,7 @@ def line_print(line_input):
684 684
             if found >= 0:
685 685
               found_space = text.find(' ', found_1 + 1)
686 686
               found_tab = text.find('\t', found_1 + 1)
687
-              if found_space < 0 or found_space > found_tab:
687
+              if not (0 <= found_space <= found_tab):
688 688
                 found_space = found_tab
689 689
               found_right = text.find(']', found + 1)
690 690
               write_to_screen_queue(text[found_1 + 1:found_space + 1], highlight[2])
@@ -701,7 +701,7 @@ def line_print(line_input):
701 701
         break
702 702
     if did_something == False:
703 703
       r_loc = text.find('\r') + 1
704
-      if r_loc > 0 and r_loc < len(text):  # need to split this line
704
+      if 0 < r_loc < len(text):  # need to split this line
705 705
         text = text.split('\r')
706 706
         for line in text:
707 707
           if line != '':

Loading…
Cancel
Save