womm-cli 4.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- womm/__init__.py +53 -0
- womm/__main__.py +48 -0
- womm/_version.py +10 -0
- womm/assets/copier/meta/copier.yml +15 -0
- womm/assets/copier/meta/template/README.md.jinja +32 -0
- womm/assets/copier/meta/template/copier.yml.jinja +13 -0
- womm/assets/copier/meta/template/template/.gitkeep +0 -0
- womm/assets/copier/official/javascript/copier.yml +104 -0
- womm/assets/copier/official/javascript/template/.gitignore.jinja +35 -0
- womm/assets/copier/official/javascript/template/.nvmrc.jinja +1 -0
- womm/assets/copier/official/javascript/template/.prettierignore.jinja +10 -0
- womm/assets/copier/official/javascript/template/README.md.jinja +81 -0
- womm/assets/copier/official/javascript/template/biome.json.jinja +54 -0
- womm/assets/copier/official/javascript/template/eslint.config.mjs.jinja +51 -0
- womm/assets/copier/official/javascript/template/index.html.jinja +12 -0
- womm/assets/copier/official/javascript/template/package.json.jinja +88 -0
- womm/assets/copier/official/javascript/template/prettier.config.mjs.jinja +8 -0
- womm/assets/copier/official/javascript/template/src/App.jsx.jinja +10 -0
- womm/assets/copier/official/javascript/template/src/App.tsx.jinja +10 -0
- womm/assets/copier/official/javascript/template/src/App.vue.jinja +18 -0
- womm/assets/copier/official/javascript/template/src/index.jsx.jinja +10 -0
- womm/assets/copier/official/javascript/template/src/index.tsx.jinja +11 -0
- womm/assets/copier/official/javascript/template/src/main.js.jinja +21 -0
- womm/assets/copier/official/javascript/template/src/main.ts.jinja +21 -0
- womm/assets/copier/official/javascript/template/tsconfig.json.jinja +35 -0
- womm/assets/copier/official/javascript/template/vite.config.mjs.jinja +10 -0
- womm/assets/copier/official/javascript/template/{% if with_ci %}.github{% endif %}/workflows/ci.yml.jinja +63 -0
- womm/assets/copier/official/javascript/template/{% if with_tests %}tests{% endif %}/smoke.test.js.jinja +12 -0
- womm/assets/copier/official/javascript/template/{% if with_tests %}tests{% endif %}/smoke.test.ts.jinja +12 -0
- womm/assets/copier/official/javascript/template/{% if with_vscode %}.vscode{% endif %}/extensions.json.jinja +4 -0
- womm/assets/copier/official/javascript/template/{% if with_vscode %}.vscode{% endif %}/settings.json.jinja +27 -0
- womm/assets/copier/official/python/copier.yml +107 -0
- womm/assets/copier/official/python/template/.gitignore.jinja +40 -0
- womm/assets/copier/official/python/template/.pre-commit-config.yaml.jinja +19 -0
- womm/assets/copier/official/python/template/.python-version.jinja +1 -0
- womm/assets/copier/official/python/template/README.md.jinja +83 -0
- womm/assets/copier/official/python/template/pyproject.toml.jinja +114 -0
- womm/assets/copier/official/python/template/{% if framework == 'django' %}manage.py{% endif %}.jinja +23 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/__init__.py.jinja +3 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/asgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/__init__.py.jinja +0 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/apps.py.jinja +10 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/models.py.jinja +1 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/core/views.py.jinja +8 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/py.typed +0 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/settings.py.jinja +81 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/urls.py.jinja +11 -0
- womm/assets/copier/official/python/template/{% if not use_src_layout %}{{ package_name }}{% endif %}/wsgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/__init__.py.jinja +3 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/asgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/__init__.py.jinja +0 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/apps.py.jinja +10 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/models.py.jinja +1 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/core/views.py.jinja +8 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/py.typed +0 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/settings.py.jinja +81 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/urls.py.jinja +11 -0
- womm/assets/copier/official/python/template/{% if use_src_layout %}src{% endif %}/{{ package_name }}/wsgi.py.jinja +9 -0
- womm/assets/copier/official/python/template/{% if with_ci %}.github{% endif %}/workflows/ci.yml.jinja +78 -0
- womm/assets/copier/official/python/template/{% if with_tests %}tests{% endif %}/test_smoke.py.jinja +16 -0
- womm/assets/copier/official/python/template/{% if with_vscode %}.vscode{% endif %}/extensions.json.jinja +8 -0
- womm/assets/copier/official/python/template/{% if with_vscode %}.vscode{% endif %}/settings.json.jinja +28 -0
- womm/bin/refresh_env.cmd +130 -0
- womm/cli.py +111 -0
- womm/commands/__init__.py +30 -0
- womm/commands/core/__init__.py +29 -0
- womm/commands/core/doctor.py +52 -0
- womm/commands/core/path.py +337 -0
- womm/commands/project/__init__.py +31 -0
- womm/commands/project/create.py +128 -0
- womm/commands/project/setup.py +438 -0
- womm/commands/project/template.py +160 -0
- womm/commands/system/__init__.py +31 -0
- womm/commands/system/context/__init__.py +82 -0
- womm/commands/system/context/backup.py +344 -0
- womm/commands/system/context/inventory.py +111 -0
- womm/commands/system/context/registration.py +290 -0
- womm/commands/system/deps.py +165 -0
- womm/commands/system/system.py +130 -0
- womm/exceptions/__init__.py +69 -0
- womm/exceptions/common/__init__.py +55 -0
- womm/exceptions/common/command_service.py +91 -0
- womm/exceptions/common/file_service.py +60 -0
- womm/exceptions/common/security_service.py +44 -0
- womm/exceptions/common/validation_service.py +70 -0
- womm/exceptions/context/__init__.py +27 -0
- womm/exceptions/context/context_service.py +55 -0
- womm/exceptions/project/__init__.py +29 -0
- womm/exceptions/project/project_service.py +59 -0
- womm/exceptions/system/__init__.py +25 -0
- womm/exceptions/system/system_service.py +53 -0
- womm/interfaces/__init__.py +71 -0
- womm/interfaces/context/__init__.py +34 -0
- womm/interfaces/context/menu_interface.py +686 -0
- womm/interfaces/context/registry_interface.py +562 -0
- womm/interfaces/context/script_detector_interface.py +208 -0
- womm/interfaces/context/script_registrar.py +264 -0
- womm/interfaces/core/__init__.py +26 -0
- womm/interfaces/core/doctor_interface.py +102 -0
- womm/interfaces/dependencies/__init__.py +28 -0
- womm/interfaces/dependencies/deps_interface.py +160 -0
- womm/interfaces/project/__init__.py +36 -0
- womm/interfaces/project/create_interface.py +162 -0
- womm/interfaces/project/detection_interface.py +181 -0
- womm/interfaces/project/manager_interface.py +99 -0
- womm/interfaces/project/setup_interface.py +477 -0
- womm/interfaces/project/template_store_interface.py +196 -0
- womm/interfaces/system/__init__.py +32 -0
- womm/interfaces/system/detector_interface.py +84 -0
- womm/interfaces/system/environment_interface.py +110 -0
- womm/interfaces/system/path_interface.py +570 -0
- womm/services/__init__.py +70 -0
- womm/services/common/__init__.py +33 -0
- womm/services/common/base_validation_service.py +450 -0
- womm/services/common/command_runner_service.py +647 -0
- womm/services/common/file_scanner_service.py +483 -0
- womm/services/common/security_validator_service.py +348 -0
- womm/services/context/__init__.py +37 -0
- womm/services/context/backup_entries.py +148 -0
- womm/services/context/parameters.py +515 -0
- womm/services/context/registry_paths.py +56 -0
- womm/services/context/registry_service.py +573 -0
- womm/services/context/validation_service.py +691 -0
- womm/services/dependencies/__init__.py +29 -0
- womm/services/dependencies/probe.py +102 -0
- womm/services/project/__init__.py +48 -0
- womm/services/project/copier_project_creation_service.py +111 -0
- womm/services/project/destination_guard.py +96 -0
- womm/services/project/detection_service.py +354 -0
- womm/services/project/env_utils.py +333 -0
- womm/services/project/javascript_environment_service.py +348 -0
- womm/services/project/python_environment_service.py +245 -0
- womm/services/project/setup_profile_resolver.py +146 -0
- womm/services/project/template_store_service.py +344 -0
- womm/services/project/validation_service.py +418 -0
- womm/services/system/__init__.py +32 -0
- womm/services/system/detector_service.py +704 -0
- womm/services/system/environment_service.py +494 -0
- womm/services/system/path_service.py +642 -0
- womm/shared/__init__.py +30 -0
- womm/shared/configs/__init__.py +51 -0
- womm/shared/configs/context/__init__.py +43 -0
- womm/shared/configs/context/context_config.py +125 -0
- womm/shared/configs/context/context_file_types_config.py +159 -0
- womm/shared/configs/context/context_limits_config.py +187 -0
- womm/shared/configs/context/context_paths_config.py +115 -0
- womm/shared/configs/context/context_types_config.py +65 -0
- womm/shared/configs/context/script_config.py +219 -0
- womm/shared/configs/dependencies/__init__.py +32 -0
- womm/shared/configs/dependencies/runtime_config.py +46 -0
- womm/shared/configs/dependencies/runtime_package_manager_config.py +48 -0
- womm/shared/configs/logging_config.py +89 -0
- womm/shared/configs/project/__init__.py +33 -0
- womm/shared/configs/project/project_config.py +109 -0
- womm/shared/configs/project/project_structure_config.py +88 -0
- womm/shared/configs/project/python_project_config.py +165 -0
- womm/shared/configs/security/__init__.py +26 -0
- womm/shared/configs/security/security_patterns_config.py +242 -0
- womm/shared/configs/system/__init__.py +28 -0
- womm/shared/configs/system/system_detector_config.py +210 -0
- womm/shared/configs/system/system_environment_config.py +101 -0
- womm/shared/models/__init__.py +13 -0
- womm/shared/models/template_source.py +65 -0
- womm/shared/paths.py +192 -0
- womm/shared/results/__init__.py +138 -0
- womm/shared/results/base.py +85 -0
- womm/shared/results/command_results.py +61 -0
- womm/shared/results/context_results.py +345 -0
- womm/shared/results/dependency_results.py +110 -0
- womm/shared/results/doctor_results.py +41 -0
- womm/shared/results/file_results.py +97 -0
- womm/shared/results/project_results.py +163 -0
- womm/shared/results/security_results.py +128 -0
- womm/shared/results/system_results.py +268 -0
- womm/shared/results/template_results.py +43 -0
- womm/shared/runtime.py +36 -0
- womm/ui/__init__.py +31 -0
- womm/ui/common/__init__.py +39 -0
- womm/ui/common/interactive_menu.py +246 -0
- womm/ui/common/logging.py +184 -0
- womm/ui/common/prompts.py +93 -0
- womm/ui/context/__init__.py +31 -0
- womm/ui/context/display.py +485 -0
- womm/ui/context/menu_display.py +189 -0
- womm/ui/context/wizard.py +557 -0
- womm/ui/project/__init__.py +42 -0
- womm/ui/project/create/create_completion_summaries.py +55 -0
- womm/ui/project/project_wizard.py +174 -0
- womm/ui/project/setup/setup_completion_summaries.py +111 -0
- womm/ui/project/templates/template_store_display.py +128 -0
- womm/ui/system/__init__.py +60 -0
- womm/ui/system/display.py +531 -0
- womm/ui/system/path_display.py +387 -0
- womm/utils/__init__.py +23 -0
- womm/utils/common/__init__.py +49 -0
- womm/utils/common/file_scanner_utils.py +110 -0
- womm/utils/common/path_resolver_utils.py +127 -0
- womm/utils/common/safe_fs_utils.py +135 -0
- womm/utils/context/__init__.py +54 -0
- womm/utils/context/core_utils.py +345 -0
- womm/utils/context/icon_utils.py +259 -0
- womm/utils/project/__init__.py +106 -0
- womm/utils/project/asset_utils.py +154 -0
- womm/utils/project/core_utils.py +391 -0
- womm/utils/project/file_utils.py +494 -0
- womm/utils/project/platform_utils.py +170 -0
- womm/utils/project/validation_utils.py +273 -0
- womm/utils/security/__init__.py +46 -0
- womm/utils/security/security_validation_utils.py +258 -0
- womm/utils/system/__init__.py +69 -0
- womm/utils/system/detector_utils.py +299 -0
- womm/utils/system/environment_utils.py +172 -0
- womm/utils/system/path_utils.py +101 -0
- womm_cli-4.0.0.dist-info/METADATA +203 -0
- womm_cli-4.0.0.dist-info/RECORD +218 -0
- womm_cli-4.0.0.dist-info/WHEEL +4 -0
- womm_cli-4.0.0.dist-info/entry_points.txt +2 -0
- womm_cli-4.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# ///////////////////////////////////////////////////////////////
|
|
3
|
+
# CONTEXT REGISTRY INTERFACE - Context Menu Backup Management
|
|
4
|
+
# Project: works-on-my-machine
|
|
5
|
+
# ///////////////////////////////////////////////////////////////
|
|
6
|
+
|
|
7
|
+
"""
|
|
8
|
+
Backup manager for context menu operations.
|
|
9
|
+
|
|
10
|
+
This module provides comprehensive backup management functionality
|
|
11
|
+
for Windows context menu entries, including creation, validation,
|
|
12
|
+
listing, and cleanup of backup files.
|
|
13
|
+
|
|
14
|
+
This interface never raises: every public method returns a typed Result.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
# ///////////////////////////////////////////////////////////////
|
|
20
|
+
# IMPORTS
|
|
21
|
+
# ///////////////////////////////////////////////////////////////
|
|
22
|
+
# Standard library imports
|
|
23
|
+
import json
|
|
24
|
+
import logging
|
|
25
|
+
import shutil
|
|
26
|
+
from datetime import datetime, timedelta
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
# Local imports
|
|
30
|
+
from ...shared.configs.context import ContextTypesConfig
|
|
31
|
+
from ...shared.paths import registry_backups_dir
|
|
32
|
+
from ...shared.results import (
|
|
33
|
+
BackupCleanupResult,
|
|
34
|
+
BackupDataResult,
|
|
35
|
+
BackupFileInfo,
|
|
36
|
+
BackupFileListResult,
|
|
37
|
+
BackupFileResult,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# ///////////////////////////////////////////////////////////////
|
|
41
|
+
# MAIN CLASS
|
|
42
|
+
# ///////////////////////////////////////////////////////////////
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ContextRegistryInterface:
|
|
46
|
+
"""Manages context menu backup operations."""
|
|
47
|
+
|
|
48
|
+
# Backup file format version
|
|
49
|
+
BACKUP_VERSION = "1.0"
|
|
50
|
+
|
|
51
|
+
BACKUP_REQUIRED_KEYS = ("metadata", "entries")
|
|
52
|
+
BACKUP_REQUIRED_METADATA = ("version", "timestamp", "total_entries")
|
|
53
|
+
|
|
54
|
+
# Maximum number of backup files to keep
|
|
55
|
+
MAX_BACKUP_FILES = 10
|
|
56
|
+
|
|
57
|
+
# Backup file retention period (days)
|
|
58
|
+
BACKUP_RETENTION_DAYS = 30
|
|
59
|
+
|
|
60
|
+
def __init__(self):
|
|
61
|
+
"""Initialize the backup manager."""
|
|
62
|
+
self.logger = logging.getLogger(__name__)
|
|
63
|
+
self.backup_dir = self.get_backup_directory()
|
|
64
|
+
|
|
65
|
+
# ///////////////////////////////////////////////////////////////
|
|
66
|
+
# PUBLIC METHODS
|
|
67
|
+
# ///////////////////////////////////////////////////////////////
|
|
68
|
+
|
|
69
|
+
def get_backup_directory(self) -> Path:
|
|
70
|
+
"""
|
|
71
|
+
Get the backup directory path, creating it if needed.
|
|
72
|
+
|
|
73
|
+
Registry backups are user data: they live under ``~/.womm/backups/
|
|
74
|
+
registry``. Falls back to the current directory only when that
|
|
75
|
+
location is unwritable; never raises.
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
return registry_backups_dir()
|
|
79
|
+
except OSError as e:
|
|
80
|
+
self.logger.warning(f"Could not access WOMM backup directory: {e}")
|
|
81
|
+
|
|
82
|
+
return Path(".")
|
|
83
|
+
|
|
84
|
+
def create_backup_file(
|
|
85
|
+
self,
|
|
86
|
+
entries: dict,
|
|
87
|
+
custom_filename: str | None = None,
|
|
88
|
+
add_timestamp: bool = True,
|
|
89
|
+
) -> BackupFileResult:
|
|
90
|
+
"""
|
|
91
|
+
Create a backup file with context menu entries.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
entries: Dictionary containing context menu entries
|
|
95
|
+
custom_filename: Optional custom filename (without extension)
|
|
96
|
+
add_timestamp: Whether to add timestamp to filename
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
BackupFileResult: written path and metadata; failure carries the error.
|
|
100
|
+
"""
|
|
101
|
+
if not isinstance(entries, dict):
|
|
102
|
+
return BackupFileResult(
|
|
103
|
+
success=False,
|
|
104
|
+
error=f"Entries must be a dictionary, got {type(entries).__name__}",
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# Generate filename
|
|
108
|
+
base_name = custom_filename or "context_menu_backup"
|
|
109
|
+
|
|
110
|
+
if add_timestamp:
|
|
111
|
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
112
|
+
filename = f"{base_name}_{timestamp}.json"
|
|
113
|
+
else:
|
|
114
|
+
filename = f"{base_name}.json"
|
|
115
|
+
|
|
116
|
+
filepath = self.backup_dir / filename
|
|
117
|
+
|
|
118
|
+
# Create backup data with metadata
|
|
119
|
+
backup_data = self._create_backup_data(entries)
|
|
120
|
+
|
|
121
|
+
# Write backup file
|
|
122
|
+
try:
|
|
123
|
+
with open(filepath, "w", encoding="utf-8") as f:
|
|
124
|
+
json.dump(backup_data, f, indent=2, ensure_ascii=False)
|
|
125
|
+
except (OSError, TypeError, ValueError) as e:
|
|
126
|
+
return BackupFileResult(
|
|
127
|
+
success=False,
|
|
128
|
+
filepath=str(filepath),
|
|
129
|
+
error=f"Failed to write backup file: {e}",
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
return BackupFileResult(
|
|
133
|
+
success=True,
|
|
134
|
+
message=f"Backup written to {filepath}",
|
|
135
|
+
filepath=str(filepath),
|
|
136
|
+
metadata=backup_data["metadata"],
|
|
137
|
+
data=backup_data,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
# ///////////////////////////////////////////////////////////////
|
|
141
|
+
# PRIVATE METHODS
|
|
142
|
+
# ///////////////////////////////////////////////////////////////
|
|
143
|
+
|
|
144
|
+
def _create_backup_data(self, entries: dict) -> dict:
|
|
145
|
+
"""
|
|
146
|
+
Create backup data structure with metadata.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
entries: Context menu entries
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
Backup data dictionary with metadata
|
|
153
|
+
"""
|
|
154
|
+
# Count total entries
|
|
155
|
+
total_entries = sum(
|
|
156
|
+
len(entries.get(context_type, []))
|
|
157
|
+
for context_type in ["directory", "background"]
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
# Create metadata
|
|
161
|
+
metadata = {
|
|
162
|
+
"version": self.BACKUP_VERSION,
|
|
163
|
+
"timestamp": datetime.now().isoformat(),
|
|
164
|
+
"platform": "Windows",
|
|
165
|
+
"total_entries": total_entries,
|
|
166
|
+
"context_types": list(entries.keys()),
|
|
167
|
+
"entry_counts": {
|
|
168
|
+
context_type: len(entries.get(context_type, []))
|
|
169
|
+
for context_type in ["directory", "background"]
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {"metadata": metadata, "entries": entries}
|
|
174
|
+
|
|
175
|
+
def list_backup_files(self, include_metadata: bool = True) -> BackupFileListResult:
|
|
176
|
+
"""
|
|
177
|
+
List all available backup files with optional metadata.
|
|
178
|
+
|
|
179
|
+
A backup whose metadata cannot be read is still listed, with the
|
|
180
|
+
metadata fields left at their defaults.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
include_metadata: Whether to include backup metadata
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
BackupFileListResult: the discovered backups; failure carries the error.
|
|
187
|
+
"""
|
|
188
|
+
pattern = "context_menu_backup_*.json"
|
|
189
|
+
try:
|
|
190
|
+
files = sorted(
|
|
191
|
+
self.backup_dir.glob(pattern),
|
|
192
|
+
key=lambda x: x.stat().st_mtime,
|
|
193
|
+
reverse=True,
|
|
194
|
+
)
|
|
195
|
+
except OSError as e:
|
|
196
|
+
return BackupFileListResult(
|
|
197
|
+
success=False,
|
|
198
|
+
backup_directory=str(self.backup_dir),
|
|
199
|
+
error=f"Could not access backup directory: {e}",
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
backups: list[BackupFileInfo] = []
|
|
203
|
+
for file in files:
|
|
204
|
+
try:
|
|
205
|
+
stat = file.stat()
|
|
206
|
+
except OSError as e:
|
|
207
|
+
self.logger.warning(f"Failed to stat backup file {file.name}: {e}")
|
|
208
|
+
continue
|
|
209
|
+
|
|
210
|
+
info = BackupFileInfo(
|
|
211
|
+
filename=file.name,
|
|
212
|
+
filepath=str(file),
|
|
213
|
+
size_bytes=stat.st_size,
|
|
214
|
+
modified_time=datetime.fromtimestamp(stat.st_mtime),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
if include_metadata:
|
|
218
|
+
try:
|
|
219
|
+
with open(file, encoding="utf-8") as f:
|
|
220
|
+
metadata = json.load(f).get("metadata", {})
|
|
221
|
+
info.entry_count = metadata.get("total_entries", 0)
|
|
222
|
+
info.backup_version = metadata.get("version", "unknown")
|
|
223
|
+
info.backup_timestamp = metadata.get("timestamp", "unknown")
|
|
224
|
+
info.context_types = metadata.get("context_types", [])
|
|
225
|
+
except (json.JSONDecodeError, OSError, AttributeError) as e:
|
|
226
|
+
self.logger.warning(
|
|
227
|
+
f"Failed to read metadata from {file.name}: {e}"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
backups.append(info)
|
|
231
|
+
|
|
232
|
+
return BackupFileListResult(
|
|
233
|
+
success=True,
|
|
234
|
+
message=f"Found {len(backups)} backup file(s)",
|
|
235
|
+
backup_directory=str(self.backup_dir),
|
|
236
|
+
backups=backups,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
def load_backup_file(self, filepath: str) -> BackupDataResult:
|
|
240
|
+
"""
|
|
241
|
+
Load and validate a backup file.
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
filepath: Path to the backup file
|
|
245
|
+
|
|
246
|
+
Returns:
|
|
247
|
+
BackupDataResult: the parsed backup; failure carries the error.
|
|
248
|
+
"""
|
|
249
|
+
if not filepath:
|
|
250
|
+
return BackupDataResult(
|
|
251
|
+
success=False, error="Filepath cannot be None or empty"
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
backup_path = Path(filepath)
|
|
255
|
+
if not backup_path.exists():
|
|
256
|
+
return BackupDataResult(
|
|
257
|
+
success=False,
|
|
258
|
+
filepath=filepath,
|
|
259
|
+
error=f"Backup file not found: {filepath}",
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
try:
|
|
263
|
+
with open(backup_path, encoding="utf-8") as f:
|
|
264
|
+
data = json.load(f)
|
|
265
|
+
except (json.JSONDecodeError, OSError) as e:
|
|
266
|
+
return BackupDataResult(
|
|
267
|
+
success=False,
|
|
268
|
+
filepath=filepath,
|
|
269
|
+
error=f"Could not read backup file: {e}",
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
# Validate backup format
|
|
273
|
+
try:
|
|
274
|
+
self._validate_backup_data(data)
|
|
275
|
+
except ValueError as e:
|
|
276
|
+
return BackupDataResult(
|
|
277
|
+
success=False, filepath=filepath, error=f"Invalid backup file: {e}"
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
return BackupDataResult(
|
|
281
|
+
success=True,
|
|
282
|
+
message=f"Loaded backup {backup_path.name}",
|
|
283
|
+
filepath=filepath,
|
|
284
|
+
data=data,
|
|
285
|
+
metadata=data.get("metadata", {}),
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
def _validate_backup_data(self, data: dict) -> None:
|
|
289
|
+
"""
|
|
290
|
+
Validate backup data structure.
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
data: Backup data to validate
|
|
294
|
+
|
|
295
|
+
Raises:
|
|
296
|
+
ValueError: If data is None or invalid
|
|
297
|
+
"""
|
|
298
|
+
# Input validation
|
|
299
|
+
if data is None:
|
|
300
|
+
raise ValueError("Backup data cannot be None")
|
|
301
|
+
|
|
302
|
+
if not isinstance(data, dict):
|
|
303
|
+
raise ValueError(
|
|
304
|
+
f"Backup data must be a dictionary, got {type(data).__name__}"
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
# Check required top-level keys
|
|
308
|
+
for key in self.BACKUP_REQUIRED_KEYS:
|
|
309
|
+
if key not in data:
|
|
310
|
+
raise ValueError(f"Missing required key: {key}")
|
|
311
|
+
|
|
312
|
+
# Validate metadata
|
|
313
|
+
metadata = data["metadata"]
|
|
314
|
+
for key in self.BACKUP_REQUIRED_METADATA:
|
|
315
|
+
if key not in metadata:
|
|
316
|
+
raise ValueError(f"Missing metadata key: {key}")
|
|
317
|
+
|
|
318
|
+
# Validate entries structure
|
|
319
|
+
entries = data["entries"]
|
|
320
|
+
if not isinstance(entries, dict):
|
|
321
|
+
raise ValueError("Entries must be a dictionary")
|
|
322
|
+
|
|
323
|
+
# Check for expected context types
|
|
324
|
+
expected_types = ContextTypesConfig.ALL_TYPES
|
|
325
|
+
for context_type in expected_types:
|
|
326
|
+
if context_type not in entries:
|
|
327
|
+
raise ValueError(f"Missing context type: {context_type}")
|
|
328
|
+
|
|
329
|
+
# Validate individual entries
|
|
330
|
+
for context_type, context_entries in entries.items():
|
|
331
|
+
if not isinstance(context_entries, list):
|
|
332
|
+
raise ValueError(f"Context entries must be a list: {context_type}")
|
|
333
|
+
|
|
334
|
+
for entry in context_entries:
|
|
335
|
+
if not isinstance(entry, dict):
|
|
336
|
+
raise ValueError(f"Entry must be a dictionary in {context_type}")
|
|
337
|
+
|
|
338
|
+
# Check required entry fields
|
|
339
|
+
required_entry_fields = ["key_name", "display_name"]
|
|
340
|
+
for field in required_entry_fields:
|
|
341
|
+
if field not in entry:
|
|
342
|
+
raise ValueError(f"Missing entry field: {field}")
|
|
343
|
+
|
|
344
|
+
def cleanup_old_backups(
|
|
345
|
+
self, max_files: int | None = None, retention_days: int | None = None
|
|
346
|
+
) -> BackupCleanupResult:
|
|
347
|
+
"""
|
|
348
|
+
Clean up old backup files.
|
|
349
|
+
|
|
350
|
+
Files that cannot be deleted are logged and counted as kept.
|
|
351
|
+
|
|
352
|
+
Args:
|
|
353
|
+
max_files: Maximum number of backup files to keep
|
|
354
|
+
retention_days: Number of days to keep backups
|
|
355
|
+
|
|
356
|
+
Returns:
|
|
357
|
+
BackupCleanupResult: deleted and kept files; failure carries the error.
|
|
358
|
+
"""
|
|
359
|
+
if max_files is not None and (not isinstance(max_files, int) or max_files < 0):
|
|
360
|
+
return BackupCleanupResult(
|
|
361
|
+
success=False,
|
|
362
|
+
error=f"max_files must be a positive integer, got {max_files}",
|
|
363
|
+
)
|
|
364
|
+
|
|
365
|
+
if retention_days is not None and (
|
|
366
|
+
not isinstance(retention_days, int) or retention_days < 0
|
|
367
|
+
):
|
|
368
|
+
return BackupCleanupResult(
|
|
369
|
+
success=False,
|
|
370
|
+
error=(
|
|
371
|
+
f"retention_days must be a positive integer, got {retention_days}"
|
|
372
|
+
),
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
if max_files is None:
|
|
376
|
+
max_files = self.MAX_BACKUP_FILES
|
|
377
|
+
if retention_days is None:
|
|
378
|
+
retention_days = self.BACKUP_RETENTION_DAYS
|
|
379
|
+
|
|
380
|
+
listing = self.list_backup_files(include_metadata=False)
|
|
381
|
+
if not listing.success:
|
|
382
|
+
return BackupCleanupResult(success=False, error=listing.error)
|
|
383
|
+
|
|
384
|
+
deleted_files: list[str] = []
|
|
385
|
+
kept_files: list[str] = []
|
|
386
|
+
|
|
387
|
+
# Sort by modification time (oldest first)
|
|
388
|
+
backups = sorted(
|
|
389
|
+
listing.backups or [], key=lambda b: b.modified_time or datetime.min
|
|
390
|
+
)
|
|
391
|
+
cutoff_date = datetime.now() - timedelta(days=retention_days)
|
|
392
|
+
|
|
393
|
+
for info in backups:
|
|
394
|
+
expired = (
|
|
395
|
+
info.modified_time is not None and info.modified_time < cutoff_date
|
|
396
|
+
)
|
|
397
|
+
over_limit = len(kept_files) >= max_files
|
|
398
|
+
|
|
399
|
+
if not (expired or over_limit):
|
|
400
|
+
kept_files.append(info.filename)
|
|
401
|
+
continue
|
|
402
|
+
|
|
403
|
+
try:
|
|
404
|
+
Path(info.filepath).unlink()
|
|
405
|
+
deleted_files.append(info.filename)
|
|
406
|
+
except OSError as e:
|
|
407
|
+
self.logger.warning(
|
|
408
|
+
f"Could not delete backup file {info.filename}: {e}"
|
|
409
|
+
)
|
|
410
|
+
kept_files.append(info.filename)
|
|
411
|
+
|
|
412
|
+
return BackupCleanupResult(
|
|
413
|
+
success=True,
|
|
414
|
+
message=f"Deleted {len(deleted_files)} backup(s), kept {len(kept_files)}",
|
|
415
|
+
deleted_files=deleted_files,
|
|
416
|
+
kept_files=kept_files,
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
def get_backup_info(self, filepath: str) -> BackupDataResult:
|
|
420
|
+
"""
|
|
421
|
+
Get detailed information about a backup file.
|
|
422
|
+
|
|
423
|
+
Args:
|
|
424
|
+
filepath: Path to the backup file
|
|
425
|
+
|
|
426
|
+
Returns:
|
|
427
|
+
BackupDataResult: metadata plus per-context entry statistics;
|
|
428
|
+
failure carries the error.
|
|
429
|
+
"""
|
|
430
|
+
loaded = self.load_backup_file(filepath)
|
|
431
|
+
if not loaded.success:
|
|
432
|
+
return loaded
|
|
433
|
+
|
|
434
|
+
data = loaded.data or {}
|
|
435
|
+
entries = data.get("entries", {})
|
|
436
|
+
|
|
437
|
+
# Calculate additional statistics
|
|
438
|
+
entry_stats = {
|
|
439
|
+
context_type: {
|
|
440
|
+
"count": len(context_entries),
|
|
441
|
+
"sample_keys": [
|
|
442
|
+
entry.get("key_name", "unknown") for entry in context_entries[:5]
|
|
443
|
+
],
|
|
444
|
+
}
|
|
445
|
+
for context_type, context_entries in entries.items()
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
loaded.entry_stats = entry_stats
|
|
449
|
+
return loaded
|
|
450
|
+
|
|
451
|
+
def create_backup_copy(
|
|
452
|
+
self, source_filepath: str, destination_filepath: str
|
|
453
|
+
) -> BackupFileResult:
|
|
454
|
+
"""
|
|
455
|
+
Create a copy of a backup file.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
source_filepath: Source backup file path
|
|
459
|
+
destination_filepath: Destination backup file path
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
BackupFileResult: the destination path; failure carries the error.
|
|
463
|
+
"""
|
|
464
|
+
if not source_filepath:
|
|
465
|
+
return BackupFileResult(
|
|
466
|
+
success=False, error="Source filepath cannot be None or empty"
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
if not destination_filepath:
|
|
470
|
+
return BackupFileResult(
|
|
471
|
+
success=False, error="Destination filepath cannot be None or empty"
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
source_path = Path(source_filepath)
|
|
475
|
+
destination_path = Path(destination_filepath)
|
|
476
|
+
|
|
477
|
+
if not source_path.exists():
|
|
478
|
+
return BackupFileResult(
|
|
479
|
+
success=False, error=f"Source file not found: {source_filepath}"
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
try:
|
|
483
|
+
# Create destination directory if needed
|
|
484
|
+
destination_path.parent.mkdir(parents=True, exist_ok=True)
|
|
485
|
+
shutil.copy2(source_path, destination_path)
|
|
486
|
+
except OSError as e:
|
|
487
|
+
return BackupFileResult(
|
|
488
|
+
success=False,
|
|
489
|
+
filepath=str(destination_path),
|
|
490
|
+
error=f"Failed to copy backup file: {e}",
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
return BackupFileResult(
|
|
494
|
+
success=True,
|
|
495
|
+
message=f"Copied backup to {destination_path}",
|
|
496
|
+
filepath=str(destination_path),
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
def merge_backups(
|
|
500
|
+
self, backup_filepaths: list[str], output_filepath: str
|
|
501
|
+
) -> BackupFileResult:
|
|
502
|
+
"""
|
|
503
|
+
Merge multiple backup files into a single backup.
|
|
504
|
+
|
|
505
|
+
Args:
|
|
506
|
+
backup_filepaths: List of backup file paths to merge
|
|
507
|
+
output_filepath: Output backup file path
|
|
508
|
+
|
|
509
|
+
Returns:
|
|
510
|
+
BackupFileResult: the written merge; failure carries the error.
|
|
511
|
+
"""
|
|
512
|
+
if not backup_filepaths:
|
|
513
|
+
return BackupFileResult(
|
|
514
|
+
success=False, error="Backup filepaths list cannot be empty"
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
if not output_filepath:
|
|
518
|
+
return BackupFileResult(
|
|
519
|
+
success=False, error="Output filepath cannot be None or empty"
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
merged_entries: dict[str, list] = {
|
|
523
|
+
ctx_type: [] for ctx_type in ContextTypesConfig.ALL_TYPES
|
|
524
|
+
}
|
|
525
|
+
merged_from: list[str] = []
|
|
526
|
+
|
|
527
|
+
# Load and merge each backup
|
|
528
|
+
for filepath in backup_filepaths:
|
|
529
|
+
loaded = self.load_backup_file(filepath)
|
|
530
|
+
if not loaded.success:
|
|
531
|
+
return BackupFileResult(
|
|
532
|
+
success=False,
|
|
533
|
+
error=f"Could not merge {filepath}: {loaded.error}",
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
data = loaded.data or {}
|
|
537
|
+
|
|
538
|
+
# Add to merged entries (avoid duplicates by key_name)
|
|
539
|
+
existing_keys = {
|
|
540
|
+
entry.get("key_name")
|
|
541
|
+
for context_type in ["directory", "background"]
|
|
542
|
+
for entry in merged_entries[context_type]
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
for context_type in ["directory", "background"]:
|
|
546
|
+
for entry in data.get("entries", {}).get(context_type, []):
|
|
547
|
+
key_name = entry.get("key_name")
|
|
548
|
+
if key_name and key_name not in existing_keys:
|
|
549
|
+
merged_entries[context_type].append(entry)
|
|
550
|
+
existing_keys.add(key_name)
|
|
551
|
+
|
|
552
|
+
merged_from.append(filepath)
|
|
553
|
+
|
|
554
|
+
# Save merged backup — create_backup_file rebuilds the metadata block
|
|
555
|
+
written = self.create_backup_file(
|
|
556
|
+
merged_entries, output_filepath, add_timestamp=False
|
|
557
|
+
)
|
|
558
|
+
if not written.success:
|
|
559
|
+
return written
|
|
560
|
+
|
|
561
|
+
written.message = f"Merged {len(merged_from)} backup(s) into {written.filepath}"
|
|
562
|
+
return written
|