-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathOgresync.py
More file actions
2714 lines (2345 loc) · 147 KB
/
Copy pathOgresync.py
File metadata and controls
2714 lines (2345 loc) · 147 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
import os
import subprocess
import sys
import shlex
import threading
import time
import psutil
import shutil
import random
import tkinter as tk
import platform
import datetime
from tkinter import ttk, scrolledtext
from typing import Optional
import webbrowser
import pyperclip
import requests
import ui_elements # Import the new UI module
try:
import Stage1_conflict_resolution as conflict_resolution # Import the enhanced conflict resolution module
CONFLICT_RESOLUTION_AVAILABLE = True
except ImportError:
conflict_resolution = None
CONFLICT_RESOLUTION_AVAILABLE = False
import setup_wizard # Import the new setup wizard module
# Import offline sync manager
try:
import offline_sync_manager
# Check if the module actually has the required class
if hasattr(offline_sync_manager, 'OfflineSyncManager'):
OFFLINE_SYNC_AVAILABLE = True
else:
OFFLINE_SYNC_AVAILABLE = False
offline_sync_manager = None
except ImportError:
offline_sync_manager = None
OFFLINE_SYNC_AVAILABLE = False
# ------------------------------------------------
# CONFIG / GLOBALS
# ------------------------------------------------
def get_config_directory():
"""Get the appropriate config directory for the current OS"""
import sys
from pathlib import Path
# ALWAYS use OS-specific directories for proper packaging behavior
# This ensures consistent behavior between development and packaged versions
if sys.platform == "win32":
config_dir = os.path.join(os.environ['APPDATA'], 'Ogresync')
elif sys.platform == "darwin":
config_dir = os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', 'Ogresync')
else: # Linux
config_dir = os.path.join(os.path.expanduser('~'), '.config', 'ogresync')
try:
os.makedirs(config_dir, exist_ok=True)
print(f"DEBUG: Config directory: {config_dir}")
except Exception as e:
print(f"WARNING: Could not create config directory {config_dir}: {e}")
# Fallback to script directory only if OS-specific fails
config_dir = os.path.dirname(os.path.abspath(__file__))
print(f"DEBUG: Using fallback config directory: {config_dir}")
return config_dir
def get_config_file_path():
"""Get the full path to the config file"""
return os.path.join(get_config_directory(), "config.txt")
# Config file path will be determined dynamically
CONFIG_FILE = None # Will be set by get_config_file_path()
config_data = {
"VAULT_PATH": "",
"OBSIDIAN_PATH": "",
"GITHUB_REMOTE_URL": "",
"SETUP_DONE": "0"
}
SSH_KEY_PATH = os.path.expanduser(os.path.join("~", ".ssh", "id_rsa.pub"))
root: Optional[tk.Tk] = None # Will be created by ui_elements.create_main_window()
log_text: Optional[scrolledtext.ScrolledText] = None # Will be created by ui_elements.create_main_window()
progress_bar: Optional[ttk.Progressbar] = None # Will be created by ui_elements.create_main_window()
# ------------------------------------------------
# CONFIG HANDLING
# ------------------------------------------------
def load_config():
"""
Reads config.txt into config_data dict.
Expected lines like: KEY=VALUE
Also handles migration from old script-directory config to new OS-specific location.
"""
config_loaded = False
# Get current config file path
config_file = get_config_file_path()
# Check for config in new location first
if os.path.exists(config_file):
print(f"DEBUG: Loading config from {config_file}")
try:
with open(config_file, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if "=" in line:
key, val = line.split("=", 1)
config_data[key.strip()] = val.strip()
config_loaded = True
print("DEBUG: Config loaded successfully from new location")
except Exception as e:
print(f"ERROR: Failed to load config from {config_file}: {e}")
# If no config found in new location, check for old location (migration)
if not config_loaded:
old_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.txt")
if os.path.exists(old_config_file):
print(f"DEBUG: Found old config at {old_config_file}, migrating...")
try:
with open(old_config_file, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if "=" in line:
key, val = line.split("=", 1)
config_data[key.strip()] = val.strip()
# Save to new location
save_config()
# Try to remove old config file
try:
os.remove(old_config_file)
print("DEBUG: Successfully migrated config and removed old file")
except Exception as remove_err:
print(f"WARNING: Could not remove old config file: {remove_err}")
config_loaded = True
except Exception as e:
print(f"ERROR: Failed to migrate config from {old_config_file}: {e}")
if config_loaded:
print("DEBUG: Final config loaded:")
for k, v in config_data.items():
print(f"DEBUG: Config - {k}: {v}")
else:
print("DEBUG: No config file found, using defaults")
def save_config():
"""
Writes config_data dict to config.txt in the appropriate OS-specific directory.
"""
config_file = get_config_file_path()
print(f"DEBUG: Saving config to {config_file}")
for k, v in config_data.items():
print(f"DEBUG: Saving config - {k}: {v}")
try:
# Ensure directory exists
config_dir = os.path.dirname(config_file)
os.makedirs(config_dir, exist_ok=True)
with open(config_file, "w", encoding="utf-8") as f:
for k, v in config_data.items():
f.write(f"{k}={v}\n")
print(f"DEBUG: Config saved successfully to {config_file}")
except Exception as e:
print(f"ERROR: Failed to save config: {e}")
# Try fallback location
try:
fallback_config = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.txt")
print(f"DEBUG: Attempting fallback save to {fallback_config}")
with open(fallback_config, "w", encoding="utf-8") as f:
for k, v in config_data.items():
f.write(f"{k}={v}\n")
print("DEBUG: Fallback config save successful")
except Exception as fallback_err:
print(f"ERROR: Fallback config save also failed: {fallback_err}")
# Import GitHub setup functions from separate module
import github_setup
# ------------------------------------------------
# HELPER FUNCTIONS
# ------------------------------------------------
def run_command(command, cwd=None, timeout=None):
"""
Runs a shell command safely across platforms, returning (stdout, stderr, return_code).
Safe to call in a background thread.
Args:
command: Command string to execute
cwd: Working directory for the command
timeout: Timeout in seconds
Returns:
Tuple of (stdout, stderr, return_code)
"""
try:
# For better cross-platform compatibility, try to avoid shell=True when possible
# but still support it for complex commands and commit messages
if isinstance(command, str):
# Check if this is a simple git command that can be safely split
# CRITICAL: Exclude git commit commands with -m messages as they contain quotes
is_simple_git = (command.strip().startswith('git ') and
' && ' not in command and
' || ' not in command and
' | ' not in command and
'git commit -m' not in command) # Exclude commit messages
if is_simple_git:
try:
# Use shlex for proper argument splitting only for simple commands
if platform.system() == "Windows":
# On Windows, use posix=False for proper quote handling
command_parts = shlex.split(command, posix=False)
else:
# On Unix-like systems, use standard splitting
command_parts = shlex.split(command)
result = subprocess.run(
command_parts,
cwd=cwd,
capture_output=True,
text=True,
timeout=timeout,
check=False
)
return result.stdout.strip(), result.stderr.strip(), result.returncode
except (ValueError, OSError):
# Fall back to shell=True if splitting fails
pass
# Use shell=True for:
# - Complex commands with pipes, redirects, etc.
# - Git commit commands with messages (to preserve quotes)
# - When argument splitting fails
# - Non-string commands (already arrays)
result = subprocess.run(
command,
cwd=cwd,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
check=False
)
return result.stdout.strip(), result.stderr.strip(), result.returncode
except subprocess.TimeoutExpired as e:
return "", str(e), 1
except Exception as e:
return "", str(e), 1
def ensure_github_known_host():
"""
Adds GitHub's RSA key to known_hosts if not already present.
This prevents the 'Are you sure you want to continue connecting?' prompt.
Best Practice Note:
- We're automatically trusting 'github.com' here.
- In a more security-conscious workflow, you'd verify the key's fingerprint
against GitHub's official documentation before appending.
"""
# Check if GitHub is already in known_hosts
known_hosts_path = os.path.expanduser("~/.ssh/known_hosts")
if os.path.exists(known_hosts_path):
with open(known_hosts_path, "r", encoding="utf-8") as f:
if "github.com" in f.read():
# Already have GitHub host key, nothing to do
return
safe_update_log("Adding GitHub to known hosts (ssh-keyscan)...", 32)
# Fetch GitHub's RSA key and append to known_hosts
scan_out, scan_err, rc = run_command("ssh-keyscan -t rsa github.com")
if rc == 0 and scan_out:
# Ensure .ssh folder exists
os.makedirs(os.path.expanduser("~/.ssh"), exist_ok=True)
with open(known_hosts_path, "a", encoding="utf-8") as f:
f.write(scan_out + "\n")
else:
# If this fails, we won't block the user; but we warn them.
safe_update_log("Warning: Could not fetch GitHub host key automatically.", 32)
def is_obsidian_running():
"""
Checks if Obsidian is currently running using a more robust approach.
Compares against known process names and the configured obsidian_path.
"""
# Attempt to load config_data if not already loaded (e.g., if called in a standalone context)
if not config_data.get("OBSIDIAN_PATH"):
load_config() # Ensure config_data is populated
obsidian_executable_path = config_data.get("OBSIDIAN_PATH")
# Normalize obsidian_executable_path for comparison
if obsidian_executable_path:
obsidian_executable_path = os.path.normpath(obsidian_executable_path).lower()
process_names_to_check = []
if sys.platform.startswith("win"):
process_names_to_check = ["obsidian.exe"]
elif sys.platform.startswith("linux"):
# Common names for native, Snap, or simple AppImage launches
process_names_to_check = ["obsidian"]
# Add Flatpak common application ID as a potential process name
# psutil often shows the application ID for Flatpak apps
process_names_to_check.append("md.obsidian.obsidian")
elif sys.platform.startswith("darwin"):
process_names_to_check = ["Obsidian"] # Main bundle executable name
for proc in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
try:
proc_info_name = proc.info.get("name", "").lower()
proc_info_exe = os.path.normpath(proc.info.get("exe", "") or "").lower()
proc_info_cmdline = [str(arg).lower() for arg in proc.info.get("cmdline", []) or []]
# 1. Check against known process names
for name_to_check in process_names_to_check:
if name_to_check.lower() == proc_info_name:
return True
# 2. Check if the process executable path matches the configured obsidian_path
if obsidian_executable_path and proc_info_exe == obsidian_executable_path:
return True
# 3. For Linux (especially Flatpak/Snap/AppImage) and potentially others,
# check if the configured obsidian_path (which could be a command or part of it)
# is in the process's command line arguments.
if obsidian_executable_path:
if any(obsidian_executable_path in cmd_arg for cmd_arg in proc_info_cmdline):
return True
# Sometimes the exe is just 'flatpak' and the app id is in cmdline
if proc_info_name == "flatpak" and any("md.obsidian.obsidian" in cmd_arg for cmd_arg in proc_info_cmdline):
return True
# 4. Special case for Flatpak: check for bwrap process with obsidian in cmdline
if proc_info_name == "bwrap" and any("obsidian" in cmd_arg for cmd_arg in proc_info_cmdline):
return True
# 5. Check for any process with obsidian in the command line (broader match)
if any("obsidian" in cmd_arg for cmd_arg in proc_info_cmdline):
# Additional validation to avoid false positives
if "obsidian.sh" in " ".join(proc_info_cmdline) or "md.obsidian" in " ".join(proc_info_cmdline):
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
return False
# Global flag to prevent UI updates during transition
_ui_updating_enabled = True
_ui_lock = threading.Lock()
_pending_after_ids = set() # Track pending after() calls
_ui_cleanup_in_progress = False # Flag to indicate cleanup is happening
def disable_ui_updates():
"""Disable UI updates during transition and cancel pending operations"""
global _ui_updating_enabled, _pending_after_ids, _ui_cleanup_in_progress
with _ui_lock:
_ui_updating_enabled = False
_ui_cleanup_in_progress = True
# Cancel all tracked pending after() calls
if root is not None:
try:
for after_id in _pending_after_ids.copy():
try:
root.after_cancel(after_id)
except:
pass
_pending_after_ids.clear()
except:
pass
def enable_ui_updates():
"""Re-enable UI updates after transition"""
global _ui_updating_enabled, _pending_after_ids, _ui_cleanup_in_progress
with _ui_lock:
_ui_updating_enabled = True
_ui_cleanup_in_progress = False
# Clear any stale after IDs when re-enabling
_pending_after_ids.clear()
def safe_update_log(message, progress=None):
# Always print to console for debugging
print(f"LOG: {message}")
# Check if UI updates are enabled and cleanup is not in progress
with _ui_lock:
if not _ui_updating_enabled or _ui_cleanup_in_progress:
return
# Check if we have valid UI components
if not (log_text and progress_bar and root):
return
def _update():
try:
# ENHANCED: Multiple safety checks during cleanup periods
with _ui_lock:
if not _ui_updating_enabled or _ui_cleanup_in_progress:
return
if not (log_text and root):
return
# ENHANCED: More comprehensive widget existence checks
try:
# Verify root exists and is valid
if not root.winfo_exists():
return
# Verify we're not in the middle of destruction
root.winfo_name() # This will throw if root is being destroyed
except (tk.TclError, AttributeError, RuntimeError):
# Root is destroyed, being destroyed, or invalid
return
# Update log text with enhanced error handling
if log_text is not None:
try:
# Verify log_text widget exists and is valid
log_text.winfo_exists()
log_text.winfo_name() # Additional validation
log_text.config(state='normal')
log_text.insert(tk.END, message + "\n")
log_text.config(state='disabled')
log_text.yview_moveto(1)
except (tk.TclError, AttributeError, RuntimeError):
# Widget destroyed or invalid - stop trying to update
return
# Update progress bar with enhanced error handling
if progress is not None and progress_bar is not None:
try:
# Verify progress_bar widget exists and is valid
progress_bar.winfo_exists()
progress_bar.winfo_name() # Additional validation
progress_bar["value"] = progress
except (tk.TclError, AttributeError, RuntimeError):
# Progress bar destroyed or invalid - continue without it
pass
# ENHANCED: Ultra-conservative UI update approach
try:
# Only update if we can confirm root is still completely valid
if root.winfo_exists():
root.winfo_name() # Final validation
root.update_idletasks()
# Skip root.update() to prevent recursive event processing during cleanup
except (tk.TclError, AttributeError, RuntimeError):
# Root destroyed or being destroyed - stop immediately
return
except Exception as e:
# Catch any other unexpected errors and ignore them during cleanup
print(f"DEBUG: safe_update_log error during cleanup (ignored): {e}")
try:
# ENHANCED: Ultra-safe thread detection and scheduling
current_thread = threading.current_thread()
is_main_thread = current_thread == threading.main_thread()
if is_main_thread:
# We're in main thread, update immediately with extensive safety checks
try:
if root is not None:
# Multiple validation layers
if root.winfo_exists():
root.winfo_name() # Ensure not being destroyed
_update()
except (tk.TclError, AttributeError, RuntimeError):
# Root destroyed or invalid - skip update completely
return
else:
# We're in background thread, be extremely careful about scheduling
try:
# Extensive safety checks before scheduling
if root is not None:
# Check if root still exists and is not being destroyed
if root.winfo_exists():
root.winfo_name() # Validate not in destruction
# Check cleanup status one more time
with _ui_lock:
if _ui_cleanup_in_progress:
return # Don't schedule during cleanup
# Schedule with tracking for cleanup
after_id = root.after_idle(_update)
with _ui_lock:
if not _ui_cleanup_in_progress: # Double check
_pending_after_ids.add(after_id)
else:
# Cleanup started, cancel immediately
try:
root.after_cancel(after_id)
except:
pass
except (tk.TclError, AttributeError, RuntimeError):
# Root destroyed, invalid, or being destroyed - silently ignore
return
except Exception as e:
# Final safety net - ignore all errors during cleanup periods
print(f"DEBUG: safe_update_log scheduling error during cleanup (ignored): {e}")
def is_network_available():
"""
Checks if the network is available by trying to connect to github.com over HTTPS.
Returns True if successful, otherwise False.
"""
import socket
try:
socket.create_connection(("github.com", 443), timeout=5)
return True
except Exception:
return False
def get_unpushed_commits(vault_path):
"""
Fetches the latest from origin and returns a string listing commits in HEAD that are not in origin/main.
"""
# Update remote tracking info first.
run_command("git fetch origin", cwd=vault_path)
unpushed, _, _ = run_command("git log origin/main..HEAD --oneline", cwd=vault_path)
return unpushed.strip()
def open_obsidian(obsidian_path):
"""
Launches Obsidian in a cross-platform manner with improved handling.
Supports various installation methods including native, Snap, Flatpak, and App Store.
"""
try:
if not obsidian_path:
print("Error: No Obsidian path configured")
return False
if sys.platform.startswith("win"):
# Windows: Handle both executable paths and command strings
if obsidian_path.endswith('.exe') and os.path.exists(obsidian_path):
# Direct executable path
subprocess.Popen([obsidian_path], shell=False)
else:
# Fallback to shell execution for edge cases
subprocess.Popen(obsidian_path, shell=True)
elif sys.platform.startswith("linux"):
# Linux: Handle various installation methods
if obsidian_path.startswith("flatpak "):
# Flatpak command string - split properly
cmd_parts = shlex.split(obsidian_path)
subprocess.Popen(cmd_parts)
elif obsidian_path.startswith("/snap/") or "snap" in obsidian_path:
# Snap installation
if os.path.exists(obsidian_path):
subprocess.Popen([obsidian_path])
else:
subprocess.Popen(["snap", "run", "obsidian"])
elif os.path.exists(obsidian_path):
# Direct executable path (AppImage, native binary, etc.)
subprocess.Popen([obsidian_path])
else:
# Command in PATH or complex command string
try:
cmd_parts = shlex.split(obsidian_path)
subprocess.Popen(cmd_parts)
except ValueError:
# Fallback to shell if splitting fails
subprocess.Popen(obsidian_path, shell=True)
elif sys.platform.startswith("darwin"):
# macOS: Handle app bundles and command paths
if obsidian_path.endswith('.app') or '/Applications/' in obsidian_path:
# App bundle - use 'open' command
if obsidian_path.endswith('.app'):
subprocess.Popen(['open', '-a', obsidian_path])
else:
# Path to executable inside app bundle
subprocess.Popen([obsidian_path])
elif os.path.exists(obsidian_path):
# Direct executable path
subprocess.Popen([obsidian_path])
else:
# Command in PATH
subprocess.Popen([obsidian_path])
else:
# Other platforms - generic approach
if os.path.exists(obsidian_path):
subprocess.Popen([obsidian_path])
else:
subprocess.Popen(obsidian_path, shell=True)
print(f"Launched Obsidian: {obsidian_path}")
return True
except Exception as e:
print(f"Error launching Obsidian: {e}")
return False
def conflict_resolution_dialog(conflict_files):
"""
Opens a two-stage conflict resolution dialog system.
Stage 1: High-level strategy selection (Keep Local, Keep Remote, Smart Merge)
Stage 2: File-by-file resolution for conflicting files (if Smart Merge is chosen)
Returns the user's choice as one of the strings: "ours", "theirs", or "manual".
This maintains backward compatibility while providing enhanced resolution capabilities.
"""
if not CONFLICT_RESOLUTION_AVAILABLE:
print("Enhanced conflict resolution not available, using fallback")
return ui_elements.create_conflict_resolution_dialog(root, conflict_files)
try:
# Get vault path from config
vault_path = config_data.get("VAULT_PATH", "")
if not vault_path:
print("No vault path configured")
return ui_elements.create_conflict_resolution_dialog(root, conflict_files)
# Create conflict resolver
import Stage1_conflict_resolution as cr_module
resolver = cr_module.ConflictResolver(vault_path, root)
# Create a mock remote URL for conflict analysis (this should ideally come from git remote)
github_url = config_data.get("GITHUB_REMOTE_URL", "")
# Use the enhanced conflict resolution system
result = resolver.resolve_initial_setup_conflicts(github_url)
if result.success:
strategy = result.strategy
if strategy:
# Map new strategies to old format for backward compatibility
if strategy.value == "keep_local_only":
return 'ours'
elif strategy.value == "keep_remote_only":
return 'theirs'
elif strategy.value == "smart_merge":
return 'manual' # Indicates smart merge was applied
return 'manual' # Default for successful resolution
else:
# User cancelled or resolution failed
if "cancelled by user" in result.message.lower():
return None # User cancelled
else:
print(f"Enhanced conflict resolution failed: {result.message}")
# Fallback to simple dialog
return ui_elements.create_conflict_resolution_dialog(root, conflict_files)
except Exception as e:
print(f"Error in enhanced conflict resolution: {e}")
import traceback
traceback.print_exc()
# Fallback to original UI element for backward compatibility
return ui_elements.create_conflict_resolution_dialog(root, conflict_files)
# ------------------------------------------------
# REPOSITORY CONFLICT RESOLUTION FUNCTIONS
# ------------------------------------------------
def analyze_repository_state(vault_path):
"""
Analyzes the state of local vault and remote repository to detect potential conflicts.
Returns a dictionary with analysis results.
"""
analysis = {
"has_local_files": False,
"has_remote_files": False,
"local_files": [],
"remote_files": [],
"conflict_detected": False
}
# Check for local files (excluding .git directory)
try:
for root_dir, dirs, files in os.walk(vault_path):
# Skip .git directory
if '.git' in root_dir:
continue
for file in files:
# Skip hidden files and common non-content files
if not file.startswith('.') and file not in ['README.md', '.gitignore']:
rel_path = os.path.relpath(os.path.join(root_dir, file), vault_path)
analysis["local_files"].append(rel_path)
analysis["has_local_files"] = len(analysis["local_files"]) > 0
except Exception as e:
safe_update_log(f"Error analyzing local files: {e}", None)
# Check for remote files by attempting to fetch
try:
# Try to fetch remote refs to see if repository has content
fetch_out, fetch_err, fetch_rc = run_command("git fetch origin", cwd=vault_path)
if fetch_rc == 0:
# Check if remote main branch exists and has files
ls_out, ls_err, ls_rc = run_command("git ls-tree -r --name-only origin/main", cwd=vault_path)
if ls_rc == 0 and ls_out.strip():
remote_files = [f.strip() for f in ls_out.splitlines() if f.strip() and not f.startswith('.')]
# Filter out common non-content files
analysis["remote_files"] = [f for f in remote_files if f not in ['README.md', '.gitignore']]
analysis["has_remote_files"] = len(analysis["remote_files"]) > 0
except Exception as e:
safe_update_log(f"Error analyzing remote repository: {e}", None)
# Determine if there's a conflict (both local and remote have content files)
analysis["conflict_detected"] = analysis["has_local_files"] and analysis["has_remote_files"]
return analysis
def handle_initial_repository_conflict(vault_path, analysis, parent_window=None):
"""
Handles repository content conflicts during initial setup using the enhanced two-stage resolution system.
Returns True if resolved successfully, False otherwise.
"""
if not analysis["conflict_detected"]:
return True
if not CONFLICT_RESOLUTION_AVAILABLE:
# Fall back to simple dialog
safe_update_log("Enhanced conflict resolution not available, using fallback", None)
return False
try:
# Use the enhanced two-stage conflict resolution system
dialog_parent = parent_window if parent_window is not None else root
# Create conflict resolver
import Stage1_conflict_resolution as cr_module
resolver = cr_module.ConflictResolver(vault_path, dialog_parent)
# Get GitHub URL for analysis
github_url = config_data.get("GITHUB_REMOTE_URL", "")
# Use the enhanced conflict resolution system
result = resolver.resolve_initial_setup_conflicts(github_url)
if result.success:
safe_update_log(f"Repository conflict resolved successfully: {result.message}", None)
return True
else:
if "cancelled by user" in result.message.lower():
safe_update_log("Conflict resolution cancelled by user", None)
return False
else:
safe_update_log(f"Repository conflict resolution failed: {result.message}", None)
return False
except Exception as e:
safe_update_log(f"Error in enhanced repository conflict resolution: {e}", None)
import traceback
traceback.print_exc()
return False
def ensure_git_user_config():
"""
Ensures Git user configuration is set up for commits.
Sets default values if not configured.
"""
try:
# Check if user.name is configured
name_out, name_err, name_rc = run_command("git config --global user.name")
if name_rc != 0 or not name_out.strip():
safe_update_log("Setting default Git user name...", None)
run_command('git config --global user.name "Ogresync User"')
# Check if user.email is configured
email_out, email_err, email_rc = run_command("git config --global user.email")
if email_rc != 0 or not email_out.strip():
safe_update_log("Setting default Git user email...", None)
run_command('git config --global user.email "ogresync@example.com"')
except Exception as e:
safe_update_log(f"Warning: Could not configure Git user settings: {e}", None)
# ===== DEPRECATED FUNCTIONS REMOVED =====
# The following functions have been replaced by the enhanced conflict_resolution module:
# - handle_merge_strategy() -> Use conflict_resolution.ConflictResolver
# - handle_local_strategy() -> Use conflict_resolution._apply_keep_local_strategy
# - handle_remote_strategy() -> Use conflict_resolution._apply_keep_remote_strategy
#
# These old functions contained potentially destructive operations and have been
# replaced with non-destructive alternatives that preserve git history and create backups.
#
# All conflict resolution is now handled through:
# - conflict_resolution.ConflictResolver.resolve_conflicts()
# - conflict_resolution.apply_conflict_resolution()
#
# See conflict_resolution.py for the new implementation.
def create_descriptive_backup_dir(vault_path, operation_description, file_list=None):
"""
Creates a backup directory with a descriptive name and optional README.
Args:
vault_path: Path to the vault directory
operation_description: Description of the operation (e.g., "before_remote_download")
file_list: Optional list of files being backed up (for documentation)
Returns:
tuple: (backup_dir_path, backup_name)
"""
from datetime import datetime
# Create human-readable timestamp
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
backup_name = f"LOCAL_FILES_BACKUP_{timestamp}_{operation_description}"
backup_dir = os.path.join(vault_path, backup_name)
# Handle name collisions with incremental counter
counter = 1
while os.path.exists(backup_dir):
backup_name = f"LOCAL_FILES_BACKUP_{timestamp}_{operation_description}_({counter})"
backup_dir = os.path.join(vault_path, backup_name)
counter += 1
# Create the backup directory
os.makedirs(backup_dir, exist_ok=True)
# Create a README file explaining the backup
readme_path = os.path.join(backup_dir, "BACKUP_INFO.txt")
with open(readme_path, "w", encoding="utf-8") as f:
f.write(f"OGRESYNC LOCAL FILES BACKUP\n")
f.write(f"=" * 50 + "\n\n")
f.write(f"Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Operation: {operation_description.replace('_', ' ').title()}\n")
f.write(f"Backup Directory: {backup_name}\n\n")
f.write(f"PURPOSE:\n")
f.write(f"This backup was created to preserve your local vault files\n")
f.write(f"before performing a repository operation that might modify them.\n\n")
if file_list:
f.write(f"BACKED UP FILES ({len(file_list)} items):\n")
f.write(f"-" * 30 + "\n")
for file_path in sorted(file_list):
f.write(f" • {file_path}\n")
f.write("\n")
f.write(f"RESTORATION:\n")
f.write(f"If you need to restore these files, simply copy them back\n")
f.write(f"from this backup directory to your vault directory.\n\n")
f.write(f"SAFETY:\n")
f.write(f"This backup can be safely deleted once you're confident\n")
f.write(f"that the repository operation completed successfully.\n")
return backup_dir, backup_name
# Import GitHub setup functions from separate module
import github_setup
# Initialize GitHub setup module dependencies
try:
import Stage1_conflict_resolution as cr_module
github_setup.set_dependencies(
ui_elements=None, # Will be set later when ui_elements is available
config_data=config_data,
save_config_func=save_config,
conflict_resolution_module=cr_module,
safe_update_log_func=safe_update_log
)
except ImportError:
# Conflict resolution module not available
github_setup.set_dependencies(
ui_elements=None, # Will be set later when ui_elements is available
config_data=config_data,
save_config_func=save_config,
conflict_resolution_module=None,
safe_update_log_func=safe_update_log
)
def restart_for_setup():
"""
Restart the application to run the setup wizard.
"""
try:
safe_update_log("Restarting for setup wizard...", None)
# Close current UI if it exists
if root is not None:
root.quit()
root.destroy()
# Re-run the main function which will detect SETUP_DONE=0 and run the wizard
main()
except Exception as e:
safe_update_log(f"❌ Error restarting for setup: {e}", None)
def restart_to_sync_mode():
"""
Restart the application in sync mode after setup completion.
FIXED: Comprehensive threading isolation to prevent Tcl_AsyncDelete errors.
"""
global root, log_text, progress_bar
try:
print("DEBUG: Transitioning to sync mode...")
# STEP 1: Immediately disable all UI updates to prevent any thread interference
disable_ui_updates()
# STEP 2: Force garbage collection to clean up any dangling references
import gc
gc.collect()
# STEP 3: Wait for all daemon threads to finish current operations
print("DEBUG: Stopping any remaining background operations...")
print("DEBUG: Waiting for background threads to complete UI operations...")
time.sleep(1.5) # Give existing threads time to finish
# STEP 4: Comprehensive UI cleanup with complete isolation
if root is not None:
try:
print("DEBUG: Comprehensive UI cleanup...")
# Cancel ALL pending operations - be very aggressive
try:
# Method 1: Cancel all after calls
root.after_cancel("all")
# Method 2: Clear the event queue
while True:
try:
root.update_idletasks()
if not root.tk.call('after', 'info'):
break
except:
break
# Method 3: Force process remaining events
for _ in range(10): # Process up to 10 pending events
try:
root.update_idletasks()
except:
break
except Exception as cleanup_err:
print(f"Event cleanup error (non-critical): {cleanup_err}")
# STEP 5: Complete widget destruction
print("DEBUG: Complete widget destruction...")
try:
# Hide window immediately
root.withdraw()
root.overrideredirect(True) # Prevent any window manager interactions
# Wait for any pending operations to complete
time.sleep(0.5)
# Quit mainloop
root.quit()
# Additional safety delay
time.sleep(0.5)
# Final destroy
root.destroy()
except Exception as destroy_error:
print(f"Widget destruction error (non-critical): {destroy_error}")
# Clear all global references immediately
root = None
log_text = None
progress_bar = None
print("DEBUG: UI destroyed successfully")
except Exception as cleanup_error:
print(f"UI cleanup error (will continue): {cleanup_error}")
# STEP 6: Extended thread isolation period
print("DEBUG: Extended thread isolation period...")
# Force another garbage collection
gc.collect()
# Wait longer for all threads to completely finish
time.sleep(4.0) # Increased from 3.0 to 4.0 seconds
# Monitor active threads
active_thread_count = threading.active_count()
print(f"DEBUG: Active thread count after cleanup: {active_thread_count}")
# If there are still many active threads, wait a bit more
if active_thread_count > 2: # Main thread + potentially 1 cleanup thread
print("DEBUG: Waiting for additional background threads to finish...")
time.sleep(2.0)
final_count = threading.active_count()
print(f"DEBUG: Final active thread count: {final_count}")
# STEP 7: Create completely new UI in isolated environment