forked from ArthurkaX/cds-text-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProject_export.py
More file actions
794 lines (647 loc) · 31.6 KB
/
Project_export.py
File metadata and controls
794 lines (647 loc) · 31.6 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
# -*- coding: utf-8 -*-
"""
Project_export.py - Export CODESYS project to git-friendly folder structure
Exports all textual objects (POUs, GVLs, DUTs) to .st files organized in
folders matching the CODESYS project hierarchy. Creates a single _metadata.json
file containing GUID mappings, sync settings, and project info for reliable import.
Features:
- Project identity check: Warns if exporting to a directory with different project
- Initializes autosync and sync_timeout fields for Project_AutoSync.py
- Preserves consistent field order in metadata JSON
Usage: Run from CODESYS IDE after setting sync directory with Project_directory.py
"""
import os
import codecs
import json
import time
import shutil
from codesys_constants import TYPE_GUIDS, EXPORTABLE_TYPES, IMPL_MARKER, XML_TYPES
from codesys_utils import (
safe_str, clean_filename, load_base_dir,
save_metadata, calculate_hash, format_st_content,
log_info, log_warning, log_error, MetadataLock,
save_libraries, extract_libraries_from_project,
init_logging, backup_project_binary, format_property_content
)
# Ensure global objects are available if imported
try:
_ = projects.primary
except NameError:
# If imported, projects might not be in local scope but available in sys.modules['__main__']?
# Or we can import them from script engine?
# Actually, in CODESYS, 'projects' is a global variable.
# To be safe during import:
pass
# Shared constants and utilities imported from modules
def get_object_path(obj, stop_at_application=True):
"""
Build the path from object to Application root.
Returns list of folder names from Application (exclusive) to object (exclusive).
"""
path_parts = []
current = obj
while current is not None:
try:
if not hasattr(current, "parent") or current.parent is None:
break
parent = current.parent
# Validate parent has required attributes
if not hasattr(parent, "type") or not hasattr(parent, "get_name"):
break
parent_type = safe_str(parent.type)
# Stop at Application level
if stop_at_application and parent_type == TYPE_GUIDS["application"]:
break
# Stop at Plc Logic or Device level
if parent_type in [TYPE_GUIDS["plc_logic"], TYPE_GUIDS["device"]]:
break
# Add parent name to path if it's a folder or other container
parent_name = clean_filename(parent.get_name())
path_parts.insert(0, parent_name)
current = parent
except Exception as e:
log_error("Error building path: " + safe_str(e))
break
return path_parts
def get_parent_pou_name(obj):
"""Get parent POU/Interface name for nested objects (actions, methods, properties)"""
try:
if hasattr(obj, "parent") and obj.parent:
# Validate parent has required attributes
if not hasattr(obj.parent, "type") or not hasattr(obj.parent, "get_name"):
return None
parent_type = safe_str(obj.parent.type)
if parent_type in [TYPE_GUIDS["pou"], TYPE_GUIDS["itf"]]:
return obj.parent.get_name()
except:
pass
return None
def export_object_content(obj):
"""
Extract declaration and implementation text from object.
Returns tuple (declaration, implementation) or (None, None) if no content.
"""
declaration = None
implementation = None
try:
if hasattr(obj, "has_textual_declaration") and obj.has_textual_declaration:
declaration = obj.textual_declaration.text
except Exception as e:
print("Warning: Could not read declaration for " + safe_str(obj.get_name()) + ": " + safe_str(e))
try:
if hasattr(obj, "has_textual_implementation") and obj.has_textual_implementation:
implementation = obj.textual_implementation.text
except Exception as e:
print("Warning: Could not read implementation for " + safe_str(obj.get_name()) + ": " + safe_str(e))
return declaration, implementation
def export_native_xml(obj, file_path):
"""Export object in native CODESYS format (XML)"""
# Delete existing file to avoid CODESYS overwrite prompts
if os.path.exists(file_path):
try:
os.remove(file_path)
except Exception as e:
print("Warning: Could not delete existing XML " + file_path)
try:
# Visualizations and other non-IEC objects must be exported using native format
projects.primary.export_native([obj], file_path, recursive=True)
return True
except Exception as e:
print("Error exporting Native XML for " + safe_str(obj.get_name()) + ": " + safe_str(e))
return False
def cleanup_orphaned_files(export_dir, current_objects, silent=False):
"""
Find and optionally delete files in export_dir that are not in current_objects.
"""
orphaned_items = []
# We'll collect everything first to show a preview
for root, dirs, files in os.walk(export_dir):
# Calculate relative path from export_dir
rel_root = os.path.relpath(root, export_dir)
if rel_root == ".":
rel_root = ""
# Check files
for f in files:
# Skip reserved files and folders
if f in ["_metadata.json", "_config.json", "_metadata.csv", "BASE_DIR", "sync_debug.log", ".project", ".gitattributes", ".gitignore"] or f.startswith("."):
continue
# Skip project folder if it exists (for Git LFS)
if rel_root.startswith("project") or rel_root == "project":
continue
# Only consider our export types to be safe
if not (f.endswith(".st") or f.endswith(".xml")):
continue
rel_path = os.path.join(rel_root, f).replace("\\", "/")
if rel_path not in current_objects:
orphaned_items.append(rel_path)
if not orphaned_items:
return True
# 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 Mode: " + str(len(orphaned_items)) + " orphans ignored (set cds-sync-auto-delete-orphans=True to delete).")
return True # Ignore
else:
# Prompt user
message = "The following files exist in the export directory but are NOT in the CODESYS project (orphans):\n\n"
# Show first 15 files as preview
for item in orphaned_items[:15]:
message += "- " + item + "\n"
if len(orphaned_items) > 15:
message += "... and " + str(len(orphaned_items) - 15) + " more.\n"
message += "\nWould you like to delete these orphaned files?"
# buttons: Delete, Ignore, Cancel
try:
result = system.ui.choose(message, ("Delete Orphans", "Ignore", "Cancel Export"))
except:
# Fallback for environments where choose is not available or fails
print("UI Choose not available, skipping cleanup.")
return True
if result[0] == 0: # Delete
print("Cleaning up orphaned files...")
for rel_path in orphaned_items:
full_path = os.path.join(export_dir, rel_path.replace("/", os.sep))
try:
if os.path.exists(full_path):
os.remove(full_path)
print("Deleted: " + rel_path)
except Exception as e:
print("Error deleting " + rel_path + ": " + safe_str(e))
# Now clean up empty directories
# Use topdown=False to delete subdirectories before parents
for root, dirs, files in os.walk(export_dir, topdown=False):
rel_root = os.path.relpath(root, export_dir)
if rel_root == "." or not rel_root:
continue
rel_path = rel_root.replace("\\", "/")
# Check if this folder or any of its children should exist
folder_needed = False
for obj_path in current_objects:
if obj_path.startswith(rel_path + "/"):
folder_needed = True
break
if not folder_needed and rel_path not in current_objects:
# If directory is empty, delete it
try:
if not os.listdir(root):
os.rmdir(root)
print("Deleted empty folder: " + rel_path)
except:
pass
return True
elif result[0] == 1: # Ignore
print("Orphaned files ignored.")
return True
else: # Cancel
print("Export cancelled during cleanup.")
return False
def ensure_git_configs(export_dir):
"""Create .gitignore and .gitattributes if they don't exist."""
gitignore_path = os.path.join(export_dir, ".gitignore")
gitattributes_path = os.path.join(export_dir, ".gitattributes")
# Gitignore handling
if not os.path.exists(gitignore_path):
content = [
"# CODESYS Sync local files",
"_config.json",
"_metadata.csv",
"*.log",
"*.tmp",
"*.bak",
"",
"# CODESYS temporary and build files",
"*.~u",
"*.precompilecache",
"*.opt",
"*.bootinfo",
"*.bootinfo_guids",
"*.compileinfo",
"*.simulation.bootinfo",
"*.simulation.bootinfo_guids",
"*.simulation.compileinfo",
""
]
try:
with codecs.open(gitignore_path, "w", "utf-8") as f:
f.write("\n".join(content))
print("Created: .gitignore")
except: pass
else:
# File exists, check if sync_debug.log is ignored
try:
with codecs.open(gitignore_path, "r", "utf-8") as f:
lines = f.readlines()
if not any("*.log" in line for line in lines):
with codecs.open(gitignore_path, "a", "utf-8") as f:
f.write("\n*.log\n")
print("Updated .gitignore with *.log")
except: pass
if not os.path.exists(gitattributes_path):
content = [
"# Git LFS configuration for CODESYS project binary",
"*.project filter=lfs diff=lfs merge=lfs -text",
"",
"# Prevent line ending conversion for CODESYS Structured Text files",
"*.st -text",
"",
"# GitHub linguist language detection",
"*.st linguist-language=Pascal",
""
]
try:
with codecs.open(gitattributes_path, "w", "utf-8") as f:
f.write("\n".join(content))
print("Created: .gitattributes")
except: pass
def export_project(export_dir, projects_obj=None, silent=False):
"""Export all project objects to folder structure with metadata"""
# Resolving projects object (dependency injection or global fallback)
if projects_obj is None:
# Explicitly check globals to avoid UnboundLocalError
if "projects" in globals():
projects_obj = globals()["projects"]
if projects_obj is None:
if not silent:
system.ui.error("Script Error: 'projects' object not found. Please pass it explicitly.")
else:
print("Error: 'projects' object not found")
return
if not projects_obj.primary:
if not silent:
system.ui.error("No project open!")
else:
print("Error: No project open")
return
# Create export directory
if not os.path.exists(export_dir):
os.makedirs(export_dir)
# Ensure Git config files exist
ensure_git_configs(export_dir)
# Create project binary backup (moved down)
print("=== Starting Project Export ===")
start_time = time.time()
print("Export directory: " + export_dir)
# Metadata structure
current_project_name = safe_str(projects.primary)
metadata = {
"project_name": current_project_name,
"export_timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"autosync": "STOPPED",
"sync_timeout": 10000,
"export_xml": False,
"objects": {}
}
try:
if hasattr(projects.primary, "path"):
metadata["project_path"] = safe_str(projects.primary.path)
except:
pass
# Read settings from project properties (Source of Truth)
from codesys_utils import get_project_prop
metadata["export_xml"] = get_project_prop("cds-sync-export-xml", False)
metadata["sync_timeout"] = get_project_prop("cds-sync-timeout", 10000)
metadata["autosync"] = get_project_prop("cds-sync-autosync", "STOPPED")
backup_binary = get_project_prop("cds-sync-backup-binary", False)
# Store settings in metadata for reference
metadata["settings"] = {
"export_xml": metadata["export_xml"],
"backup_binary": backup_binary
}
# Check if metadata already exists with different project
metadata_path = os.path.join(export_dir, "_metadata.json")
if os.path.exists(metadata_path):
try:
with codecs.open(metadata_path, "r", "utf-8") as f:
existing_metadata = json.load(f)
# Note: We now prioritize project properties over file metadata
# Only preserve settings if they're not in project properties
existing_project = existing_metadata.get("project_name", "")
if existing_project and existing_project != current_project_name:
if silent:
print("Warning: Exporting to folder owned by different project: " + existing_project)
else:
message = "WARNING: This directory contains exports from a different project!\n\n"
message += "Current project: " + current_project_name + "\n"
message += "Existing exports: " + existing_project + "\n\n"
message += "Exporting will OVERWRITE the existing files.\n\n"
message += "Are you sure you want to proceed?"
result = system.ui.choose(message, ("Yes, Overwrite", "No, Cancel"))
if result[0] != 0:
print("Export cancelled by user - project mismatch")
return
except:
# If we can't read existing metadata, continue with export
pass
# Execute binary backup if enabled
if backup_binary:
print("Binary backup enabled.")
backup_project_binary(export_dir, projects_obj)
else:
print("Binary backup disabled (skipping .project copy).")
# Get all objects recursively
all_objects = projects_obj.primary.get_children(recursive=True)
print("Found " + str(len(all_objects)) + " total objects")
exported_count = 0
skipped_count = 0
# Create subdirectories
src_dir = os.path.join(export_dir, "src")
xml_dir = os.path.join(export_dir, "xml")
config_dir = os.path.join(export_dir, "config")
for d in [src_dir, xml_dir, config_dir]:
if not os.path.exists(d):
os.makedirs(d)
# First pass: collect all property accessors by their parent property
property_accessors = {} # property_guid -> {'get': obj, 'set': obj}
for obj in all_objects:
try:
if not hasattr(obj, 'type') or not hasattr(obj, 'get_name'):
continue
obj_type = safe_str(obj.type)
# Collect property accessors (Get/Set)
if obj_type == TYPE_GUIDS["property_accessor"]:
obj_name = obj.get_name()
print(" DEBUG: Found property accessor: " + obj_name)
# Get parent property
if hasattr(obj, "parent") and obj.parent:
parent_guid = safe_str(obj.parent.guid)
parent_type = safe_str(obj.parent.type)
parent_name = safe_str(obj.parent.get_name()) if hasattr(obj.parent, 'get_name') else "Unknown"
print(" Parent: " + parent_name + " (type: " + parent_type + ")")
# Only process if parent is a property
if parent_type == TYPE_GUIDS["property"]:
if parent_guid not in property_accessors:
property_accessors[parent_guid] = {'get': None, 'set': None, 'parent_obj': obj.parent}
# Determine if this is Get or Set based on name
if obj_name.lower() == "get":
property_accessors[parent_guid]['get'] = obj
print(" -> Registered as GET for property " + parent_name)
elif obj_name.lower() == "set":
property_accessors[parent_guid]['set'] = obj
print(" -> Registered as SET for property " + parent_name)
else:
print(" WARNING: Parent is not a property! Type: " + parent_type)
except Exception as e:
print(" ERROR in first pass: " + safe_str(e))
continue
print("Found " + str(len(property_accessors)) + " properties with accessors (first pass)")
# Alternative collection: Check each property's children directly
# This is needed because get_children(recursive=True) might not include property accessors
for obj in all_objects:
try:
if not hasattr(obj, 'type') or not hasattr(obj, 'get_name'):
continue
obj_type = safe_str(obj.type)
# If this is a property, check its children for accessors
if obj_type == TYPE_GUIDS["property"]:
obj_guid = safe_str(obj.guid)
obj_name = safe_str(obj.get_name())
# Get property's children
try:
prop_children = obj.get_children()
if prop_children:
print(" DEBUG: Property " + obj_name + " has " + str(len(prop_children)) + " children")
for child in prop_children:
try:
child_type = safe_str(child.type)
child_name = safe_str(child.get_name())
if child_type == TYPE_GUIDS["property_accessor"]:
print(" Found accessor: " + child_name)
# Initialize if needed
if obj_guid not in property_accessors:
property_accessors[obj_guid] = {'get': None, 'set': None, 'parent_obj': obj}
# Register accessor
if child_name.lower() == "get":
property_accessors[obj_guid]['get'] = child
print(" -> Registered as GET")
elif child_name.lower() == "set":
property_accessors[obj_guid]['set'] = child
print(" -> Registered as SET")
except:
pass
except:
pass
except:
continue
print("Found " + str(len(property_accessors)) + " properties with accessors (after direct check)")
# Second pass: export all objects
for obj in all_objects:
try:
# Validate that object has required methods
if not hasattr(obj, 'type') or not hasattr(obj, 'get_name') or not hasattr(obj, 'guid'):
continue
obj_type = safe_str(obj.type)
obj_name = obj.get_name()
obj_guid = safe_str(obj.guid)
# Skip property accessors - they will be handled with their parent property
if obj_type == TYPE_GUIDS["property_accessor"]:
continue
# Special handling for folders - create directory and convert
if obj_type == TYPE_GUIDS["folder"]:
path_parts = get_object_path(obj)
clean_name = clean_filename(obj_name)
# Add folder itself to path
path_parts.append(clean_name)
# Create folder in src directory
target_dir = os.path.join(src_dir, *path_parts) if path_parts else src_dir
if not os.path.exists(target_dir):
os.makedirs(target_dir)
print("Created folder: src/" + "/".join(path_parts))
# Add to metadata (with src/ prefix)
rel_path = "src/" + "/".join(path_parts)
metadata["objects"][rel_path] = {
"guid": obj_guid,
"type": obj_type,
"name": obj_name,
"parent": safe_str(obj.parent.get_name()) if hasattr(obj, "parent") and obj.parent and hasattr(obj.parent, "get_name") else None,
"content_hash": ""
}
exported_count += 1
continue
# Skip non-exportable types
if obj_type not in EXPORTABLE_TYPES:
continue
# Check if object is XML type
is_xml = obj_type in XML_TYPES
# Mandatory Configuration Exports
is_config = False
if obj_type == TYPE_GUIDS["task_config"]:
is_config = True
is_xml = True # Force XML for config
# Skip XML objects if disabled in metadata (unless it's mandatory config)
if is_xml and not metadata.get("export_xml", False) and not is_config:
continue
# Check if object has any textual content
has_content = False
try:
if hasattr(obj, "has_textual_declaration") and obj.has_textual_declaration:
has_content = True
if hasattr(obj, "has_textual_implementation") and obj.has_textual_implementation:
has_content = True
except:
pass
# Special handling for properties - they might not have content but have accessors
is_property = obj_type == TYPE_GUIDS["property"]
if is_property and obj_guid in property_accessors:
has_content = True # Force export if it has accessors
# Allow export if it has content OR is an XML type
if not has_content and not is_xml:
skipped_count += 1
continue
# Build file path
path_parts = get_object_path(obj)
clean_name = clean_filename(obj_name)
# Handle nested objects (actions, methods, properties)
parent_pou = get_parent_pou_name(obj)
if parent_pou and obj_type in [TYPE_GUIDS["action"], TYPE_GUIDS["method"], TYPE_GUIDS["property"]]:
# Nested objects: ParentPOU.MethodName.st or ParentPOU.PropertyName.st
file_name = clean_filename(parent_pou) + "." + clean_name + ".st"
# Remove parent POU from path since it's in filename
clean_parent_pou = clean_filename(parent_pou)
if path_parts and path_parts[-1] == clean_parent_pou:
path_parts = path_parts[:-1]
elif is_xml:
file_name = clean_name + ".xml"
else:
file_name = clean_name + ".st"
# Determine Target Directory and Prefix
if is_config:
base_dir_obj = config_dir
prefix = "config"
elif is_xml:
base_dir_obj = xml_dir
prefix = "xml"
else:
base_dir_obj = src_dir
prefix = "src"
# Create target directory
target_dir = os.path.join(base_dir_obj, *path_parts) if path_parts else base_dir_obj
if not os.path.exists(target_dir):
os.makedirs(target_dir)
# Build full file path
file_path = os.path.join(target_dir, file_name)
# Initialize content_hash
content_hash = ""
if is_xml:
if not export_native_xml(obj, file_path):
skipped_count += 1
continue
# Verify that file was actually created
if not os.path.exists(file_path):
print("Warning: XML export claimed success but file not found: " + file_name)
skipped_count += 1
continue
elif is_property and obj_guid in property_accessors:
# Export property with combined GET/SET accessors
prop_data = property_accessors[obj_guid]
# Get property declaration
declaration, _ = export_object_content(obj)
# Get GET accessor content (combine declaration and implementation)
get_impl = None
if prop_data['get']:
get_decl, get_impl_raw = export_object_content(prop_data['get'])
# Combine declaration (VAR section) and implementation (code) like methods/actions
get_impl = format_st_content(get_decl, get_impl_raw)
# Get SET accessor content (combine declaration and implementation)
set_impl = None
if prop_data['set']:
set_decl, set_impl_raw = export_object_content(prop_data['set'])
# Combine declaration (VAR section) and implementation (code) like methods/actions
set_impl = format_st_content(set_decl, set_impl_raw)
# Format combined content
content = format_property_content(declaration, get_impl, set_impl)
if not content.strip():
skipped_count += 1
continue
# Normalize line endings to LF for cross-platform consistency
content_normalized = content.replace('\r\n', '\n').replace('\r', '\n')
with open(file_path, "wb") as f:
f.write(content_normalized.encode('utf-8'))
# Calculate hash for metadata
content_hash = calculate_hash(content)
else:
# Textual export (normal POUs, methods, actions, etc.)
declaration, implementation = export_object_content(obj)
content = format_st_content(declaration, implementation)
if not content.strip():
skipped_count += 1
continue
# Normalize line endings to LF for cross-platform consistency
content_normalized = content.replace('\r\n', '\n').replace('\r', '\n')
with open(file_path, "wb") as f:
f.write(content_normalized.encode('utf-8'))
# Calculate hash for metadata
content_hash = calculate_hash(content)
# Build relative path for metadata
if path_parts:
parts_for_join = [prefix] + path_parts + [file_name]
rel_path = "/".join(parts_for_join)
else:
rel_path = prefix + "/" + file_name
# rel_path is already forward slashes
# Store metadata
metadata["objects"][rel_path] = {
"guid": obj_guid,
"type": obj_type,
"name": obj_name,
"parent": safe_str(obj.parent.get_name()) if hasattr(obj, "parent") and obj.parent and hasattr(obj.parent, "get_name") else None,
"content_hash": content_hash,
"last_modified": safe_str(os.path.getmtime(file_path))
}
print("Exported: " + rel_path)
exported_count += 1
except Exception as e:
log_error("Error exporting " + safe_str(obj) + ": " + safe_str(e))
# Cleanup orphaned files (files on disk not in current export)
if not cleanup_orphaned_files(export_dir, metadata["objects"], silent=silent):
return
# Debug: Count methods in metadata before saving
method_count = sum(1 for obj in metadata["objects"].values() if obj.get("type") == TYPE_GUIDS["method"])
print("DEBUG: Before saving - Total objects: " + str(len(metadata["objects"])) + ", Methods: " + str(method_count))
# Write metadata file with consistent field order (60s timeout for large projects)
with MetadataLock(export_dir, timeout=60):
if save_metadata(export_dir, metadata):
print("Created: _config.json and _metadata.csv")
else:
print("Error writing metadata")
# Add library export
libraries = extract_libraries_from_project(projects.primary)
if libraries:
if save_libraries(export_dir, libraries):
print("Created: _libraries.csv (" + str(len(libraries)) + " libraries)")
else:
print("Error writing _libraries.csv")
print("=== Export Complete ===")
elapsed_time = time.time() - start_time
print("Exported: " + str(exported_count) + " files")
print("Skipped: " + str(skipped_count) + " objects (no textual content)")
print("Time elapsed: {:.2f} seconds".format(elapsed_time))
print("Completed at: " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
log_info("Export complete! Exported: " + str(exported_count) + " files.")
# Check for silent mode (Non-Blocking UI)
silent_mode = get_project_prop("cds-sync-silent-mode", False)
if silent_mode:
try:
from codesys_ui import show_toast
show_toast("Export Complete", "Exported: " + str(exported_count) + " files\nTime: {:.2f}s".format(elapsed_time))
except:
# Fallback if UI module missing
print("Export complete (Silent mode active, but UI module failed)")
else:
system.ui.info("Export complete!\n\nExported: " + str(exported_count) + " files\nLocation: " + export_dir + "\nTime elapsed: {:.2f} seconds".format(elapsed_time))
def main():
base_dir, error = load_base_dir()
if error:
system.ui.warning(error)
return
# Check if we are being run in silent mode (e.g. from Daemon)
is_silent = globals().get("SILENT", False)
init_logging(base_dir)
export_project(base_dir, silent=is_silent)
if __name__ == "__main__":
main()