# GitUtility.py import os # import shutil # Not needed here anymore import datetime import tkinter as tk from tkinter import messagebox import logging # import zipfile # Not needed here anymore # Import application modules from config_manager import ConfigManager, DEFAULT_PROFILE, DEFAULT_BACKUP_DIR from git_commands import GitCommands, GitCommandError from logger_config import setup_logger # Import GUI classes from gui import MainFrame, GitignoreEditorWindow, CreateTagDialog # Import Handler classes from backup_handler import BackupHandler from profile_handler import ProfileHandler from action_handler import ActionHandler class GitSvnSyncApp: """ Main application class: Coordinates GUI, configuration, and actions. Delegates logic to specific handler classes. """ def __init__(self, master): """ Initializes the GitSvnSyncApp. Args: master (tk.Tk): The main Tkinter root window. """ self.master = master master.title("Git SVN Sync Tool") # Handle window close event gracefully master.protocol("WM_DELETE_WINDOW", self.on_closing) # --- Early Logger Setup --- logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" ) self.logger = logging.getLogger("GitSvnSyncApp") # Initialize Core Components try: self.config_manager = ConfigManager(self.logger) self.git_commands = GitCommands(self.logger) # Initialize Handlers self.profile_handler = ProfileHandler(self.logger, self.config_manager) self.backup_handler = BackupHandler(self.logger) self.action_handler = ActionHandler( self.logger, self.git_commands, self.backup_handler ) except Exception as e: self.logger.critical(f"Failed component initialization: {e}", exc_info=True) self.show_fatal_error(f"Initialization Error:\n{e}\nApp cannot start.") master.destroy() return # Create GUI Main Frame, passing necessary callbacks try: self.main_frame = MainFrame( master, load_profile_settings_cb=self.load_profile_settings, browse_folder_cb=self.browse_folder, update_svn_status_cb=self.update_svn_status_indicator, # Action Callbacks prepare_svn_for_git_cb=self.ui_prepare_svn, create_git_bundle_cb=self.ui_create_bundle, fetch_from_git_bundle_cb=self.ui_fetch_bundle, manual_backup_cb=self.ui_manual_backup, manual_commit_cb=self.ui_manual_commit, create_tag_cb=self.ui_create_tag, checkout_tag_cb=self.ui_checkout_tag, refresh_tags_cb=self.refresh_tag_list, open_gitignore_editor_cb=self.open_gitignore_editor, save_profile_cb=self.ui_save_settings, # Profile Management Callbacks add_profile_cb=self.ui_add_profile, remove_profile_cb=self.ui_remove_profile, # Pass instances/data needed by GUI config_manager_instance=self.config_manager, profile_sections_list=self.profile_handler.get_profile_list() ) except Exception as e: self.logger.critical(f"Failed init MainFrame: {e}", exc_info=True) self.show_fatal_error(f"GUI Error:\n{e}\nApp cannot start.") master.destroy() return # Configure full logger now that GUI exists self.logger = setup_logger(self.main_frame.log_text) # Ensure all components use the final logger self.config_manager.logger = self.logger self.git_commands.logger = self.logger self.profile_handler.logger = self.logger self.backup_handler.logger = self.logger self.action_handler.logger = self.logger # Initial Application State Setup self.logger.info("Application initializing...") initial_profile = self.main_frame.profile_var.get() if initial_profile: self.logger.debug(f"Initial profile: '{initial_profile}'. Loading...") # Load settings (called automatically by trace on profile_var) else: self.logger.warning("No profile selected on startup.") self._clear_and_disable_fields() # Initial state if no profile self.logger.info("Application started successfully.") def on_closing(self): """Handles the event when the user tries to close the window.""" self.logger.info("Application closing.") # Add cleanup logic if needed self.master.destroy() # --- ADDED BACK: Helper methods to get/validate paths from GUI --- def _get_and_validate_svn_path(self, operation_name="Operation"): """Retrieves and validates the SVN path from the GUI.""" # Check if main_frame and widget exist if not hasattr(self, 'main_frame') or \ not self.main_frame.winfo_exists() or \ not hasattr(self.main_frame, 'svn_path_entry'): self.logger.error(f"{operation_name}: GUI component unavailable.") # Raise error or return None? Return None to allow caller to handle. self.main_frame.show_error("Internal Error", "SVN Path widget not found.") return None svn_path_str = self.main_frame.svn_path_entry.get().strip() if not svn_path_str: self.logger.error(f"{operation_name}: SVN Path is empty.") self.main_frame.show_error("Input Error", "SVN Path cannot be empty.") return None abs_path = os.path.abspath(svn_path_str) if not os.path.isdir(abs_path): self.logger.error( f"{operation_name}: Invalid directory path: {abs_path}" ) self.main_frame.show_error( "Input Error", f"Invalid SVN path (not a directory):\n{abs_path}" ) return None self.logger.debug(f"{operation_name}: Validated SVN path: {abs_path}") return abs_path def _get_and_validate_usb_path(self, operation_name="Operation"): """Retrieves and validates the USB/Bundle Target path from the GUI.""" # Check if main_frame and widget exist if not hasattr(self, 'main_frame') or \ not self.main_frame.winfo_exists() or \ not hasattr(self.main_frame, 'usb_path_entry'): self.logger.error(f"{operation_name}: GUI component unavailable.") self.main_frame.show_error("Internal Error", "USB Path widget not found.") return None usb_path_str = self.main_frame.usb_path_entry.get().strip() if not usb_path_str: self.logger.error(f"{operation_name}: Bundle Target Dir path empty.") self.main_frame.show_error("Input Error", "Bundle Target Directory cannot be empty.") return None abs_path = os.path.abspath(usb_path_str) if not os.path.isdir(abs_path): self.logger.error( f"{operation_name}: Invalid Bundle Target directory: {abs_path}" ) self.main_frame.show_error( "Input Error", f"Invalid Bundle Target path (not a directory):\n{abs_path}" ) return None self.logger.debug(f"{operation_name}: Validated Bundle Target path: {abs_path}") return abs_path # --- END: Added back helper methods --- # --- Profile Handling Wrappers --- def load_profile_settings(self, profile_name): """Loads profile settings into GUI when profile selection changes.""" self.logger.info(f"UI Request: Load profile '{profile_name}'") if not profile_name: self._clear_and_disable_fields() return # Delegate loading to ProfileHandler profile_data = self.profile_handler.load_profile_data(profile_name) if profile_data and hasattr(self, 'main_frame'): # Update GUI fields with loaded data mf = self.main_frame mf.svn_path_entry.delete(0, tk.END) mf.svn_path_entry.insert(0, profile_data.get("svn_working_copy_path", "")) mf.usb_path_entry.delete(0, tk.END) mf.usb_path_entry.insert(0, profile_data.get("usb_drive_path", "")) mf.bundle_name_entry.delete(0, tk.END) mf.bundle_name_entry.insert(0, profile_data.get("bundle_name", "")) mf.bundle_updated_name_entry.delete(0, tk.END) mf.bundle_updated_name_entry.insert(0, profile_data.get("bundle_name_updated", "")) mf.autocommit_var.set(profile_data.get("autocommit", False)) # Bool mf.commit_message_var.set(profile_data.get("commit_message", "")) mf.autobackup_var.set(profile_data.get("autobackup", False)) # Bool mf.backup_dir_var.set(profile_data.get("backup_dir", DEFAULT_BACKUP_DIR)) mf.backup_exclude_extensions_var.set( profile_data.get("backup_exclude_extensions", ".log,.tmp") ) mf.toggle_backup_dir() # Update status indicators and dependent buttons svn_path = profile_data.get("svn_working_copy_path", "") self.update_svn_status_indicator(svn_path) # Enable general buttons self._enable_function_buttons() # Refresh tag list if repo ready repo_ready = (svn_path and os.path.isdir(svn_path) and os.path.exists(os.path.join(svn_path, ".git"))) if repo_ready: self.refresh_tag_list() # Call refresh method directly else: mf.update_tag_list([]) # Clear tags if not ready self.logger.info(f"Settings loaded successfully for '{profile_name}'.") elif not profile_data: # Profile loading failed (logged by handler) self.main_frame.show_error("Load Error", f"Could not load profile '{profile_name}'.") self._clear_and_disable_fields() else: self.logger.error("Cannot load settings: Main frame missing.") def ui_save_settings(self): """Callback for the 'Save Settings' button.""" self.logger.debug("UI Request: Save Settings button clicked.") profile = self.main_frame.profile_var.get() if not profile: self.logger.warning("Save requested but no profile selected.") self.main_frame.show_error("Save Error", "No profile selected.") return # Gather data from GUI current_data = self._get_data_from_gui() # Delegate saving to ProfileHandler success = self.profile_handler.save_profile_data(profile, current_data) if success: self.main_frame.show_info("Settings Saved", f"Settings for profile '{profile}' saved.") else: # Error message likely shown by handler or save method self.main_frame.show_error("Save Error", f"Failed to save settings for '{profile}'.") def _get_data_from_gui(self): """Helper to gather current settings from GUI widgets into a dict.""" if not hasattr(self, 'main_frame'): self.logger.error("Cannot get GUI data: Main frame missing.") return {} # Return empty dict if GUI not ready mf = self.main_frame data = { "svn_working_copy_path": mf.svn_path_entry.get(), "usb_drive_path": mf.usb_path_entry.get(), "bundle_name": mf.bundle_name_entry.get(), "bundle_name_updated": mf.bundle_updated_name_entry.get(), "autocommit": mf.autocommit_var.get(), # Gets boolean value "commit_message": mf.commit_message_var.get(), "autobackup": mf.autobackup_var.get(), # Gets boolean value "backup_dir": mf.backup_dir_var.get(), "backup_exclude_extensions": mf.backup_exclude_extensions_var.get() } return data def ui_add_profile(self): """Callback for the 'Add Profile' button.""" self.logger.debug("UI Request: Add Profile button clicked.") new_name = self.main_frame.ask_new_profile_name() if not new_name: self.logger.info("Add profile cancelled.") return new_name = new_name.strip() if not new_name: self.main_frame.show_error("Error", "Profile name cannot be empty.") return # Delegate adding logic to ProfileHandler success = self.profile_handler.add_new_profile(new_name) if success: # Update GUI dropdown and select the new profile sections = self.profile_handler.get_profile_list() self.main_frame.update_profile_dropdown(sections) self.main_frame.profile_var.set(new_name) # Triggers load via trace self.main_frame.show_info("Profile Added", f"Profile '{new_name}' created.") else: # Handler logged the reason (exists or error) # Show specific error? Handler currently doesn't return reason. self.main_frame.show_error("Error", f"Could not add profile '{new_name}'. " f"It might already exist.") def ui_remove_profile(self): """Callback for the 'Remove Profile' button.""" self.logger.debug("UI Request: Remove Profile button clicked.") profile_to_remove = self.main_frame.profile_var.get() if not profile_to_remove: self.main_frame.show_error("Error", "No profile selected.") return if profile_to_remove == DEFAULT_PROFILE: self.main_frame.show_error("Error", f"Cannot remove '{DEFAULT_PROFILE}'.") return # Confirm with user confirm_msg = f"Remove profile '{profile_to_remove}'?" if self.main_frame.ask_yes_no("Remove Profile", confirm_msg): # Delegate removal to ProfileHandler success = self.profile_handler.remove_existing_profile(profile_to_remove) if success: sections = self.profile_handler.get_profile_list() # Update dropdown, selection changes trigger load self.main_frame.update_profile_dropdown(sections) self.main_frame.show_info("Profile Removed", f"Profile '{profile_to_remove}' removed.") else: # Handler logged the reason self.main_frame.show_error("Error", f"Failed to remove '{profile_to_remove}'.") else: self.logger.info("Profile removal cancelled.") # --- GUI Interaction Wrappers --- def browse_folder(self, entry_widget): """Opens folder dialog to update an entry widget.""" self.logger.debug("Browse folder requested.") current = entry_widget.get() initial = current if os.path.isdir(current) else os.path.expanduser("~") directory = filedialog.askdirectory(initialdir=initial, title="Select Directory", parent=self.master) if directory: self.logger.debug(f"Selected: {directory}") entry_widget.delete(0, tk.END) entry_widget.insert(0, directory) # Trigger status update if SVN path changed if entry_widget == self.main_frame.svn_path_entry: self.update_svn_status_indicator(directory) else: self.logger.debug("Browse cancelled.") def update_svn_status_indicator(self, svn_path): """Checks repo status and updates all dependent GUI widget states.""" is_valid = bool(svn_path and os.path.isdir(svn_path)) is_ready = is_valid and os.path.exists(os.path.join(svn_path, ".git")) self.logger.debug(f"Updating status indicators for '{svn_path}'. " f"Valid:{is_valid}, Ready:{is_ready}") if hasattr(self, 'main_frame'): mf = self.main_frame # Update indicator & Prepare button via GUI method mf.update_svn_indicator(is_ready) # Determine states for other widgets gitignore_state = tk.NORMAL if is_valid else tk.DISABLED commit_tag_state = tk.NORMAL if is_ready else tk.DISABLED # Apply states if hasattr(mf, 'edit_gitignore_button'): mf.edit_gitignore_button.config(state=gitignore_state) if hasattr(mf, 'commit_message_entry'): mf.commit_message_entry.config(state=commit_tag_state) if hasattr(mf, 'autocommit_checkbox'): mf.autocommit_checkbox.config(state=commit_tag_state) if hasattr(mf, 'commit_button'): # Manual commit button mf.commit_button.config(state=commit_tag_state) if hasattr(mf, 'refresh_tags_button'): mf.refresh_tags_button.config(state=commit_tag_state) if hasattr(mf, 'create_tag_button'): mf.create_tag_button.config(state=commit_tag_state) if hasattr(mf, 'checkout_tag_button'): mf.checkout_tag_button.config(state=commit_tag_state) def open_gitignore_editor(self): """Opens the modal editor window for .gitignore.""" self.logger.info("--- Action Triggered: Edit .gitignore ---") svn_path = self._get_and_validate_svn_path("Edit .gitignore") if not svn_path: return gitignore_path = os.path.join(svn_path, ".gitignore") self.logger.debug(f"Target .gitignore path: {gitignore_path}") try: # Create and run the modal editor editor = GitignoreEditorWindow(self.master, gitignore_path, self.logger) self.logger.debug("Gitignore editor finished.") # After window closes except Exception as e: self.logger.exception(f"Error opening .gitignore editor: {e}") self.main_frame.show_error("Editor Error", f"Could not open editor:\n{e}") # --- Core Action Wrappers (GUI Callbacks) --- def ui_prepare_svn(self): """Callback for 'Prepare SVN Repo' button.""" self.logger.info("--- Action Triggered: Prepare SVN Repo ---") svn_path = self._get_and_validate_svn_path("Prepare SVN") if not svn_path: return # Save settings before action if not self.ui_save_settings(): self.logger.warning("Prepare SVN: Failed save settings first.") # Ask user? # Delegate execution to ActionHandler try: self.action_handler.execute_prepare_repo(svn_path) self.main_frame.show_info("Success", "Repository prepared.") # Update GUI state after successful preparation self.update_svn_status_indicator(svn_path) except ValueError as e: # Catch specific "already prepared" error self.logger.info(f"Prepare Repo info: {e}") self.main_frame.show_info("Info", str(e)) self.update_svn_status_indicator(svn_path) # Ensure UI reflects state except (GitCommandError, IOError) as e: self.logger.error(f"Error preparing repository: {e}") self.main_frame.show_error("Error", f"Failed prepare:\n{e}") self.update_svn_status_indicator(svn_path) except Exception as e: self.logger.exception(f"Unexpected error during preparation: {e}") self.main_frame.show_error("Error", f"Unexpected error:\n{e}") self.update_svn_status_indicator(svn_path) def ui_create_bundle(self): """Callback for 'Create Bundle' button.""" self.logger.info("--- Action Triggered: Create Git Bundle ---") profile = self.main_frame.profile_var.get() if not profile: self.main_frame.show_error("Error", "No profile."); return # Validate inputs svn_path = self._get_and_validate_svn_path("Create Bundle") if not svn_path: return usb_path = self._get_and_validate_usb_path("Create Bundle") if not usb_path: return bundle_name = self.main_frame.bundle_name_entry.get().strip() if not bundle_name: self.main_frame.show_error("Input Error", "Bundle name empty."); return # Ensure .bundle extension if not bundle_name.lower().endswith(".bundle"): bundle_name += ".bundle" self.main_frame.bundle_name_entry.delete(0, tk.END) self.main_frame.bundle_name_entry.insert(0, bundle_name) bundle_full_path = os.path.join(usb_path, bundle_name) # Get settings needed by action handler current_settings = self._get_data_from_gui() backup_needed = current_settings.get("autobackup", False) commit_needed = current_settings.get("autocommit", False) commit_msg = current_settings.get("commit_message", "") backup_dir = current_settings.get("backup_dir", "") try: excluded_ext, excluded_dir = self._parse_exclusions(profile) except ValueError as e: # Catch parsing errors self.main_frame.show_error("Config Error", str(e)); return # Save settings before action if not self.ui_save_settings(): self.logger.warning("Create Bundle: Failed save settings first.") # Ask user? # Delegate execution to ActionHandler try: created_path = self.action_handler.execute_create_bundle( svn_path, bundle_full_path, profile, backup_needed, backup_dir, commit_needed, commit_msg, excluded_ext, excluded_dir ) if created_path: self.main_frame.show_info("Success", f"Bundle created:\n{created_path}") else: # Non-fatal issue (e.g., empty bundle) self.main_frame.show_warning("Info", "Bundle empty or not created.") except Exception as e: # Handle errors from backup, commit, or bundle creation self.logger.error(f"Create bundle process error: {e}", exc_info=True) # Provide specific message based on exception type if possible if isinstance(e, IOError) and "backup" in str(e).lower(): self.main_frame.show_error("Backup Error", f"Backup failed:\n{e}") elif isinstance(e, GitCommandError) and "commit" in str(e).lower(): self.main_frame.show_error("Commit Error", f"Commit failed:\n{e}") elif isinstance(e, GitCommandError) and "bundle" in str(e).lower(): self.main_frame.show_error("Bundle Error", f"Bundle creation failed:\n{e}") else: # General/unexpected error self.main_frame.show_error("Error", f"Failed:\n{e}") def ui_fetch_bundle(self): """Callback for 'Fetch Bundle' button.""" self.logger.info("--- Action Triggered: Fetch from Git Bundle ---") profile = self.main_frame.profile_var.get() if not profile: self.main_frame.show_error("Error", "No profile."); return # Validate inputs svn_path = self._get_and_validate_svn_path("Fetch Bundle") if not svn_path: return usb_path = self._get_and_validate_usb_path("Fetch Bundle") if not usb_path: return bundle_name = self.main_frame.bundle_updated_name_entry.get().strip() if not bundle_name: self.main_frame.show_error("Input Error", "Fetch name empty."); return bundle_full_path = os.path.join(usb_path, bundle_name) if not os.path.isfile(bundle_full_path): self.main_frame.show_error("Error", f"Bundle not found:\n{bundle_full_path}"); return # Get settings needed by action handler current_settings = self._get_data_from_gui() backup_needed = current_settings.get("autobackup", False) backup_dir = current_settings.get("backup_dir", "") try: excluded_ext, excluded_dir = self._parse_exclusions(profile) except ValueError as e: self.main_frame.show_error("Config Error", str(e)); return # Save settings before action if not self.ui_save_settings(): self.logger.warning("Fetch Bundle: Failed save settings first.") # Ask user? # Delegate execution to ActionHandler try: self.action_handler.execute_fetch_bundle( svn_path, bundle_full_path, profile, backup_needed, backup_dir, excluded_ext, excluded_dir ) # Show generic success, conflicts handled by error message below self.main_frame.show_info("Fetch Complete", f"Fetch complete.\nCheck logs for status.") except GitCommandError as e: # Handle specific Git errors like merge conflicts self.logger.error(f"Fetch/merge error: {e}", exc_info=False) if "merge conflict" in str(e).lower(): self.main_frame.show_error( "Merge Conflict", f"Merge conflict occurred.\nResolve manually in:\n{svn_path}" f"\nThen run 'git add .' and 'git commit'." ) else: self.main_frame.show_error("Fetch/Merge Error", f"Failed:\n{e}") except Exception as e: # Handle other errors (backup, unexpected) self.logger.error(f"Error during fetch process: {e}", exc_info=True) if isinstance(e, IOError) and "backup" in str(e).lower(): self.main_frame.show_error("Backup Error", f"Backup failed:\n{e}") else: self.main_frame.show_error("Error", f"Fetch failed:\n{e}") def ui_manual_backup(self): """Callback for 'Backup Now' button.""" self.logger.info("--- Action Triggered: Manual Backup ---") profile = self.main_frame.profile_var.get() if not profile: self.main_frame.show_error("Error", "No profile."); return svn_path = self._get_and_validate_svn_path(f"Manual Backup ({profile})") if not svn_path: return backup_dir = self.main_frame.backup_dir_var.get().strip() if not backup_dir: self.main_frame.show_error("Error", "Backup dir empty."); return # Check/create backup dir here in the UI layer before calling handler? if not os.path.isdir(backup_dir): if self.main_frame.ask_yes_no("Create Dir?", f"Create dir:\n{backup_dir}?"): try: os.makedirs(backup_dir, exist_ok=True) except OSError as e: self.main_frame.show_error("Error", f"Cannot create:\n{e}"); return else: return # User cancelled creation # Parse exclusions before calling handler try: excluded_ext, excluded_dir = self._parse_exclusions(profile) except ValueError as e: self.main_frame.show_error("Config Error", str(e)); return # Save settings first if not self.ui_save_settings(): if not self.main_frame.ask_yes_no("Warning", "Could not save settings.\nContinue backup anyway?"): self.logger.warning("Manual backup aborted."); return # Delegate to BackupHandler try: backup_path = self.backup_handler.create_zip_backup( svn_path, backup_dir, profile, excluded_ext, excluded_dir ) # Check if backup_path is returned (success) if backup_path: self.main_frame.show_info("Backup Complete", f"Backup created:\n{backup_path}") else: # Should not happen if exceptions are raised correctly self.main_frame.show_error("Backup Error", "Backup failed (unknown reason).") except Exception as e: self.logger.error(f"Manual backup failed: {e}", exc_info=True) self.main_frame.show_error("Backup Error", f"Failed:\n{e}") def ui_manual_commit(self): """Callback for the 'Commit' button.""" self.logger.info("--- Action Triggered: Manual Commit ---") svn_path = self._get_and_validate_svn_path("Manual Commit") if not svn_path: return commit_msg = self.main_frame.commit_message_var.get().strip() if not commit_msg: self.logger.warning("Manual commit blocked: Message empty.") self.main_frame.show_error("Commit Error", "Commit message empty.") return # Save settings first? Optional for commit. if not self.ui_save_settings(): self.logger.warning("Manual Commit: Could not save settings.") # Ask user? # Delegate commit execution to ActionHandler try: commit_made = self.action_handler.execute_manual_commit( svn_path, commit_msg ) if commit_made: self.main_frame.show_info("Commit Successful", "Changes committed.") # Clear message field after success? # self.main_frame.commit_message_var.set("") else: self.main_frame.show_info("Nothing to Commit", "No changes detected.") except (GitCommandError, ValueError) as e: self.logger.error(f"Manual commit failed: {e}") self.main_frame.show_error("Commit Error", f"Failed:\n{e}") except Exception as e: self.logger.exception(f"Unexpected error during manual commit: {e}") self.main_frame.show_error("Error", f"Unexpected commit error:\n{e}") def ui_create_tag(self): """Callback for 'Create Tag' button.""" self.logger.info("--- Action Triggered: Create Tag ---") svn_path = self._get_and_validate_svn_path("Create Tag") if not svn_path: return profile = self.main_frame.profile_var.get() if not profile: self.main_frame.show_error("Error", "No profile."); return # Get commit message from GUI (needed for potential pre-commit) commit_msg = self.main_frame.commit_message_var.get().strip() # Save settings before action if not self.ui_save_settings(): self.logger.warning("Create Tag: Could not save settings first.") # Ask user? # Open Dialog first to get tag name/message self.logger.debug("Opening create tag dialog...") dialog = CreateTagDialog(self.master) tag_info = dialog.result # Returns (tag_name, tag_message) or None if not tag_info: self.logger.info("Tag creation cancelled by user in dialog.") return # User cancelled dialog tag_name, tag_message = tag_info self.logger.info(f"User provided tag: '{tag_name}', msg: '{tag_message}'") # Delegate Execution (including potential pre-commit) to ActionHandler try: success = self.action_handler.execute_create_tag( svn_path, commit_msg, tag_name, tag_message ) # ActionHandler raises errors if commit/tag fail if success: # Should always be true if no exception self.logger.info(f"Tag '{tag_name}' created successfully.") self.main_frame.show_info("Success", f"Tag '{tag_name}' created.") self.refresh_tag_list() # Update list after successful creation except ValueError as e: # Catch specific errors like "commit message required" self.logger.error(f"Tag creation validation failed: {e}") self.main_frame.show_error("Tag Error", str(e)) except GitCommandError as e: # Catch Git command errors (commit or tag) self.logger.error(f"Tag creation failed (Git Error): {e}") self.main_frame.show_error("Tag Error", f"Git command failed:\n{e}") except Exception as e: # Catch unexpected errors self.logger.exception(f"Unexpected error creating tag: {e}") self.main_frame.show_error("Error", f"Unexpected error:\n{e}") def ui_checkout_tag(self): """Callback for 'Checkout Selected Tag' button.""" self.logger.info("--- Action Triggered: Checkout Tag ---") svn_path = self._get_and_validate_svn_path("Checkout Tag") if not svn_path: return selected_tag = self.main_frame.get_selected_tag() # Gets name if not selected_tag: self.main_frame.show_error("Selection Error", "Select a tag."); return self.logger.info(f"Attempting checkout for tag: {selected_tag}") # Confirmation dialog first confirm_msg = (f"Checkout tag '{selected_tag}'?\n\n" f"WARNINGS:\n- Files WILL BE OVERWRITTEN.\n- NO backup created.\n" f"- Enters 'detached HEAD' state.") if not self.main_frame.ask_yes_no("Confirm Checkout", confirm_msg): self.logger.info("Tag checkout cancelled."); return # Save settings before action (optional) if not self.ui_save_settings(): self.logger.warning("Checkout Tag: Could not save settings.") # Delegate execution to ActionHandler try: success = self.action_handler.execute_checkout_tag(svn_path, selected_tag) if success: self.main_frame.show_info("Checkout Successful", f"Checked out tag '{selected_tag}'.\n\nNOTE: In 'detached HEAD'.") # TODO: Update UI state for detached HEAD? except ValueError as e: # Catch specific errors like "uncommitted changes" self.logger.error(f"Checkout blocked: {e}") self.main_frame.show_error("Checkout Blocked", str(e)) except GitCommandError as e: # Catch Git command errors self.logger.error(f"Failed checkout tag '{selected_tag}': {e}") self.main_frame.show_error("Checkout Error", f"Could not checkout:\n{e}") except Exception as e: # Catch unexpected errors self.logger.exception(f"Unexpected checkout error: {e}") self.main_frame.show_error("Error", f"Unexpected checkout error:\n{e}") # --- Tag Management (Direct Call/Wrapper) --- def refresh_tag_list(self): """Refreshes tag list in GUI. Called by button or after profile load.""" self.logger.info("--- Action: Refresh Tag List ---") svn_path = self._get_and_validate_svn_path("Refresh Tags") if not svn_path: if hasattr(self, 'main_frame'): self.main_frame.update_tag_list([]) return # Check repo readiness if not os.path.exists(os.path.join(svn_path, ".git")): self.logger.warning("Refresh Tags: Repo not prepared.") if hasattr(self, 'main_frame'): self.main_frame.update_tag_list([]) return # Fetch tags and update GUI try: tags_data = self.git_commands.list_tags(svn_path) # List of (name, subject) if hasattr(self, 'main_frame'): self.main_frame.update_tag_list(tags_data) self.logger.info(f"Tag list updated ({len(tags_data)} tags).") except Exception as e: self.logger.error(f"Failed refresh tags: {e}", exc_info=True) self.main_frame.show_error("Error", f"Could not refresh tags:\n{e}") if hasattr(self, 'main_frame'): self.main_frame.update_tag_list([]) # --- GUI State Utilities --- def _clear_and_disable_fields(self): """Clears relevant GUI fields and disables most buttons.""" if hasattr(self, 'main_frame'): mf = self.main_frame # Clear Repo frame fields mf.svn_path_entry.delete(0, tk.END) mf.usb_path_entry.delete(0, tk.END) mf.bundle_name_entry.delete(0, tk.END) mf.bundle_updated_name_entry.delete(0, tk.END) # Clear Commit/Tag frame fields mf.commit_message_var.set("") mf.autocommit_var.set(False) mf.update_tag_list([]) # Clear tag listbox # Reset indicator and dependent buttons (handles state-based disabling) self.update_svn_status_indicator("") # Disable general action buttons explicitly self._disable_general_buttons() self.logger.debug("GUI fields cleared/reset. Buttons disabled.") def _disable_general_buttons(self): """Disables buttons generally requiring only a loaded profile.""" if hasattr(self, 'main_frame'): # List of general action button attribute names in main_frame button_names = [ 'create_bundle_button', 'fetch_bundle_button', 'manual_backup_button', 'save_settings_button' ] for name in button_names: button = getattr(self.main_frame, name, None) if button: button.config(state=tk.DISABLED) def _enable_function_buttons(self): """ Enables general action buttons. State-dependent buttons rely on update_svn_status_indicator for their state. """ if hasattr(self, 'main_frame'): general_state = tk.NORMAL # List of general action button attribute names button_names = [ 'create_bundle_button', 'fetch_bundle_button', 'manual_backup_button', 'save_settings_button' ] for name in button_names: button = getattr(self.main_frame, name, None) if button: button.config(state=general_state) # Ensure state-dependent buttons reflect the current path status # This updates Prepare, EditGitignore, Commit/Tag widget states current_svn_path = "" if hasattr(self.main_frame, 'svn_path_entry'): current_svn_path = self.main_frame.svn_path_entry.get() self.update_svn_status_indicator(current_svn_path) self.logger.debug("General buttons enabled. State buttons updated.") def show_fatal_error(self, message): """Shows a fatal error message.""" try: # Determine parent window safely parent = None if hasattr(self, 'master') and self.master and self.master.winfo_exists(): parent = self.master messagebox.showerror("Fatal Error", message, parent=parent) except tk.TclError: # Fallback if GUI is not ready or fails print(f"FATAL ERROR: {message}") except Exception as e: # Log error showing the message box itself print(f"FATAL ERROR (and GUI error: {e}): {message}") # --- Application Entry Point --- def main(): """Main function: Creates Tkinter root and runs the application.""" root = tk.Tk() # Adjust min size for the new layout root.minsize(700, 700) # Adjusted min height app = None # Initialize app variable try: app = GitSvnSyncApp(root) # Start main loop only if initialization likely succeeded if hasattr(app, 'main_frame') and app.main_frame: root.mainloop() else: # Initialization failed before GUI setup could complete print("Application initialization failed, exiting.") # Ensure window closes if init failed but window was created if root and root.winfo_exists(): root.destroy() except Exception as e: # Catch-all for unexpected errors during startup or main loop logging.exception("Fatal error during application startup or main loop.") # Try showing message box, fallback to print try: parent_window = root if root and root.winfo_exists() else None messagebox.showerror("Fatal Error", f"Application failed unexpectedly:\n{e}", parent=parent_window) except Exception as msg_e: print(f"FATAL ERROR (GUI error: {msg_e}): App failed:\n{e}") finally: # Log application exit regardless of success or failure logging.info("Application exiting.") if __name__ == "__main__": # Set up basic logging configuration immediately at startup log_format = "%(asctime)s - %(levelname)s - [%(module)s:%(funcName)s] - %(message)s" logging.basicConfig(level=logging.INFO, format=log_format) main()