forked from ArthurkaX/cds-text-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProject_import.py
More file actions
1111 lines (925 loc) · 47 KB
/
Project_import.py
File metadata and controls
1111 lines (925 loc) · 47 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
# -*- coding: utf-8 -*-
"""
Project_import.py - Import edited ST files back into CODESYS project
Reads _metadata.json to match files to CODESYS objects by GUID, then updates
the textual declaration and implementation from the ST files.
Usage: Run from CODESYS IDE after setting sync directory with Project_directory.py
and editing files
"""
import os
import codecs
import json
import time
# Ensure global objects are available if imported
try:
_ = projects.primary
except NameError:
# If this script is imported by another script (Daemon), global variables like 'projects'
# might not be directly available in this scope unless injected.
# However, usually they are injected into the top-level script execution context.
pass
import re
from codesys_constants import IMPL_MARKER, TYPE_GUIDS, PROPERTY_GET_MARKER, PROPERTY_SET_MARKER
from codesys_utils import (
safe_str, parse_st_file, build_object_cache,
find_object_by_guid, find_object_by_name, load_base_dir,
calculate_hash, save_metadata, load_metadata,
format_st_content, log_info, log_warning, log_error, MetadataLock,
load_libraries, extract_libraries_from_project,
init_logging, get_project_prop, backup_project_binary,
parse_property_content, format_property_content
)
# Shared constants and utilities imported from modules
def update_object_code(obj, declaration, implementation):
"""
Update object's textual declaration and/or implementation.
Returns True if any update was made.
"""
updated = False
obj_name = safe_str(obj.get_name())
# Update declaration
if declaration:
try:
if hasattr(obj, "has_textual_declaration") and obj.has_textual_declaration:
obj.textual_declaration.replace(declaration)
updated = True
else:
log_warning(obj_name + " has no textual declaration property")
except Exception as e:
log_error("Error updating declaration for " + obj_name + ": " + safe_str(e))
# Update implementation
if implementation:
try:
if hasattr(obj, "has_textual_implementation") and obj.has_textual_implementation:
obj.textual_implementation.replace(implementation)
updated = True
else:
# This is normal for GVLs and DUTs - they only have declaration
pass
except Exception as e:
log_error("Error updating implementation for " + obj_name + ": " + safe_str(e))
return updated
def determine_object_type(content):
"""Determine CODESYS object type from ST content"""
# Remove comments and pragmas to avoid false matches
# 1. Remove (* ... *) multiline comments
content = re.sub(r"\(\*[\s\S]*?\*\)", "", content)
# 2. Remove { ... } pragmas/attributes
content = re.sub(r"\{[\s\S]*?\}", "", content)
# 3. Remove // ... single line comments
content = re.sub(r"//.*", "", content)
content = content.strip()
lines = content.splitlines()
for line in lines:
line = line.strip()
if not line:
continue
# Check keywords
parts = line.split()
if not parts:
continue
word = parts[0].upper()
if word == "PROGRAM":
return TYPE_GUIDS["pou"]
if word == "FUNCTION_BLOCK":
return TYPE_GUIDS["pou"]
if word == "FUNCTION":
return TYPE_GUIDS["pou"]
if word == "VAR_GLOBAL":
return TYPE_GUIDS["gvl"]
if word == "TYPE":
return TYPE_GUIDS["dut"]
if word == "INTERFACE":
return TYPE_GUIDS["itf"]
if word == "METHOD":
return TYPE_GUIDS["method"]
if word == "PROPERTY":
return TYPE_GUIDS["property"]
if word == "ACTION":
return TYPE_GUIDS["action"]
return None
# Global cache for start_obj to avoid repetitive searches and logging
_ensure_folder_start_obj = None
def ensure_folder_path(path_str):
"""
Ensure folder structure exists in CODESYS project.
path_str: relative path string e.g. "Folder/SubFolder"
Returns the parent object (folder) or None if failed.
"""
global _ensure_folder_start_obj
if _ensure_folder_start_obj is None:
def find_application_recursive(obj, depth=0):
"""Recursively search for Application or PLC Logic container"""
if depth > 3: # Limit recursion depth
return None
try:
children = obj.get_children()
for child in children:
try:
child_type = safe_str(child.type)
if child_type == TYPE_GUIDS["application"]:
return child
if child_type == TYPE_GUIDS["device"] or child_type == TYPE_GUIDS["plc_logic"]:
result = find_application_recursive(child, depth + 1)
if result:
return result
except:
continue
except:
pass
return None
try:
start_obj = find_application_recursive(projects.primary, 0)
if start_obj:
_ensure_folder_start_obj = start_obj
try:
container_name = safe_str(start_obj.get_name())
container_type = safe_str(start_obj.type)
print(" >>> Using container: " + container_name + " (type: " + container_type + ")")
except:
print(" >>> Found container")
except Exception as e:
print(" Error getting project children: " + safe_str(e))
start_obj = _ensure_folder_start_obj
# Fallback to primary project if we can't find Application
if start_obj is None:
if _ensure_folder_start_obj is None: # Only warn once
print(" Warning: Could not find Application/PLC Logic container, using project root")
_ensure_folder_start_obj = projects.primary
start_obj = _ensure_folder_start_obj
if not path_str or path_str == ".":
return start_obj
parts = path_str.replace("\\", "/").split("/")
current_obj = start_obj
for part in parts:
if not part: continue
matches = []
try:
children = current_obj.get_children()
except:
children = []
for child in children:
if child.get_name().lower() == part.lower():
try:
child_type = safe_str(child.type)
if child_type == TYPE_GUIDS["device"]:
continue
except:
pass
matches.append(child)
found = None
if len(matches) > 1:
print(" Found " + str(len(matches)) + " match(es) for '" + part + "' (Ambiguity):")
for m in matches:
try:
m_type = safe_str(m.type)
m_name = safe_str(m.get_name())
print(" - " + m_name + " (type: " + m_type + ")")
except:
pass
for m in matches:
try:
obj_type = safe_str(m.type)
if obj_type == TYPE_GUIDS["folder"]:
found = m
break
except:
pass
if not found:
for m in matches:
if hasattr(m, "create_child"):
found = m
break
if not found and matches:
found = matches[0]
if found:
current_obj = found
else:
try:
parent_obj = current_obj
current_obj = None
if hasattr(parent_obj, "create_folder"):
try:
current_obj = parent_obj.create_folder(part)
except Exception as e:
pass
if not current_obj and hasattr(parent_obj, "create_child"):
try:
current_obj = parent_obj.create_child(part, "738bea1e-99bb-4f04-90bb-a7a567e74e3a")
except Exception as e:
pass
if not current_obj:
try:
children = parent_obj.get_children()
for child in children:
if child.get_name().lower() == part.lower():
current_obj = child
break
except:
pass
if not current_obj:
return None
except Exception as e:
print(" Error creating folder " + part + ": " + safe_str(e))
return None
return current_obj
def cleanup_ide_orphans(import_dir, objects_meta, guid_map, name_map, silent=False):
"""
Find objects in IDE that have no corresponding file on disk and ask to delete them.
Returns list of rel_paths that were deleted.
"""
orphans = []
# Sort by depth (number of slashes) and then by length to ensure children
# (longer names like Parent.Method) are processed before parents.
all_paths = sorted(objects_meta.keys(), key=lambda x: (x.count('/'), len(x)), reverse=True)
for rel_path in all_paths:
file_path = os.path.join(import_dir, rel_path.replace("/", os.sep))
if not os.path.exists(file_path):
info = objects_meta[rel_path]
# Debug: Log methods being considered for deletion
if info.get("type") == TYPE_GUIDS["method"]:
print("DEBUG: Method file not found, marking as orphan: " + rel_path)
print("DEBUG: Expected file path: " + file_path)
obj = None
if info.get("guid") and info.get("guid") != "N/A":
obj = find_object_by_guid(info["guid"], guid_map)
if not obj and info.get("name"):
obj = find_object_by_name(info["name"], name_map, info.get("parent"))
if obj:
orphans.append((rel_path, obj))
if not orphans:
return []
# Check for auto-delete property
try:
auto_delete = get_project_prop("cds-sync-auto-delete-orphans", False)
except:
auto_delete = False
if silent:
if auto_delete:
result = (0,) # Simulate Delete
else:
print("Silent import: " + str(len(orphans)) + " objects need deletion but auto-delete is OFF.")
return [] # Ignore
else:
message = "The following objects were removed from the disk but still exist in CODESYS:\n\n"
for rel_path, _ in orphans[:15]:
message += "- " + rel_path + "\n"
message += "\nWould you like to delete these objects from the CODESYS project?"
try:
result = system.ui.choose(message, ("Delete from IDE", "Ignore", "Cancel Import"))
except:
return []
if result[0] == 0:
deleted_paths = []
for rel_path, obj in orphans:
try:
# Check if object still exists and has a parent (not already removed)
if obj and hasattr(obj, "get_name"):
try:
_ = obj.guid # Trigger access check
except:
# Object became invalid (probably parent was deleted)
continue
obj.remove()
deleted_paths.append(rel_path)
except Exception as e:
# Ignore "Object reference not set" which often means already deleted
if "Object reference not set" not in safe_str(e):
print("Error deleting " + rel_path + ": " + safe_str(e))
else:
# Successfully "deleted" (effectively)
deleted_paths.append(rel_path)
return deleted_paths
elif result[0] == 1:
return []
else:
return None
def sync_libraries(import_dir, silent=False):
"""
Check libraries in project against _libraries.csv and warn about differences.
Note: Automatic library updates are not reliable across all CODESYS versions.
"""
libraries_file = load_libraries(import_dir)
if not libraries_file:
return
print(" Checking project libraries...")
# Get current project libraries
current_libs = extract_libraries_from_project(projects.primary)
if not current_libs:
print(" Warning: Could not extract current library information")
return
# Compare
missing_libs = []
mismatch_libs = []
for lib_file in libraries_file:
found = False
for lib_proj in current_libs:
# Match by name or namespace to be robust
if lib_file["name"] == lib_proj["name"] or (lib_file["namespace"] != "N/A" and lib_file["namespace"] == lib_proj["namespace"]):
found = True
if lib_file["version"] != lib_proj["version"]:
mismatch_libs.append((lib_file, lib_proj))
break
if not found:
missing_libs.append(lib_file)
if not missing_libs and not mismatch_libs:
print(" All libraries match.")
return
# Show status
if silent:
print("Silent Mode: Library version differences detected (see log). Ignoring.")
# Log details
if missing_libs:
for lib in missing_libs:
print("MISSING LIB: " + safe_str(lib.get("name")))
return
message = "Library differences detected (Version Control):\n\n"
if missing_libs:
message += "Missing in CODESYS project:\n"
for lib in missing_libs:
message += "- " + lib["name"] + " (" + lib["version"] + ")\n"
message += "\n"
if mismatch_libs:
message += "Version differences:\n"
for lib_file, lib_proj in mismatch_libs:
message += "- " + lib_file["name"] + ":\n On disk: " + lib_file["version"] + "\n In IDE: " + lib_proj["version"] + "\n"
message += "\nPlease update libraries manually via Library Manager.\n"
message += "Would you like to continue with import?"
try:
result = system.ui.choose(message, ("Continue Import", "Cancel Import"))
except:
return
if result[0] == 1: # Cancel
return "CANCEL"
def import_project(import_dir, projects_obj=None, silent=False):
"""Import ST files from folder structure back into CODESYS project"""
# Resolving projects object
if projects_obj is None:
# Check globals first (explicitly)
projects_obj = globals().get("projects")
# Fallback to sys.modules or __main__
if projects_obj is None:
try:
import __main__
projects_obj = getattr(__main__, "projects", None)
except:
pass
if projects_obj is None:
try:
import sys
for module in sys.modules.values():
if hasattr(module, "projects") and hasattr(getattr(module, "projects"), "primary"):
projects_obj = module.projects
break
except:
pass
if projects_obj is None:
error_msg = "Script Error: 'projects' object not found."
if not silent:
system.ui.error(error_msg)
else:
print(error_msg)
return
if not projects_obj.primary:
if not silent:
system.ui.error("No project open!")
else:
print("Error: No project open")
return
# Check save setting
should_save = get_project_prop("cds-sync-save-after-import", True)
print("=== Starting Project Import ===")
print("Import directory: " + import_dir)
print("Auto-save enabled: " + str(should_save))
start_time = time.time()
# Find Application container early
app_container = None
def find_application_recursive(obj, depth=0):
if depth > 3:
return None
try:
children = obj.get_children()
for child in children:
try:
child_type = safe_str(child.type)
if child_type == TYPE_GUIDS["application"]:
return child
if child_type == TYPE_GUIDS["device"] or child_type == TYPE_GUIDS["plc_logic"]:
result = find_application_recursive(child, depth + 1)
if result:
return result
except:
continue
except:
pass
return None
try:
app_container = find_application_recursive(projects_obj.primary, 0)
except:
pass
with MetadataLock(import_dir, timeout=60):
# Load metadata
metadata = load_metadata(import_dir)
if not metadata:
if not silent:
system.ui.error("Metadata not found!\n\nPlease run Project_export.py first.")
else:
print("Error: Metadata not found")
return
objects_meta = metadata.get("objects", {})
print(" Loaded " + str(len(objects_meta)) + " objects from metadata")
# Build cache
print(" Building object cache...")
guid_map, name_map = build_object_cache(projects.primary)
print(" Cache built: " + str(len(guid_map)) + " objects by GUID")
# Cleanup IDE orphans
deleted_from_ide = cleanup_ide_orphans(import_dir, objects_meta, guid_map, name_map, silent=silent)
if deleted_from_ide is None:
return
for path in deleted_from_ide:
if path in objects_meta:
del objects_meta[path]
# Sync libraries first
if sync_libraries(import_dir, silent=silent) == "CANCEL":
print("Import cancelled during library sync.")
return
# Track existing folders
tracked_folders = set()
for rel_path in objects_meta.keys():
parts = rel_path.split("/")
for i in range(1, len(parts)):
tracked_folders.add("/".join(parts[:i]))
# Identify new files and folders
new_files = []
new_folders = []
for root, dirs, files in os.walk(import_dir):
dirs[:] = [d for d in dirs if not d.startswith('.')]
for d in dirs:
rel_path = os.path.relpath(os.path.join(root, d), import_dir).replace(os.sep, "/")
if rel_path not in objects_meta and rel_path not in tracked_folders:
new_folders.append(rel_path)
for name in files:
if name in ["_metadata.json", "_config.json", "_metadata.csv", "BASE_DIR", "sync_debug.log"] or name.startswith('.'):
continue
if not name.endswith(".st"):
continue
rel_path = os.path.relpath(os.path.join(root, name), import_dir).replace(os.sep, "/")
if rel_path not in objects_meta:
new_files.append((rel_path, os.path.join(root, name)))
updated_count = 0
failed_count = 0
skipped_count = 0
created_count = 0
deleted_count = len(deleted_from_ide) if deleted_from_ide else 0
folder_cache = {} # Shared cache for folder resolution during this import
# Update existing objects
for rel_path, obj_info in objects_meta.items():
file_path = os.path.join(import_dir, rel_path.replace("/", os.sep))
if not os.path.exists(file_path):
skipped_count += 1
continue
if obj_info.get("type") == TYPE_GUIDS["folder"] or os.path.isdir(file_path):
continue
obj = None
if obj_info.get("guid") and obj_info.get("guid") != "N/A":
obj = find_object_by_guid(obj_info["guid"], guid_map)
# Debug: Log method lookups
if obj_info.get("type") == TYPE_GUIDS["method"]:
if obj:
print("DEBUG: Found method by GUID: " + rel_path)
else:
print("DEBUG: Method NOT found by GUID: " + rel_path + " (GUID: " + obj_info["guid"] + ")")
print("DEBUG: guid_map has " + str(len(guid_map)) + " entries")
if obj is None and obj_info.get("name"):
obj = find_object_by_name(obj_info["name"], name_map, obj_info.get("parent"))
# Debug: Log method name lookups
if obj_info.get("type") == TYPE_GUIDS["method"]:
if obj:
print("DEBUG: Found method by name: " + rel_path)
else:
print("DEBUG: Method NOT found by name either: " + rel_path)
if obj is None:
# Object not found - it was deleted from CODESYS but file still exists
# Treat this as a new file that needs to be created
print(" Object not found (deleted?), will recreate: " + rel_path)
# Add to new_files list for creation
if rel_path not in [nf[0] for nf in new_files]:
new_files.append((rel_path, file_path))
# Remove from metadata so it gets recreated
if rel_path in objects_meta:
del objects_meta[rel_path]
continue
# Optimization: Check timestamp first
current_mtime = safe_str(os.path.getmtime(file_path))
stored_mtime = obj_info.get("last_modified", "")
stored_hash = obj_info.get("content_hash", "")
if current_mtime == stored_mtime and stored_hash:
print(" Skipped: " + rel_path + " (Timestamp match)")
skipped_count += 1
continue
# Special handling for properties with combined GET/SET accessors
if obj_info.get("type") == TYPE_GUIDS["property"]:
# Read file content
try:
with codecs.open(file_path, "r", "utf-8") as f:
content = f.read()
except Exception as e:
print(" Error reading property file " + rel_path + ": " + safe_str(e))
failed_count += 1
continue
# Parse property content
declaration, get_impl, set_impl = parse_property_content(content)
# Update property declaration
if declaration and update_object_code(obj, declaration, None):
print(" Updated property declaration: " + rel_path)
# Find and update GET accessor
if get_impl:
try:
children = obj.get_children()
for child in children:
if child.get_name().lower() == "get":
# Parse the combined GET content back into declaration and implementation
get_decl = None
get_code = None
if IMPL_MARKER in get_impl:
parts = get_impl.split(IMPL_MARKER, 1)
get_decl = parts[0].strip() if parts[0] else None
get_code = parts[1].strip() if len(parts) > 1 and parts[1] else None
else:
# No implementation, only declaration (VAR section)
get_decl = get_impl.strip() if get_impl else None
if update_object_code(child, get_decl, get_code):
print(" Updated GET accessor: " + rel_path)
break
except Exception as e:
print(" Error updating GET accessor: " + safe_str(e))
# Find and update SET accessor
if set_impl:
try:
children = obj.get_children()
for child in children:
if child.get_name().lower() == "set":
# Parse the combined SET content back into declaration and implementation
set_decl = None
set_code = None
if IMPL_MARKER in set_impl:
parts = set_impl.split(IMPL_MARKER, 1)
set_decl = parts[0].strip() if parts[0] else None
set_code = parts[1].strip() if len(parts) > 1 and parts[1] else None
else:
# No implementation, only declaration (VAR section)
set_decl = set_impl.strip() if set_impl else None
if update_object_code(child, set_decl, set_code):
print(" Updated SET accessor: " + rel_path)
break
except Exception as e:
print(" Error updating SET accessor: " + safe_str(e))
# Update metadata
current_hash = calculate_hash(content)
obj_info["content_hash"] = current_hash
obj_info["last_modified"] = current_mtime
updated_count += 1
continue
declaration, implementation = parse_st_file(file_path)
if declaration is None and implementation is None:
skipped_count += 1
continue
full_content = format_st_content(declaration, implementation)
current_hash = calculate_hash(full_content)
if current_hash == stored_hash:
print(" Skipped: " + rel_path + " (Hash match, updating timestamp)")
obj_info["last_modified"] = current_mtime
skipped_count += 1
continue
print(" Updating: " + rel_path + " (Change detected)")
if update_object_code(obj, declaration, implementation):
updated_count += 1
obj_info["content_hash"] = current_hash
obj_info["last_modified"] = current_mtime
else:
print(" Warning: No changes applied to " + rel_path)
skipped_count += 1
# Process new folders
if new_folders:
new_folders.sort(key=len)
for folder_path in new_folders:
# Only process folders in src directory
if not folder_path.startswith("src"):
continue
if folder_path == "src":
continue
# Calculate CODESYS path (remove src prefix)
codesys_path = folder_path[4:] if folder_path.startswith("src/") else ""
if folder_path in folder_cache:
created_folder = folder_cache[folder_path]
else:
created_folder = ensure_folder_path(codesys_path)
folder_cache[folder_path] = created_folder
if created_folder:
created_count += 1
objects_meta[folder_path] = {
"guid": safe_str(created_folder.guid),
"type": TYPE_GUIDS["folder"],
"name": safe_str(created_folder.get_name()),
"parent": safe_str(created_folder.parent.get_name()) if created_folder.parent else "N/A",
"content_hash": ""
}
# Process new files
if new_files:
parent_ops = []
child_ops = []
for rel_path, file_path in new_files:
# Only process files in src directory
if not rel_path.startswith("src/"):
continue
declaration, implementation = parse_st_file(file_path)
content_check = declaration if declaration else implementation
if not content_check:
skipped_count += 1
continue
type_guid = determine_object_type(content_check)
# Strip src/ prefix for path parsing
filesys_path_parts = rel_path.split("/")
if filesys_path_parts[0] == "src":
path_parts = filesys_path_parts[1:]
else:
path_parts = filesys_path_parts
base_name = os.path.splitext(path_parts[-1])[0]
is_child = False
child_info = None
if not is_child:
upper_name = base_name.upper()
if upper_name.endswith(".GET"):
type_guid = TYPE_GUIDS["property_accessor"]
child_info = (base_name[:-4], "Get")
is_child = True
elif upper_name.endswith(".SET"):
type_guid = TYPE_GUIDS["property_accessor"]
child_info = (base_name[:-4], "Set")
is_child = True
elif base_name in ["Get", "Set"] and len(path_parts) > 1:
type_guid = TYPE_GUIDS["property_accessor"]
p_name = path_parts[-2]
child_info = (p_name, base_name)
is_child = True
if not is_child and (not type_guid or type_guid in [TYPE_GUIDS["method"], TYPE_GUIDS["property"], TYPE_GUIDS["action"]]):
if "." in base_name:
parts = base_name.rsplit(".", 1)
child_info = (parts[0], parts[1])
is_child = True
op_data = {
"rel_path": rel_path, "file_path": file_path, "base_name": base_name,
"type_guid": type_guid, "declaration": declaration, "implementation": implementation,
"is_child": is_child, "child_info": child_info, "content_check": content_check
}
if is_child:
child_ops.append(op_data)
else:
parent_ops.append(op_data)
print(" Found " + str(len(parent_ops)) + " new parent objects and " + str(len(child_ops)) + " new children")
new_stats = {"updated": 0, "created": 0, "failed": 0, "skipped": 0}
def process_op(op):
type_guid = op["type_guid"]
if not type_guid:
new_stats["skipped"] += 1
return
create_container = None
obj_name = op["base_name"]
if op["is_child"] and op["child_info"]:
p_name, c_name = op["child_info"]
parent_obj = find_object_by_name(p_name, name_map)
if parent_obj:
obj_name = c_name
create_container = parent_obj
print(" Identified parent " + p_name + " for new object " + c_name)
else:
print(" Error: Could not find parent " + p_name + " for new object " + c_name)
else:
# New parent object - resolve folder path
rel_path = op["rel_path"] # e.g. src/Folder/POU.st
if "/" in rel_path:
# logical_folder_path: src/Folder
logical_folder_path = "/".join(rel_path.split("/")[:-1])
if logical_folder_path == "src":
create_container = app_container
elif logical_folder_path in folder_cache:
create_container = folder_cache[logical_folder_path]
else:
# Parse CODESYS path
codesys_path = logical_folder_path[4:] if logical_folder_path.startswith("src/") else logical_folder_path
create_container = ensure_folder_path(codesys_path)
folder_cache[logical_folder_path] = create_container
else:
create_container = app_container
if not create_container:
print(" Error: Could not determine container for " + op["rel_path"])
new_stats["failed"] += 1
return
obj = None
try:
# Check existing
children = create_container.get_children()
for child in children:
if child.get_name().lower() == obj_name.lower():
obj = child
break
if not obj:
if op["type_guid"] == TYPE_GUIDS["gvl"] and hasattr(create_container, "create_gvl"):
obj = create_container.create_gvl(obj_name)
elif op["type_guid"] == TYPE_GUIDS["dut"] and hasattr(create_container, "create_dut"):
obj = create_container.create_dut(obj_name)
elif op["type_guid"] == TYPE_GUIDS["method"] and hasattr(create_container, "create_method"):
obj = create_container.create_method(obj_name)
elif op["type_guid"] == TYPE_GUIDS["property"] and hasattr(create_container, "create_property"):
obj = create_container.create_property(obj_name)
elif op["type_guid"] == TYPE_GUIDS["action"] and hasattr(create_container, "create_action"):
obj = create_container.create_action(obj_name)
elif op["type_guid"] == TYPE_GUIDS["property_accessor"]:
if obj_name.lower() == "get" and hasattr(create_container, "create_get_accessor"):
obj = create_container.create_get_accessor()
elif obj_name.lower() == "set" and hasattr(create_container, "create_set_accessor"):
obj = create_container.create_set_accessor()
elif hasattr(create_container, "create_pou"):
# Default to Program for general POU creation if type is unknown or pou
p_type = PouType.Program
obj = create_container.create_pou(obj_name, p_type)
elif hasattr(create_container, "create_child"):
obj = create_container.create_child(obj_name, op["type_guid"])
if obj:
# Special handling for properties with combined GET/SET
if op["type_guid"] == TYPE_GUIDS["property"]:
# Read and parse property file
try:
with codecs.open(op["file_path"], "r", "utf-8") as f:
content = f.read()
declaration, get_impl, set_impl = parse_property_content(content)
# Update property declaration
if declaration:
update_object_code(obj, declaration, None)
# Create/update GET accessor
if get_impl:
get_obj = None
try:
prop_children = obj.get_children()
for child in prop_children:
if child.get_name().lower() == "get":
get_obj = child
break
except:
pass
if not get_obj and hasattr(obj, "create_get_accessor"):
try:
get_obj = obj.create_get_accessor()
except:
pass
if get_obj:
# Parse the combined GET content back into declaration and implementation
# get_impl is a string with format: "VAR\n...\nEND_VAR\n\n// === IMPLEMENTATION ===\n<code>"
get_decl = None
get_code = None
if IMPL_MARKER in get_impl:
parts = get_impl.split(IMPL_MARKER, 1)
get_decl = parts[0].strip() if parts[0] else None
get_code = parts[1].strip() if len(parts) > 1 and parts[1] else None
else:
# No implementation, only declaration (VAR section)
get_decl = get_impl.strip() if get_impl else None
update_object_code(get_obj, get_decl, get_code)
# Create/update SET accessor
if set_impl:
set_obj = None
try:
prop_children = obj.get_children()
for child in prop_children:
if child.get_name().lower() == "set":
set_obj = child
break
except:
pass
if not set_obj and hasattr(obj, "create_set_accessor"):
try:
set_obj = obj.create_set_accessor()
except:
pass
if set_obj:
# Parse the combined SET content back into declaration and implementation
# set_impl is a string with format: "VAR\n...\nEND_VAR\n\n// === IMPLEMENTATION ===\n<code>"
set_decl = None
set_code = None
if IMPL_MARKER in set_impl:
parts = set_impl.split(IMPL_MARKER, 1)
set_decl = parts[0].strip() if parts[0] else None
set_code = parts[1].strip() if len(parts) > 1 and parts[1] else None
else:
# No implementation, only declaration (VAR section)
set_decl = set_impl.strip() if set_impl else None
update_object_code(set_obj, set_decl, set_code)
new_stats["updated"] += 1
new_stats["created"] += 1
objects_meta[op["rel_path"]] = {
"guid": safe_str(obj.guid),
"type": op["type_guid"],
"name": obj_name,
"parent": safe_str(obj.parent.get_name()) if obj.parent else "N/A",
"content_hash": calculate_hash(content)
}
if obj_name not in name_map: name_map[obj_name] = []
name_map[obj_name].append(obj)
except Exception as e:
print(" Error processing property file: " + safe_str(e))
new_stats["failed"] += 1
else:
# Normal object (not property)
if update_object_code(obj, op["declaration"], op["implementation"]):
new_stats["updated"] += 1
new_stats["created"] += 1
full_content = format_st_content(op["declaration"], op["implementation"])
objects_meta[op["rel_path"]] = {