-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiconfig.py
More file actions
executable file
·3685 lines (3103 loc) · 131 KB
/
iconfig.py
File metadata and controls
executable file
·3685 lines (3103 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Mac Sync Wizard - All-in-One Version
This is a single-file version of Mac Sync Wizard that contains all functionality
without requiring any external module imports. This ensures the tool works reliably
on any Mac without import or module structure issues.
"""
import os
import sys
import json
import time
import shutil
import logging
import argparse
import subprocess
import datetime
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple, Union
# -----------------------------------------------------------------------------
# Constants and Global Variables
# -----------------------------------------------------------------------------
HOME_DIR = os.path.expanduser("~")
APP_DIR = os.path.join(HOME_DIR, ".mac-sync-wizard")
CONFIG_DIR = os.path.join(APP_DIR, "config")
LOGS_DIR = os.path.join(APP_DIR, "logs")
REPO_DIR = os.path.join(APP_DIR, "repo")
CONFIG_PATH = os.path.join(CONFIG_DIR, "sync_config.json")
LAST_SYNC_FILE = os.path.join(APP_DIR, "last_sync")
LOCK_FILE = os.path.join(APP_DIR, "sync.lock")
# Setup logging
os.makedirs(LOGS_DIR, exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(os.path.join(LOGS_DIR, "mac-sync-wizard.log")),
logging.StreamHandler(),
],
)
logger = logging.getLogger("mac-sync-wizard")
# -----------------------------------------------------------------------------
# Terminal UI Utilities
# -----------------------------------------------------------------------------
class TerminalColors:
"""ANSI color codes for terminal output."""
RESET = "\033[0m"
BOLD = "\033[1m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BG_RED = "\033[41m"
BG_GREEN = "\033[42m"
BG_YELLOW = "\033[43m"
BG_BLUE = "\033[44m"
def clear_screen():
"""Clear the terminal screen."""
os.system("cls" if os.name == "nt" else "clear")
def print_header(title: str):
"""Print a styled header."""
width = 80
print()
print(f"{TerminalColors.BLUE}┏{'━' * (width - 2)}┓{TerminalColors.RESET}")
print(f"{TerminalColors.BLUE}┃{' ' * (width - 2)}┃{TerminalColors.RESET}")
print(
f"{TerminalColors.BLUE}┃ 🔄 {TerminalColors.BOLD}{title}{TerminalColors.RESET}{TerminalColors.BLUE}{' ' * (width - len(title) - 6)}┃{TerminalColors.RESET}"
)
print(f"{TerminalColors.BLUE}┃{' ' * (width - 2)}┃{TerminalColors.RESET}")
print(f"{TerminalColors.BLUE}┗{'━' * (width - 2)}┛{TerminalColors.RESET}")
print()
def print_success(message: str):
"""Print a success message."""
print(f"\n{TerminalColors.GREEN}✅ {message}{TerminalColors.RESET}\n")
def print_error(message: str):
"""Print an error message."""
print(f"\n{TerminalColors.RED}❌ {message}{TerminalColors.RESET}\n")
def print_warning(message: str):
"""Print a warning message."""
print(f"\n{TerminalColors.YELLOW}⚠️ {message}{TerminalColors.RESET}\n")
def print_step(message: str):
"""Print a step message."""
print(f"\n{TerminalColors.CYAN}➡️ {message}{TerminalColors.RESET}")
def print_menu(options: List[Tuple[str, str]], title: str = "Please select an option"):
"""Print a menu with options."""
print(f"{TerminalColors.BLUE}┏{'━' * 78}┓{TerminalColors.RESET}")
print(
f"{TerminalColors.BLUE}┃ {title}{' ' * (77 - len(title))}┃{TerminalColors.RESET}"
)
print(f"{TerminalColors.BLUE}┣{'━' * 78}┫{TerminalColors.RESET}")
for key, description in options:
print(
f"{TerminalColors.BLUE}┃ {TerminalColors.CYAN}[{key}]{TerminalColors.RESET} {description}{' ' * (71 - len(description) - len(key))}┃{TerminalColors.RESET}"
)
print(f"{TerminalColors.BLUE}┗{'━' * 78}┛{TerminalColors.RESET}")
def print_info(message: str):
"""Print an informational message."""
print(f"\n{TerminalColors.BLUE}ℹ️ {message}{TerminalColors.RESET}\n")
def get_input(prompt: str, default: str = None) -> str:
"""Get user input with an optional default value."""
if default:
result = input(f"{prompt} [{default}]: ").strip()
return result if result else default
return input(f"{prompt}: ").strip()
def get_choice(prompt: str, options: List[str], default: str = None) -> str:
"""Get a choice from a list of options."""
while True:
if default:
result = (
input(f"{prompt} [{'/'.join(options)}] (default: {default}): ")
.strip()
.lower()
)
if not result:
return default
else:
result = input(f"{prompt} [{'/'.join(options)}]: ").strip().lower()
if result in options:
return result
print_error(f"Invalid choice. Please enter one of: {', '.join(options)}")
def get_yes_no(prompt: str, default: bool = True) -> bool:
"""Get a yes/no response from the user."""
default_str = "Y/n" if default else "y/N"
while True:
result = input(f"{prompt} [{default_str}]: ").strip().lower()
if not result:
return default
if result in ["y", "yes"]:
return True
if result in ["n", "no"]:
return False
print_error("Invalid choice. Please enter Y or N.")
def get_menu_choice(
options: List[Tuple[str, str]], title: str = "Please select an option"
) -> str:
"""Display a menu and get user choice."""
print_menu(options, title)
valid_keys = [key for key, _ in options]
while True:
choice = input("Enter your choice: ").strip()
if choice in valid_keys:
return choice
print_error(f"Invalid choice. Please enter one of: {', '.join(valid_keys)}")
# -----------------------------------------------------------------------------
# Configuration Manager
# -----------------------------------------------------------------------------
# Default utility configurations
UTILITY_CONFIGS = {
# Syncable utilities (enabled by default)
"cursor": {
"enabled": True,
"paths": [
"~/Library/Application Support/Cursor/User/keybindings.json",
"~/Library/Application Support/Cursor/User/settings.json",
"~/Library/Application Support/Cursor/User/extensions/",
],
"exclude_patterns": ["*.log", "Cache/*"],
"install_url": "https://downloader.cursor.sh/download/latest/mac",
},
"pycharm": {
"enabled": True,
"paths": [
"~/Library/Application Support/JetBrains/PyCharm*/options/",
"~/Library/Application Support/JetBrains/PyCharm*/keymaps/",
"~/Library/Application Support/JetBrains/PyCharm*/codestyles/",
"~/Library/Application Support/JetBrains/PyCharm*/templates/",
"~/Library/Application Support/JetBrains/PyCharm*/colors/",
"~/Library/Application Support/JetBrains/PyCharm*/fileTemplates/",
"~/Library/Application Support/JetBrains/PyCharm*/inspection/",
"~/Library/Application Support/JetBrains/PyCharm*/tools/",
"~/Library/Application Support/JetBrains/PyCharm*/shelf/",
],
"exclude_patterns": [
"*.log",
"Cache/*",
"workspace/",
"tasks/",
"scratches/",
"jdbc-drivers/",
"ssl/",
"port",
"plugins/updatedPlugins.xml",
"marketplace/",
"*.hprof",
"*.snapshot",
"eval/",
"repair/",
"*/.DS_Store",
],
"install_url": "https://download.jetbrains.com/python/pycharm-2025.1.1.1-aarch64.dmg",
},
"sublime": {
"enabled": True,
"paths": ["~/Library/Application Support/Sublime Text/Packages/User/"],
"exclude_patterns": ["*.log", "Cache/*"],
"install_url": "https://download.sublimetext.com/sublime_text_build_4180_mac.zip",
},
"trackpad": {
"enabled": True,
"paths": [
"~/Library/Preferences/com.apple.driver.AppleBluetoothMultitouch.trackpad.plist",
"~/Library/Preferences/com.apple.AppleMultitouchTrackpad.plist",
],
"exclude_patterns": [],
},
"git": {
"enabled": True,
"paths": ["~/.gitconfig", "~/.config/git/"],
"exclude_patterns": [],
},
"warp": {
"enabled": True,
"paths": [
"~/.warp/themes/",
"~/.warp/launch_configurations/",
"~/.warp/user_scripts/",
"~/.warp/settings.yaml",
"~/.warp/keybindings.json",
],
"exclude_patterns": [
"Cache/*",
"*.log",
"*.pyc",
"__pycache__",
"*.sock",
"*.pid",
],
"install_url": "https://app.warp.dev/download/stable",
},
"fonts": {
"enabled": True,
"paths": ["~/Library/Fonts/"],
"exclude_patterns": [],
"include_patterns": [], # If specified, only files matching these patterns will be synced
"custom_fonts": [], # List of font family names to sync (e.g., ["Zed Plex Sans", "SF Mono"])
},
"anki": {
"enabled": True,
"paths": [
"~/Library/Application Support/Anki2/addons21/",
"~/Library/Application Support/Anki2/prefs21.db",
],
"exclude_patterns": ["*.log"],
},
"stretchly": {
"enabled": True,
"paths": ["~/Library/Application Support/stretchly/"],
"exclude_patterns": ["*.log"],
},
"maccy": {
"enabled": True,
"paths": [
"~/Library/Containers/org.p0deje.Maccy/Data/Library/Preferences/org.p0deje.Maccy.plist"
],
"exclude_patterns": [],
},
"shell": {
"enabled": True,
"paths": [
"~/.iconfig/shell/" # Custom directory for organized shell configs
],
"exclude_patterns": [],
"description": "Shell aliases, functions, and custom configurations",
"setup_on_enable": True, # Special flag to run setup when enabled
},
# Installation-only utilities (disabled by default, not synced)
"arc": {
"enabled": False, # Installation only
"paths": [
"~/Library/Application Support/Arc/",
"~/Library/Preferences/company.thebrowser.Arc.plist",
],
"exclude_patterns": ["Cache/*", "*.log"],
"install_url": "https://releases.arc.net/release/Arc-latest.dmg",
},
"logi": {
"enabled": False, # Installation only
"paths": [
"~/Library/Preferences/com.logi.optionsplus.plist",
"~/Library/Application Support/LogiOptionsPlus/config.json",
"~/Library/Application Support/LogiOptionsPlus/settings.db",
"~/Library/Application Support/LogiOptionsPlus/macros.db",
"~/Library/Application Support/LogiOptionsPlus/permissions.json",
"~/Library/Application Support/LogiOptionsPlus/cc_config.json",
],
"exclude_patterns": [],
},
"1password": {
"enabled": False, # Installation only
"paths": [
"~/Library/Application Support/1Password/",
"~/Library/Preferences/com.1password.1password.plist",
],
"exclude_patterns": ["*.log", "Cache/*"],
},
}
# Default configuration
DEFAULT_CONFIG = {
"repository": {"url": "", "branch": "main", "auth_type": "ssh"},
"sync": {
"frequency": 21600, # 6 hours in seconds
"auto_commit": True,
"commit_message_template": "Auto-sync: {date} - {changes}",
"pull_strategy": "rebase", # "rebase" or "merge"
},
"notifications": {
"level": "errors_only", # all, errors_only, none
"method": "terminal-notifier",
},
"utilities": UTILITY_CONFIGS,
}
def load_config() -> Dict[str, Any]:
"""Load configuration from file or create default if not exists."""
try:
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, "r") as f:
config = json.load(f)
# Merge with default config to ensure all fields exist
merged_config = DEFAULT_CONFIG.copy()
deep_update(merged_config, config)
return merged_config
else:
# Create default configuration
return create_default_config()
except Exception as e:
logger.error(f"Error loading config: {str(e)}")
return DEFAULT_CONFIG.copy()
def deep_update(d: Dict[str, Any], u: Dict[str, Any]) -> None:
"""Recursively update a dictionary with another dictionary."""
for k, v in u.items():
if isinstance(v, dict) and k in d and isinstance(d[k], dict):
deep_update(d[k], v)
else:
d[k] = v
def create_default_config() -> Dict[str, Any]:
"""Create default configuration with predefined utility settings."""
config = DEFAULT_CONFIG.copy()
# Create config directory if it doesn't exist
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
# Save default config
with open(CONFIG_PATH, "w") as f:
json.dump(config, f, indent=2)
return config
def save_config(config: Dict[str, Any]) -> bool:
"""Save configuration to file."""
try:
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
with open(CONFIG_PATH, "w") as f:
json.dump(config, f, indent=2)
logger.info("Configuration saved successfully")
return True
except Exception as e:
logger.error(f"Failed to save config: {str(e)}")
return False
def get_enabled_utilities(config: Dict[str, Any]) -> List[str]:
"""Get a list of enabled utilities."""
return [
utility
for utility, util_config in config["utilities"].items()
if util_config.get("enabled", False)
]
def detect_installed_utilities() -> List[str]:
"""Detect which predefined utilities are installed on the system."""
installed = []
for utility, config in UTILITY_CONFIGS.items():
# Check if any of the paths exist
for path_pattern in config["paths"]:
expanded_path = os.path.expanduser(path_pattern)
# Handle glob patterns
if "*" in expanded_path:
# Check if any matching files exist
import glob
matches = glob.glob(expanded_path)
if matches:
installed.append(utility)
break
else:
# Check if the exact path exists
if os.path.exists(expanded_path):
installed.append(utility)
break
return installed
# -----------------------------------------------------------------------------
# Git Sync Manager
# -----------------------------------------------------------------------------
def run_command(
command: List[str], cwd: str = None, check: bool = True
) -> Tuple[int, str, str]:
"""Run a shell command and return exit code, stdout, and stderr."""
try:
process = subprocess.Popen(
command,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=os.environ, # Ensure git commands have access to user's environment (e.g. for SSH keys)
)
stdout, stderr = process.communicate()
exit_code = process.returncode
if check and exit_code != 0:
logger.error(f"Command failed: {' '.join(command)}")
logger.error(f"Exit code: {exit_code}")
logger.error(f"Stdout: {stdout}")
logger.error(f"Stderr: {stderr}")
return exit_code, stdout, stderr
except Exception as e:
logger.error(f"Exception running command {' '.join(command)}: {str(e)}")
return 1, "", str(e)
def command_exists(command: str) -> bool:
"""Check if a command exists."""
exit_code, _, _ = run_command(["which", command], check=False)
return exit_code == 0
def get_directory_size(path: str) -> Tuple[int, str]:
"""Get the size of a directory in bytes and human-readable format."""
try:
if os.path.isfile(path):
size = os.path.getsize(path)
else:
# Use du command for accurate size calculation
exit_code, stdout, _ = run_command(["du", "-sk", path], check=False)
if exit_code == 0:
# du -sk returns size in KB
size = int(stdout.split()[0]) * 1024
else:
# Fallback to Python calculation
size = 0
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
try:
size += os.path.getsize(filepath)
except:
pass
# Convert to human-readable format
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size < 1024.0:
return size, f"{size:.1f} {unit}"
size /= 1024.0
return size * 1024 * 1024 * 1024 * 1024, f"{size:.1f} PB"
except Exception as e:
logger.error(f"Failed to get size for {path}: {str(e)}")
return 0, "0 B"
def check_disk_space(path: str, required_mb: int = 100) -> Tuple[bool, str]:
"""Check if there's enough disk space at the given path."""
try:
import shutil
stat = shutil.disk_usage(path)
available_mb = stat.free / (1024 * 1024)
if available_mb < required_mb:
return (
False,
f"Insufficient disk space: {available_mb:.1f}MB available, {required_mb}MB required",
)
return True, f"Sufficient disk space: {available_mb:.1f}MB available"
except Exception as e:
return False, f"Failed to check disk space: {str(e)}"
def check_network_connectivity() -> Tuple[bool, str]:
"""Check basic network connectivity."""
try:
# Try to resolve a common DNS name
import socket
socket.gethostbyname("github.com")
return True, "Network connectivity verified"
except socket.error:
return False, "No network connectivity detected"
def check_git_credentials(repo_url: str) -> Tuple[bool, str]:
"""Check if Git credentials are properly configured for the repository."""
if not repo_url:
return True, "No repository configured"
# For SSH URLs, check if SSH key is available
if repo_url.startswith("git@"):
ssh_key_path = os.path.expanduser("~/.ssh/id_rsa")
ssh_key_ed25519 = os.path.expanduser("~/.ssh/id_ed25519")
if not (os.path.exists(ssh_key_path) or os.path.exists(ssh_key_ed25519)):
return (
False,
"No SSH key found. Please set up SSH keys for Git authentication",
)
return True, "Git credentials check passed"
def check_git_lfs() -> Tuple[bool, str]:
"""Check if Git LFS is installed."""
if command_exists("git-lfs"):
return True, "Git LFS is installed"
else:
return False, "Git LFS not installed (needed for large files)"
def perform_preflight_checks(config: Dict[str, Any]) -> bool:
"""Perform pre-flight checks before sync operations."""
print_step("Performing pre-flight checks...")
checks = [
(
"Git installation",
lambda: (
command_exists("git"),
"Git is installed" if command_exists("git") else "Git is not installed",
),
),
("Disk space", lambda: check_disk_space(APP_DIR)),
("Network connectivity", lambda: check_network_connectivity()),
(
"Git credentials",
lambda: check_git_credentials(config.get("repository", {}).get("url", "")),
),
("Git LFS", lambda: check_git_lfs()),
]
all_passed = True
for check_name, check_func in checks:
passed, message = check_func()
if passed:
print(f" ✓ {check_name}: {message}")
else:
print_error(f" ✗ {check_name}: {message}")
all_passed = False
return all_passed
def init_repository(url: str, branch: str = "main") -> bool:
"""Initialize a new repository or connect to existing one."""
logger.info(f"Initializing repository: {url} ({branch})")
# Validate URL (basic check)
if not url.startswith(("http://", "https://", "git@")):
logger.error(f"Invalid repository URL format: {url}")
print_error(
f"Invalid repository URL format. Please use http(s):// or git@ format."
)
return False
git_dir = os.path.join(REPO_DIR, ".git")
if os.path.exists(git_dir):
# REPO_DIR exists and is a Git repository
logger.info(f"Found existing Git repository in {REPO_DIR}")
return connect_existing_repo_flow(url, branch)
elif os.path.exists(REPO_DIR) and os.listdir(REPO_DIR):
# REPO_DIR exists but is not a Git repository or is an empty .git folder
logger.warning(
f"{REPO_DIR} exists and is not empty or not a valid Git repository."
)
if get_yes_no(
f"Directory {REPO_DIR} exists and is not a recognized Git repository or is not empty. Do you want to try to use it or re-initialize? (y=use, n=re-initialize)",
default=False,
):
# Try to initialize in existing non-empty directory, could fail if .git is corrupted / partial
return create_new_repo_flow(url, branch, force_init_in_existing=True)
else:
if get_yes_no(
f"Do you want to delete {REPO_DIR} and start fresh? (This is irreversible)",
default=False,
):
try:
shutil.rmtree(REPO_DIR)
logger.info(f"Removed existing directory: {REPO_DIR}")
os.makedirs(REPO_DIR, exist_ok=True) # Recreate after deletion
return create_new_repo_flow(url, branch)
except Exception as e:
logger.error(f"Failed to remove directory {REPO_DIR}: {str(e)}")
print_error(
f"Could not remove {REPO_DIR}. Please check permissions or remove it manually."
)
return False
else:
print_warning("Repository setup aborted by user.")
return False
else:
# REPO_DIR does not exist or is empty
os.makedirs(REPO_DIR, exist_ok=True) # Ensure REPO_DIR exists
return create_new_repo_flow(url, branch)
def create_new_repo_flow(
url: str, branch: str, force_init_in_existing: bool = False
) -> bool:
"""Handles the flow for creating a new repository."""
if not force_init_in_existing:
logger.info(f"Creating new repository in {REPO_DIR}")
else:
logger.info(
f"Attempting to initialize Git repository in existing directory {REPO_DIR}"
)
if create_new_repo(url, branch):
print_success(
f"Successfully initialized new repository and connected to {url} on branch {branch}."
)
return True
else:
print_error(f"Failed to create and initialize new repository at {url}.")
# Clean up REPO_DIR if we created it and initialization failed, to allow retry
# But only if it was truly empty before we started, to avoid deleting user data if force_init_in_existing
if (
not force_init_in_existing
and os.path.exists(REPO_DIR)
and not os.listdir(REPO_DIR)
):
try:
shutil.rmtree(REPO_DIR)
logger.info(f"Cleaned up {REPO_DIR} after failed initialization.")
except Exception as e:
logger.warning(f"Failed to clean up {REPO_DIR} after failed init: {e}")
return False
def connect_existing_repo_flow(url: str, branch: str) -> bool:
"""Handles the flow for connecting to an existing repository."""
logger.info(f"Attempting to connect to existing repository settings in {REPO_DIR}")
# Verify remote URL if possible
exit_code, remote_url, _ = run_command(
["git", "config", "--get", "remote.origin.url"], cwd=REPO_DIR, check=False
)
if exit_code == 0 and remote_url.strip() != url:
logger.warning(
f"Existing repo remote URL '{remote_url.strip()}' differs from desired '{url}'."
)
if not get_yes_no(
f"The existing repository is configured for {remote_url.strip()}. Do you want to update it to {url}?",
default=True,
):
print_warning("Repository connection aborted by user.")
return False
if connect_existing_repo(url, branch):
print_success(
f"Successfully connected to existing repository {url} on branch {branch}."
)
return True
else:
print_error(f"Failed to connect to existing repository {url}.")
return False
def setup_git_lfs_for_fonts() -> bool:
"""Setup Git LFS for font files."""
try:
# Check if Git LFS is available
if not command_exists("git-lfs"):
print_warning(
"Git LFS is not installed. Large font files may cause issues."
)
print_info("Install with: brew install git-lfs")
return False
# Initialize Git LFS in the repository
exit_code, _, stderr = run_command(
["git", "lfs", "install"], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"Failed to initialize Git LFS: {stderr}")
return False
# Track font files with Git LFS
font_patterns = ["*.ttf", "*.otf", "*.ttc", "*.woff", "*.woff2"]
for pattern in font_patterns:
exit_code, _, _ = run_command(
["git", "lfs", "track", f"backups/fonts/{pattern}"],
cwd=REPO_DIR,
check=False,
)
# Add .gitattributes to track LFS files
exit_code, _, _ = run_command(
["git", "add", ".gitattributes"], cwd=REPO_DIR, check=False
)
logger.info("Git LFS configured for font files")
return True
except Exception as e:
logger.error(f"Failed to setup Git LFS: {str(e)}")
return False
def create_new_repo(url: str, branch: str) -> bool:
"""Create a new repository and set remote."""
try:
# Create repository directory
os.makedirs(REPO_DIR, exist_ok=True)
# Initialize Git repository
exit_code, stdout, stderr = run_command(
["git", "init"], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git init failed: {stderr}")
# Check if it's because it's already a git repo, which can happen with force_init_in_existing
if (
"already a git repository" not in stderr.lower()
and "reinitialized existing git repository" not in stderr.lower()
):
print_error(f"Failed to initialize Git repository: {stderr}")
return False
logger.info("Git repository already exists or was reinitialized.")
# Setup Git LFS for fonts
setup_git_lfs_for_fonts()
# Set remote
# Try removing remote origin first, in case it exists and is wrong (e.g. re-initializing)
run_command(["git", "remote", "remove", "origin"], cwd=REPO_DIR, check=False)
exit_code, _, stderr = run_command(
["git", "remote", "add", "origin", url], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git remote add origin failed: {stderr}")
print_error(f"Failed to set remote origin: {stderr}")
return False
# Fetch from remote to get all branches
print_step("Fetching from remote repository...")
exit_code, _, stderr = run_command(
["git", "fetch", "origin"], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.warning(
f"git fetch failed: {stderr}. This might be a new empty repository."
)
# Don't fail here - might be a new empty repo
# Create initial structure
for dir_name in ["backups", "config", "logs"]:
os.makedirs(os.path.join(REPO_DIR, dir_name), exist_ok=True)
# Create README
with open(os.path.join(REPO_DIR, "README.md"), "w") as f:
f.write(
f"# Mac Sync Wizard Repository\n\nThis repository contains synchronized Mac utility settings.\n"
)
# Add files
exit_code, _, _ = run_command(["git", "add", "."], cwd=REPO_DIR)
if exit_code != 0:
return False
# Initial commit
exit_code, _, stderr = run_command(
["git", "commit", "-m", "Initial commit"], cwd=REPO_DIR, check=False
)
if exit_code != 0:
# It's okay if initial commit fails due to nothing to commit (e.g., if .gitignore exists and ignores everything)
# Or if we are re-initializing an existing repo that already has commits.
# We check for actual errors.
if (
"nothing to commit" not in stderr.lower()
and "initial commit" not in stderr.lower()
and "no changes added to commit" not in stderr.lower()
):
logger.error(f"Initial git commit failed: {stderr}")
# print_error(f"Failed to make initial commit: {stderr}") # This might be too noisy if it's not a real problem
# return False # Decided not to fail hard here, as repo might be usable
# Check if branch exists on remote after fetch
exit_code, remote_branches, _ = run_command(
["git", "branch", "-r"], cwd=REPO_DIR, check=False
)
remote_branch_exists = (
f"origin/{branch}" in remote_branches if exit_code == 0 else False
)
# Check if branch already exists locally
exit_code_local_branch, local_branch_stdout, _ = run_command(
["git", "branch", "--list", branch], cwd=REPO_DIR, check=False
)
current_branch_code, current_branch_name, _ = run_command(
["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=REPO_DIR, check=False
)
current_branch_name = (
current_branch_name.strip() if current_branch_code == 0 else ""
)
if current_branch_name == branch:
logger.info(f"Already on branch '{branch}'.")
# Try to set upstream if remote branch exists
if remote_branch_exists:
run_command(
["git", "branch", f"--set-upstream-to=origin/{branch}", branch],
cwd=REPO_DIR,
check=False,
)
elif branch in local_branch_stdout:
logger.info(f"Switching to existing local branch '{branch}'.")
exit_code, _, stderr = run_command(
["git", "checkout", branch], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git checkout {branch} failed: {stderr}")
print_error(f"Failed to checkout local branch {branch}: {stderr}")
return False
# Set upstream if remote branch exists
if remote_branch_exists:
run_command(
["git", "branch", f"--set-upstream-to=origin/{branch}", branch],
cwd=REPO_DIR,
check=False,
)
elif remote_branch_exists:
logger.info(f"Remote branch 'origin/{branch}' exists. Checking it out...")
# Create local branch from remote
exit_code, _, stderr = run_command(
["git", "checkout", "-b", branch, f"origin/{branch}"],
cwd=REPO_DIR,
check=False,
)
if exit_code != 0:
# Maybe branch already exists locally, try just checking it out
exit_code, _, stderr = run_command(
["git", "checkout", branch], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"Failed to checkout branch {branch}: {stderr}")
print_error(f"Failed to checkout branch {branch}: {stderr}")
return False
# Set upstream
run_command(
["git", "branch", f"--set-upstream-to=origin/{branch}", branch],
cwd=REPO_DIR,
check=False,
)
else:
logger.info(f"Creating new branch '{branch}'.")
exit_code, _, stderr = run_command(
["git", "checkout", "-b", branch], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git checkout -b {branch} failed: {stderr}")
print_error(f"Failed to create branch {branch}: {stderr}")
return False
# Try to push to set upstream, this also verifies credentials early
# It's okay if this fails (e.g. new empty repo on GitHub, or branch already exists and is protected)
# We are mainly interested in setting upstream for future pulls/pushes.
run_command(
["git", "push", "--set-upstream", "origin", branch],
cwd=REPO_DIR,
check=False,
)
logger.info(f"Repository setup/verified: {url} (branch: {branch})")
return True
except Exception as e:
logger.error(f"Unexpected error creating repository: {str(e)}")
return False
def connect_existing_repo(url: str, branch: str) -> bool:
"""Connect to existing repository."""
try:
# Update remote URL
exit_code, _, stderr = run_command(
["git", "remote", "set-url", "origin", url], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git remote set-url failed: {stderr}")
print_error(f"Failed to set remote URL: {stderr}")
return False
# Fetch
exit_code, _, stderr = run_command(
["git", "fetch", "--all"], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git fetch failed: {stderr}")
print_error(
f"Failed to fetch from remote: {stderr}. Check connection and repository URL."
)
return False
# Check if branch exists on remote
exit_code, stdout, _ = run_command(
["git", "branch", "-r"], cwd=REPO_DIR, check=False
) # list remote branches
if exit_code != 0:
logger.error("Failed to list remote branches.")
# Don't fail here, maybe proceed and try to checkout/create locally
remote_branch_exists = f"origin/{branch}" in stdout
# Check if branch exists locally
exit_code_local, local_stdout, _ = run_command(
["git", "branch", "--list", branch], cwd=REPO_DIR, check=False
)
local_branch_exists = branch in local_stdout
current_branch_code, current_branch_name, _ = run_command(
["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=REPO_DIR, check=False
)
current_branch_name = (
current_branch_name.strip() if current_branch_code == 0 else ""
)
if current_branch_name == branch:
logger.info(
f"Already on branch '{branch}'. Attempting to set upstream if not set."
)
run_command(
["git", "branch", f"--set-upstream-to=origin/{branch}", branch],
cwd=REPO_DIR,
check=False,
)
elif local_branch_exists:
logger.info(f"Checking out existing local branch '{branch}'.")
exit_code, _, stderr = run_command(
["git", "checkout", branch], cwd=REPO_DIR, check=False
)
if exit_code != 0:
logger.error(f"git checkout {branch} failed: {stderr}")
print_error(f"Failed to checkout local branch {branch}: {stderr}")
return False
# Ensure it tracks the remote if the remote branch exists