-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathcreateProjectStructure.py
More file actions
executable file
·1035 lines (837 loc) · 32.7 KB
/
createProjectStructure.py
File metadata and controls
executable file
·1035 lines (837 loc) · 32.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import datetime as dt
import json
import re
import shutil
import shlex
import subprocess
import sys
import os
import urllib.request
from pathlib import Path
scriptVersion = "v2.1 (2026-02-28)"
defaultAwsServer = "admin@aandewiel.nl"
defaultAwsTarget = "/home/admin/flasherWebsite_v3"
defaultAwsSshKey = "~/.ssh/LightsailDefaultKey-eu-central-1.pem"
defaultProjectImageUrl = "https://flasher.aandewiel.nl/projects/ESP32project.png"
versionPattern = re.compile(r"v\d+\.\d+\.\d+")
envSectionPattern = re.compile(r"^\s*\[\s*env:([^\]]+)\s*\]\s*$")
semverPattern = re.compile(r"(\d+)\.(\d+)\.(\d+)")
versionWithPrefixPattern = re.compile(r"[vV](\d+\.\d+\.\d+)")
workspaceDirPattern = re.compile(r"^\s*workspace_dir\s*=\s*(.+?)\s*$", re.IGNORECASE)
fsStartPattern = re.compile(r"_FS_start\s*=\s*(0x[0-9a-fA-F]+|\d+)")
def parsePlatformioSections(platformioIni: Path) -> dict[str, dict[str, str]]:
sections: dict[str, dict[str, str]] = {}
currentSection = None
for rawLine in platformioIni.read_text(encoding="utf-8", errors="ignore").splitlines():
line = rawLine.strip()
if not line or line.startswith(";") or line.startswith("#"):
continue
sectionMatch = re.match(r"^\[(.+)\]$", line)
if sectionMatch:
currentSection = sectionMatch.group(1).strip().lower()
if currentSection not in sections:
sections[currentSection] = {}
continue
if currentSection is None or "=" not in rawLine:
continue
key, value = rawLine.split("=", 1)
normalizedKey = key.strip().lower()
normalizedValue = re.split(r"\s[;#]", value, maxsplit=1)[0].strip()
sections[currentSection][normalizedKey] = normalizedValue
return sections
def getEnvConfigValue(
sections: dict[str, dict[str, str]], envName: str, key: str
) -> str | None:
normalizedKey = key.strip().lower()
envSection = f"env:{envName}".lower()
if envSection in sections and normalizedKey in sections[envSection]:
return sections[envSection][normalizedKey]
if "env" in sections and normalizedKey in sections["env"]:
return sections["env"][normalizedKey]
return None
def sanitizePathSegment(value: str) -> str:
sanitized = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip())
sanitized = sanitized.strip("._-")
if not sanitized:
return "unknown"
return sanitized
def resolveEnvBoardName(sections: dict[str, dict[str, str]], envName: str) -> str:
configuredBoard = getEnvConfigValue(sections, envName, "board")
if configuredBoard:
return sanitizePathSegment(configuredBoard)
return sanitizePathSegment(envName)
def resolveEnvPlatformName(
sections: dict[str, dict[str, str]], envName: str
) -> str | None:
configuredPlatform = getEnvConfigValue(sections, envName, "platform")
if configuredPlatform:
return configuredPlatform.strip().lower()
return None
def detectSocFamily(boardName: str, platformName: str | None) -> str:
normalizedBoard = re.sub(r"[^a-z0-9]", "", (boardName or "").lower())
normalizedPlatform = re.sub(r"[^a-z0-9]", "", (platformName or "").lower())
esp8266BoardAliases = {
"d1mini",
"d1mini32",
"d1minipro",
"nodemcu",
"nodemcuv2",
"esp01",
"esp01s",
"esp12e",
"esp12f",
"esp07",
"esp07s",
"esp8285",
}
if (
"esp8266" in normalizedBoard
or "esp8266" in normalizedPlatform
or "8266" in normalizedBoard
or "8266" in normalizedPlatform
or normalizedBoard in esp8266BoardAliases
):
return "esp8266"
return "esp32"
def resolveEnvPartitionsSource(
projectRoot: Path,
sections: dict[str, dict[str, str]],
envName: str,
socFamily: str,
) -> Path | None:
configuredValue = None
envSection = f"env:{envName}".lower()
if socFamily == "esp8266":
envValues = sections.get(envSection, {})
configuredValue = envValues.get("board_build.partitions")
else:
configuredValue = getEnvConfigValue(sections, envName, "board_build.partitions")
candidates: list[Path] = []
if configuredValue:
cleaned = configuredValue.strip().strip('"').strip("'")
cleaned = cleaned.replace("${PROJECT_DIR}", str(projectRoot))
cleaned = cleaned.replace("$PROJECT_DIR", str(projectRoot))
resolved = Path(cleaned).expanduser()
if not resolved.is_absolute():
resolved = (projectRoot / resolved).resolve()
else:
resolved = resolved.resolve()
candidates.append(resolved)
if socFamily == "esp32":
defaultCandidate = (projectRoot / "partitions.csv").resolve()
candidates.append(defaultCandidate)
for candidate in candidates:
if candidate.exists() and candidate.is_file():
return candidate
return None
def resolveEnvLdscriptSource(
projectRoot: Path,
sections: dict[str, dict[str, str]],
envName: str,
socFamily: str,
) -> Path | None:
if socFamily != "esp8266":
return None
configuredValue = getEnvConfigValue(sections, envName, "board_build.ldscript")
if not configuredValue:
return None
cleaned = configuredValue.strip().strip('"').strip("'")
cleaned = cleaned.replace("${PROJECT_DIR}", str(projectRoot))
cleaned = cleaned.replace("$PROJECT_DIR", str(projectRoot))
resolved = Path(cleaned).expanduser()
if not resolved.is_absolute():
resolved = (projectRoot / resolved).resolve()
else:
resolved = resolved.resolve()
if resolved.exists() and resolved.is_file():
return resolved
return None
def resolveGeneratedEsp8266Ldscript(buildDir: Path) -> Path | None:
ldDir = buildDir / "ld"
if not ldDir.exists() or not ldDir.is_dir():
return None
preferredNames = [
"local.eagle.app.v6.common.ld",
"eagle.app.v6.common.ld",
]
for name in preferredNames:
candidate = ldDir / name
if candidate.exists() and candidate.is_file():
return candidate
for child in sorted(ldDir.iterdir()):
if child.is_file() and child.suffix == ".ld":
return child
return None
def parsePartitionsCsv(partitionsCsvPath: Path) -> dict[str, dict[str, str]]:
partitions: dict[str, dict[str, str]] = {}
for rawLine in partitionsCsvPath.read_text(encoding="utf-8", errors="ignore").splitlines():
line = rawLine.strip()
if not line or line.startswith("#"):
continue
parts = [part.strip() for part in rawLine.split(",")]
if len(parts) < 4:
continue
name = parts[0]
if not name:
continue
partitions[name] = {
"name": name,
"type": parts[1] if len(parts) > 1 else "",
"subtype": parts[2] if len(parts) > 2 else "",
"offset": parts[3] if len(parts) > 3 else "",
"size": parts[4] if len(parts) > 4 else "",
}
return partitions
def detectFirmwareOffset(partitions: dict[str, dict[str, str]], socFamily: str) -> str:
if socFamily == "esp8266":
firmwareEntry = partitions.get("firmware") if isinstance(partitions, dict) else None
if firmwareEntry and firmwareEntry.get("offset"):
return firmwareEntry["offset"]
return "0x00000"
if "factory" in partitions and partitions["factory"].get("offset"):
return partitions["factory"]["offset"]
if "app0" in partitions and partitions["app0"].get("offset"):
return partitions["app0"]["offset"]
if "ota_0" in partitions and partitions["ota_0"].get("offset"):
return partitions["ota_0"]["offset"]
if "firmware" in partitions and partitions["firmware"].get("offset"):
return partitions["firmware"]["offset"]
for part in partitions.values():
partType = str(part.get("type") or "").strip().lower()
partSubtype = str(part.get("subtype") or "").strip().lower()
if partType in {"app", "0", "0x00"} and part.get("offset"):
return part["offset"]
if partSubtype in {"factory", "app0", "ota_0", "ota0"} and part.get("offset"):
return part["offset"]
if socFamily == "esp8266":
return "0x00000"
return "0x10000"
def detectFilesystemOffset(partitions: dict[str, dict[str, str]]) -> str | None:
directNames = ["spiffs", "littlefs", "fatfs"]
for name in directNames:
if name in partitions and partitions[name].get("offset"):
return partitions[name]["offset"]
for part in partitions.values():
subtype = (part.get("subtype") or "").lower()
if subtype in {"spiffs", "littlefs", "fatfs"} and part.get("offset"):
return part["offset"]
return None
def detectEsp8266FilesystemOffsetFromLdscript(ldscriptPath: Path) -> str | None:
if not ldscriptPath.exists() or not ldscriptPath.is_file():
return None
content = ldscriptPath.read_text(encoding="utf-8", errors="ignore")
match = fsStartPattern.search(content)
if not match:
return None
rawValue = match.group(1)
try:
numericValue = int(rawValue, 0)
except ValueError:
return None
if numericValue >= 0x40200000:
numericValue = numericValue - 0x40200000
if numericValue < 0:
return None
return f"0x{numericValue:05X}"
def isEsp32S3Board(boardName: str) -> bool:
normalized = re.sub(r"[^a-z0-9]", "", boardName.lower())
return "esp32s3" in normalized
def generateFlashJson(
targetVersionDir: Path,
boardName: str,
version: str,
socFamily: str,
ldscriptSource: Path | None,
logLines: list[str],
) -> None:
partitionsCsvPath = targetVersionDir / "partitions.csv"
partitions: dict[str, dict[str, str]] = {}
if partitionsCsvPath.exists():
try:
partitions = parsePartitionsCsv(partitionsCsvPath)
except Exception as exc:
logLines.append(f"WARN: partitions.csv parse failed: {exc}")
flashFiles: list[dict[str, str]] = []
if socFamily == "esp32":
bootloaderOffset = "0x0000" if isEsp32S3Board(boardName) else "0x1000"
bootloaderPath = targetVersionDir / "bootloader.bin"
if bootloaderPath.exists():
flashFiles.append({"offset": bootloaderOffset, "file": "bootloader.bin"})
partitionsBinPath = targetVersionDir / "partitions.bin"
if partitionsBinPath.exists():
flashFiles.append({"offset": "0x8000", "file": "partitions.bin"})
bootAppPath = targetVersionDir / "boot_app0.bin"
if bootAppPath.exists():
flashFiles.append({"offset": "0xe000", "file": "boot_app0.bin"})
firmwarePath = targetVersionDir / "firmware.bin"
if firmwarePath.exists():
firmwareOffset = detectFirmwareOffset(partitions, socFamily)
flashFiles.append({"offset": firmwareOffset, "file": "firmware.bin"})
filesystemFile = None
if (targetVersionDir / "LittleFS.bin").exists():
filesystemFile = "LittleFS.bin"
elif (targetVersionDir / "spiffs.bin").exists():
filesystemFile = "spiffs.bin"
if filesystemFile:
filesystemOffset = detectFilesystemOffset(partitions)
if not filesystemOffset and socFamily == "esp8266" and ldscriptSource:
filesystemOffset = detectEsp8266FilesystemOffsetFromLdscript(ldscriptSource)
if filesystemOffset:
logLines.append(f"Derived filesystem offset from ldscript: {filesystemOffset}")
if not filesystemOffset and socFamily == "esp8266":
filesystemOffset = "0x300000"
logLines.append(
"WARN: Falling back to default ESP8266 filesystem offset 0x300000"
)
if filesystemOffset:
flashFiles.append({"offset": filesystemOffset, "file": filesystemFile})
else:
logLines.append(
f"WARN: No filesystem offset found in partitions.csv for {filesystemFile}"
)
flashPayload = {
"board": boardName,
"soc": socFamily,
"version": version,
"flash_files": flashFiles,
}
(targetVersionDir / "flash.json").write_text(
json.dumps(flashPayload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
def parseEnvs(platformioIni: Path) -> list[str]:
envs: list[str] = []
for line in platformioIni.read_text(encoding="utf-8", errors="ignore").splitlines():
match = envSectionPattern.match(line)
if match:
envs.append(match.group(1).strip())
seen = set()
uniqueEnvs = []
for env in envs:
if env and env not in seen:
uniqueEnvs.append(env)
seen.add(env)
return uniqueEnvs
def getWorkspaceDir(platformioIni: Path, projectPath: Path) -> Path:
sectionName = ""
workspaceValue = None
for rawLine in platformioIni.read_text(encoding="utf-8", errors="ignore").splitlines():
line = rawLine.strip()
if not line or line.startswith(";") or line.startswith("#"):
continue
sectionMatch = re.match(r"^\[(.+)\]$", line)
if sectionMatch:
sectionName = sectionMatch.group(1).strip().lower()
continue
if sectionName != "platformio":
continue
keyMatch = workspaceDirPattern.match(rawLine)
if keyMatch:
workspaceValue = keyMatch.group(1).strip()
break
if not workspaceValue:
return projectPath / ".pio"
expanded = workspaceValue
expanded = expanded.replace("${PROJECT_DIR}", str(projectPath))
expanded = expanded.replace("$PROJECT_DIR", str(projectPath))
expanded = expanded.replace("${platformio.packages_dir}", "")
resolved = Path(expanded).expanduser()
if not resolved.is_absolute():
resolved = (projectPath / resolved).resolve()
else:
resolved = resolved.resolve()
return resolved
def normalizeVersion(versionValue: str) -> str:
match = semverPattern.search(versionValue)
if not match:
return "v0.0.0"
return f"v{match.group(1)}.{match.group(2)}.{match.group(3)}"
def detectVersion(srcDir: Path) -> str:
if not srcDir.is_dir():
return "v0.0.0"
for filePath in sorted(srcDir.rglob("*")):
if not filePath.is_file():
continue
text = filePath.read_text(encoding="utf-8", errors="ignore")
if "PROG_VERSION" not in text:
continue
for line in text.splitlines():
if "PROG_VERSION" not in line:
continue
prefixedMatch = versionWithPrefixPattern.search(line)
if prefixedMatch:
return f"v{prefixedMatch.group(1)}"
semverMatch = semverPattern.search(line)
if semverMatch:
return f"v{semverMatch.group(1)}.{semverMatch.group(2)}.{semverMatch.group(3)}"
fallbackMatch = versionPattern.search(line)
if fallbackMatch:
return normalizeVersion(fallbackMatch.group(0))
return "v0.0.0"
def runCommand(cmd: list[str], cwd: Path, logLines: list[str]) -> None:
logLines.append(f"$ {' '.join(cmd)}")
process = subprocess.run(cmd, cwd=str(cwd), text=True, capture_output=True)
if process.stdout:
logLines.append(process.stdout.rstrip())
if process.stderr:
logLines.append(process.stderr.rstrip())
if process.returncode != 0:
raise RuntimeError(
f"Command failed ({process.returncode}): {' '.join(cmd)}\n{process.stderr}"
)
def discoverBuildDir(projectRoot: Path, workspaceDir: Path, envName: str) -> Path:
directCandidate = workspaceDir / "build" / envName
if directCandidate.exists():
return directCandidate
buildRoot = workspaceDir / "build"
if buildRoot.exists():
for child in sorted(buildRoot.iterdir()):
if not child.is_dir():
continue
if child.name == envName:
return child
if envName in child.name and (child / "firmware.bin").exists():
return child
fallbackPio = projectRoot / ".pio" / "build" / envName
if fallbackPio.exists():
return fallbackPio
raise RuntimeError(
f"Build directory not found for env '{envName}' in workspace_dir '{workspaceDir}' or fallback '.pio'."
)
def ensureProjectMetaDataDefaults(rootDir: Path) -> Path:
metaDataDir = rootDir / "projectMetaData"
if metaDataDir.exists() and metaDataDir.is_dir():
return metaDataDir
metaDataDir.mkdir(parents=True, exist_ok=True)
(metaDataDir / "project_en.md").write_text(
"# your_project_name\n\nDiscription in English\n", encoding="utf-8"
)
(metaDataDir / "project_nl.md").write_text(
"# your_project_name\n\nBeschrijving van het project in Dutch\n", encoding="utf-8"
)
payload = {
"name": "your_project_name",
"long_name_nl": "Langere naam in Dutch",
"long_name_en": "longer name in English",
"description_en": "Discription in English",
"description_nl": "Beschrijving van het project in Dutch",
"github_url": "https://github.com/mrWheel/",
"post_url": "https://willem.aandewiel.nl/",
"image": "thisProject.png",
}
(metaDataDir / "project.json").write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
targetImage = metaDataDir / "thisProject.png"
try:
urllib.request.urlretrieve(defaultProjectImageUrl, str(targetImage))
except Exception:
targetImage.touch()
return metaDataDir
def copyProjectMetaData(metaDataDir: Path, targetProjectDir: Path) -> None:
for item in sorted(metaDataDir.iterdir()):
if not item.is_file():
continue
destinationName = item.name
if item.name == "ESP32project.png":
destinationName = "thisProject.png"
shutil.copy2(item, targetProjectDir / destinationName)
def copyIfExists(source: Path, destination: Path) -> bool:
if source.exists() and source.is_file():
shutil.copy2(source, destination)
return True
return False
def collectAndCopyArtifacts(
projectRoot: Path,
workspaceDir: Path,
envName: str,
boardName: str,
socFamily: str,
targetVersionDir: Path,
envPartitionsSource: Path | None,
envLdscriptSource: Path | None,
version: str,
logLines: list[str],
) -> None:
buildDir = discoverBuildDir(projectRoot, workspaceDir, envName)
effectiveLdscriptSource = envLdscriptSource
if socFamily == "esp8266" and not effectiveLdscriptSource:
effectiveLdscriptSource = resolveGeneratedEsp8266Ldscript(buildDir)
if effectiveLdscriptSource:
logLines.append(f"Using generated ldscript source: {effectiveLdscriptSource}")
required = buildDir / "firmware.bin"
if not required.exists():
raise RuntimeError(f"firmware.bin not found for env '{envName}'")
shutil.copy2(required, targetVersionDir / "firmware.bin")
optionalFiles = [
"boot_app0.bin",
"bootloader.bin",
"partitions.bin",
"partitions.csv",
]
for name in optionalFiles:
copyIfExists(buildDir / name, targetVersionDir / name)
targetPartitionsCsv = targetVersionDir / "partitions.csv"
if envPartitionsSource and envPartitionsSource.exists():
shutil.copy2(envPartitionsSource, targetPartitionsCsv)
logLines.append(f"Using partitions source: {envPartitionsSource}")
if effectiveLdscriptSource and effectiveLdscriptSource.exists():
shutil.copy2(effectiveLdscriptSource, targetVersionDir / "ldscript.ld")
if envLdscriptSource and envLdscriptSource.exists():
logLines.append(f"Using ldscript source: {envLdscriptSource}")
fsCandidates = [
("spiffs.bin", "spiffs.bin"),
("littlefs.bin", "LittleFS.bin"),
("LittleFS.bin", "LittleFS.bin"),
]
for sourceName, destName in fsCandidates:
if copyIfExists(buildDir / sourceName, targetVersionDir / destName):
break
generateFlashJson(
targetVersionDir,
boardName,
version,
socFamily,
effectiveLdscriptSource,
logLines,
)
buildLogPath = targetVersionDir / "build_log.md"
now = dt.datetime.now().isoformat(timespec="seconds")
logBody = [f"# Build log for {envName}", "", f"Generated: {now}", ""]
logBody.extend(logLines)
logBody.append("")
logBody.append(f"Resolved buildDir: {buildDir}")
buildLogPath.write_text("\n".join(logBody).strip() + "\n", encoding="utf-8")
def resolveExecutable(commandName: str, preferredPaths: list[str]) -> str:
for preferredPath in preferredPaths:
pathObj = Path(preferredPath)
if pathObj.exists() and os.access(pathObj, os.X_OK):
return str(pathObj)
detectedPath = shutil.which(commandName)
if detectedPath:
return detectedPath
raise RuntimeError(f"Executable not found: {commandName}")
def syncProjectToAws(
projectsRoot: Path,
projectName: str,
awsServer: str,
awsTarget: str,
awsSshKey: Path,
awsDryRun: bool,
) -> None:
rsyncPath = resolveExecutable("rsync", ["/usr/bin/rsync"])
sshPath = resolveExecutable("ssh", ["/usr/bin/ssh"])
sourceProjectPath = projectsRoot / projectName
if not sourceProjectPath.exists():
raise RuntimeError(f"Project directory does not exist for sync: {sourceProjectPath}")
remoteProjectBase = f"{awsTarget.rstrip('/')}/projects"
remoteProjectPath = f"{remoteProjectBase}/{projectName}"
mkdirCmd = [
sshPath,
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=10",
"-i",
str(awsSshKey),
awsServer,
f"mkdir -p {shlex.quote(remoteProjectPath)}",
]
mkdirProcess = subprocess.run(mkdirCmd, text=True, capture_output=True)
if mkdirProcess.returncode != 0:
raise RuntimeError(
f"Failed to create AWS project directory: {mkdirProcess.stderr.strip() or mkdirProcess.stdout.strip()}"
)
sshRsyncTransport = (
f"{sshPath} -o BatchMode=yes -o ConnectTimeout=10 -i {shlex.quote(str(awsSshKey))}"
)
rsyncCmd = [
rsyncPath,
"-avz",
"--update",
"-e",
sshRsyncTransport,
"--exclude",
".DS_Store",
"--exclude",
"*.tmp",
"--exclude",
"*.bak",
"--exclude",
".venv/",
]
if awsDryRun:
rsyncCmd.extend(["--dry-run", "--itemize-changes"])
rsyncCmd.extend(
[
f"{sourceProjectPath}/",
f"{awsServer}:{remoteProjectPath}/",
]
)
print("Starting AWS sync for project directory...")
print(f" Local: {sourceProjectPath}")
print(f" Remote: {awsServer}:{remoteProjectPath}")
print(f" SSH key: {awsSshKey}")
print(f" Binaries: rsync={rsyncPath}, ssh={sshPath}")
process = subprocess.run(rsyncCmd, text=True, capture_output=True)
if process.stdout:
print(process.stdout.strip())
if process.stderr:
print(process.stderr.strip())
if process.returncode != 0:
raise RuntimeError(f"AWS rsync failed with code {process.returncode}")
def syncProjectsFolderToAws(
projectsRoot: Path,
awsServer: str,
awsTarget: str,
awsSshKey: Path,
awsDryRun: bool,
) -> None:
rsyncPath = resolveExecutable("rsync", ["/usr/bin/rsync"])
sshPath = resolveExecutable("ssh", ["/usr/bin/ssh"])
if not projectsRoot.exists() or not projectsRoot.is_dir():
raise RuntimeError(f"Projects directory does not exist for sync: {projectsRoot}")
remoteProjectsPath = f"{awsTarget.rstrip('/')}/projects"
mkdirCmd = [
sshPath,
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=10",
"-i",
str(awsSshKey),
awsServer,
f"mkdir -p {shlex.quote(remoteProjectsPath)}",
]
mkdirProcess = subprocess.run(mkdirCmd, text=True, capture_output=True)
if mkdirProcess.returncode != 0:
raise RuntimeError(
f"Failed to create AWS projects directory: {mkdirProcess.stderr.strip() or mkdirProcess.stdout.strip()}"
)
sshRsyncTransport = (
f"{sshPath} -o BatchMode=yes -o ConnectTimeout=10 -i {shlex.quote(str(awsSshKey))}"
)
rsyncCmd = [
rsyncPath,
"-avz",
"--update",
"-e",
sshRsyncTransport,
"--exclude",
".DS_Store",
"--exclude",
"*.tmp",
"--exclude",
"*.bak",
"--exclude",
".venv/",
]
if awsDryRun:
rsyncCmd.extend(["--dry-run", "--itemize-changes"])
rsyncCmd.extend(
[
f"{projectsRoot}/",
f"{awsServer}:{remoteProjectsPath}/",
]
)
print("Starting AWS sync for full projects directory...")
print(f" Local: {projectsRoot}")
print(f" Remote: {awsServer}:{remoteProjectsPath}")
print(f" SSH key: {awsSshKey}")
print(f" Binaries: rsync={rsyncPath}, ssh={sshPath}")
process = subprocess.run(rsyncCmd, text=True, capture_output=True)
if process.stdout:
print(process.stdout.strip())
if process.stderr:
print(process.stderr.strip())
if process.returncode != 0:
raise RuntimeError(f"AWS rsync failed with code {process.returncode}")
def validateProjectsFolderForAwsSync(projectsRoot: Path) -> None:
if not projectsRoot.exists() or not projectsRoot.is_dir():
raise RuntimeError(f"Projects directory does not exist: {projectsRoot}")
projectDirs = sorted([path for path in projectsRoot.iterdir() if path.is_dir()])
if not projectDirs:
raise RuntimeError(f"Projects directory is empty: {projectsRoot}")
requiredMetaFiles = ["project.json", "project_en.md", "project_nl.md"]
validationErrors: list[str] = []
for projectDir in projectDirs:
for fileName in requiredMetaFiles:
if not (projectDir / fileName).is_file():
validationErrors.append(
f"{projectDir.name}: missing metadata file '{fileName}'"
)
versionArtifacts = sorted(projectDir.rglob("flash.json"))
if not versionArtifacts:
validationErrors.append(
f"{projectDir.name}: no build output found (flash.json is missing)"
)
continue
hasValidArtifactSet = False
for flashJsonPath in versionArtifacts:
artifactDir = flashJsonPath.parent
if (artifactDir / "firmware.bin").is_file():
hasValidArtifactSet = True
break
if not hasValidArtifactSet:
validationErrors.append(
f"{projectDir.name}: invalid build output (firmware.bin is missing next to flash.json)"
)
if validationErrors:
errorLines = "\n - " + "\n - ".join(validationErrors)
raise RuntimeError(
"Projects directory is not correctly populated for --only-sync-aws:" + errorLines
)
def main() -> int:
parser = argparse.ArgumentParser(
usage="%(prog)s [platformioProject] [--sync-aws | --only-sync-aws] [--aws-dry-run]",
description=f"createProjectStructure.py {scriptVersion}\nCreate projects structure from a PlatformIO project.",
)
parser.add_argument(
"platformioProject",
nargs="?",
help="Path to PlatformIO project",
)
syncModeGroup = parser.add_mutually_exclusive_group()
syncModeGroup.add_argument(
"--sync-aws",
action="store_true",
help="Sync generated projects/<project> directory to AWS (add/update only, never delete)",
)
syncModeGroup.add_argument(
"--only-sync-aws",
action="store_true",
help="Skip build and only sync the full local projects directory to AWS",
)
parser.add_argument(
"--aws-dry-run",
action="store_true",
help="Show AWS rsync changes without actually copying",
)
if len(sys.argv) == 1:
parser.print_help()
return 0
args = parser.parse_args()
if not args.platformioProject:
parser.print_help()
return 0
projectPath = Path(args.platformioProject).expanduser().resolve()
if not projectPath.exists() or not projectPath.is_dir():
raise SystemExit(f"Invalid project path: {projectPath}")
outputRoot = projectPath
projectsRoot = outputRoot / "projects"
if args.only_sync_aws:
awsSshKey = Path(defaultAwsSshKey).expanduser().resolve()
if not awsSshKey.exists():
raise SystemExit(f"SSH key not found: {awsSshKey}")
print(f"Validating projects directory: {projectsRoot}")
validateProjectsFolderForAwsSync(projectsRoot)
syncProjectsFolderToAws(
projectsRoot=projectsRoot,
awsServer=defaultAwsServer,
awsTarget=defaultAwsTarget,
awsSshKey=awsSshKey,
awsDryRun=args.aws_dry_run,
)
print("Projects directory synchronized successfully.")
return 0
if shutil.which("pio") is None:
raise SystemExit(
"PlatformIO CLI not found. Install PlatformIO Core and ensure 'pio' is in PATH."
)
os.chdir(projectPath)
platformioIni = projectPath / "platformio.ini"
if not platformioIni.exists():
raise SystemExit(f"platformio.ini not found in: {projectPath}")
workspaceDir = getWorkspaceDir(platformioIni, projectPath)
platformioSections = parsePlatformioSections(platformioIni)
envs = parseEnvs(platformioIni)
if not envs:
raise SystemExit("No [env:...] sections found in platformio.ini")
envBoardMap: dict[str, str] = {}
envSocMap: dict[str, str] = {}
boardCounts: dict[str, int] = {}
for env in envs:
boardName = resolveEnvBoardName(platformioSections, env)
platformName = resolveEnvPlatformName(platformioSections, env)
socFamily = detectSocFamily(boardName, platformName)
envBoardMap[env] = boardName
envSocMap[env] = socFamily
boardCounts[boardName] = boardCounts.get(boardName, 0) + 1
version = detectVersion(projectPath / "src")
projectName = projectPath.name
targetProjectDir = projectsRoot / projectName
if targetProjectDir.exists():
print(f"Removing existing project directory: {targetProjectDir}")
shutil.rmtree(targetProjectDir)
targetProjectDir.mkdir(parents=True, exist_ok=True)
projectMetaDataDir = ensureProjectMetaDataDefaults(projectPath)
copyProjectMetaData(projectMetaDataDir, targetProjectDir)
print(f"createProjectStructure.py {scriptVersion}")
print(f"Project: {projectName}")
print(f"Version: {version}")
print(f"Environments: {', '.join(envs)}")
print("Boards per environment:")
for env in envs:
print(f" - {env} -> {envBoardMap[env]} ({envSocMap[env]})")
print(f"Output: {targetProjectDir}")
print(f"Workspace dir: {workspaceDir}")
for env in envs:
boardName = envBoardMap[env]
socFamily = envSocMap[env]
if boardCounts[boardName] > 1:
envVersionDir = targetProjectDir / env / boardName / version
else:
envVersionDir = targetProjectDir / boardName / version
envVersionDir.mkdir(parents=True, exist_ok=True)
logLines: list[str] = []
runCommand(["pio", "run", "-e", env], projectPath, logLines)
if (projectPath / "data").is_dir():
try:
runCommand(["pio", "run", "-e", env, "-t", "buildfs"], projectPath, logLines)
except RuntimeError as exc:
logLines.append(f"WARN: buildfs niet gelukt voor {env}: {exc}")
envPartitionsSource = resolveEnvPartitionsSource(
projectPath,
platformioSections,
env,
socFamily,
)
envLdscriptSource = resolveEnvLdscriptSource(
projectPath,
platformioSections,
env,
socFamily,
)
collectAndCopyArtifacts(
projectPath,