roundtripper 0.2.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.
- roundtripper/__init__.py +1 -0
- roundtripper/api_client.py +83 -0
- roundtripper/cli.py +75 -0
- roundtripper/config.py +110 -0
- roundtripper/config_interactive.py +743 -0
- roundtripper/config_store.py +197 -0
- roundtripper/confluence.py +307 -0
- roundtripper/file_utils.py +197 -0
- roundtripper/models.py +254 -0
- roundtripper/pull_service.py +387 -0
- roundtripper/push_service.py +394 -0
- roundtripper/py.typed +0 -0
- roundtripper-0.2.0.dist-info/METADATA +104 -0
- roundtripper-0.2.0.dist-info/RECORD +17 -0
- roundtripper-0.2.0.dist-info/WHEEL +4 -0
- roundtripper-0.2.0.dist-info/entry_points.txt +2 -0
- roundtripper-0.2.0.dist-info/licenses/LICENSE +31 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Storage and retrieval of application configuration for roundtripper.
|
|
2
|
+
|
|
3
|
+
Uses XDG Base Directory specification for config file location.
|
|
4
|
+
Adapted from confluence-markdown-exporter by Sebastian Penhouet.
|
|
5
|
+
https://github.com/Spenhouet/confluence-markdown-exporter
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from pydantic import BaseModel, ValidationError
|
|
14
|
+
|
|
15
|
+
from roundtripper.config import AuthConfig, ConfigModel, ConnectionConfig
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def get_app_config_path() -> Path:
|
|
19
|
+
"""Determine the path to the app config file using XDG standard.
|
|
20
|
+
|
|
21
|
+
The config file location is determined by:
|
|
22
|
+
1. ROUNDTRIPPER_CONFIG_PATH environment variable if set
|
|
23
|
+
2. XDG_CONFIG_HOME/roundtripper/config.json if XDG_CONFIG_HOME is set
|
|
24
|
+
3. ~/.config/roundtripper/config.json (XDG default)
|
|
25
|
+
|
|
26
|
+
Creates parent directories if they don't exist.
|
|
27
|
+
|
|
28
|
+
Returns
|
|
29
|
+
-------
|
|
30
|
+
Path
|
|
31
|
+
Path to the configuration file.
|
|
32
|
+
"""
|
|
33
|
+
config_env = os.environ.get("ROUNDTRIPPER_CONFIG_PATH")
|
|
34
|
+
if config_env:
|
|
35
|
+
path = Path(config_env)
|
|
36
|
+
else:
|
|
37
|
+
xdg_config_home = os.environ.get("XDG_CONFIG_HOME")
|
|
38
|
+
if xdg_config_home:
|
|
39
|
+
config_dir = Path(xdg_config_home) / "roundtripper"
|
|
40
|
+
else:
|
|
41
|
+
config_dir = Path.home() / ".config" / "roundtripper"
|
|
42
|
+
path = config_dir / "config.json"
|
|
43
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
return path
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
APP_CONFIG_PATH = get_app_config_path()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_app_data() -> dict[str, dict]:
|
|
51
|
+
"""Load application data from the config file.
|
|
52
|
+
|
|
53
|
+
Returns a validated dict. If the file doesn't exist or is invalid,
|
|
54
|
+
returns the default configuration.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
dict[str, dict]
|
|
59
|
+
Configuration data as a dictionary.
|
|
60
|
+
"""
|
|
61
|
+
if not APP_CONFIG_PATH.exists():
|
|
62
|
+
return ConfigModel().model_dump()
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
data = json.loads(APP_CONFIG_PATH.read_text())
|
|
66
|
+
return ConfigModel(**data).model_dump()
|
|
67
|
+
except (json.JSONDecodeError, ValidationError):
|
|
68
|
+
return ConfigModel().model_dump()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def save_app_data(config_model: ConfigModel) -> None:
|
|
72
|
+
"""Save application data to the config file.
|
|
73
|
+
|
|
74
|
+
Uses Pydantic's model_dump_json which properly handles SecretStr serialization.
|
|
75
|
+
|
|
76
|
+
Parameters
|
|
77
|
+
----------
|
|
78
|
+
config_model
|
|
79
|
+
The configuration model to save.
|
|
80
|
+
"""
|
|
81
|
+
json_str = config_model.model_dump_json(indent=2)
|
|
82
|
+
APP_CONFIG_PATH.write_text(json_str)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def get_settings() -> ConfigModel:
|
|
86
|
+
"""Get the current application settings as a ConfigModel instance.
|
|
87
|
+
|
|
88
|
+
Returns
|
|
89
|
+
-------
|
|
90
|
+
ConfigModel
|
|
91
|
+
Current configuration settings.
|
|
92
|
+
"""
|
|
93
|
+
data = load_app_data()
|
|
94
|
+
return ConfigModel(
|
|
95
|
+
connection_config=ConnectionConfig(**data.get("connection_config", {})),
|
|
96
|
+
auth=AuthConfig(**data.get("auth", {})),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _set_by_path(obj: dict, path: str, value: Any) -> None:
|
|
101
|
+
"""Set a value in a nested dictionary by dot-notation path.
|
|
102
|
+
|
|
103
|
+
Parameters
|
|
104
|
+
----------
|
|
105
|
+
obj
|
|
106
|
+
The dictionary to modify.
|
|
107
|
+
path
|
|
108
|
+
Dot-notation path (e.g., 'auth.confluence.url').
|
|
109
|
+
value
|
|
110
|
+
The value to set.
|
|
111
|
+
"""
|
|
112
|
+
keys = path.split(".")
|
|
113
|
+
current = obj
|
|
114
|
+
for k in keys[:-1]:
|
|
115
|
+
if k not in current or not isinstance(current[k], dict): # pragma: no cover
|
|
116
|
+
current[k] = {}
|
|
117
|
+
current = current[k]
|
|
118
|
+
current[keys[-1]] = value
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def set_setting(path: str, value: Any) -> None:
|
|
122
|
+
"""Set a setting by dot-path and save to config file.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
path
|
|
127
|
+
Dot-separated path to the setting (e.g., "auth.confluence.url").
|
|
128
|
+
value
|
|
129
|
+
The value to set.
|
|
130
|
+
|
|
131
|
+
Raises
|
|
132
|
+
------
|
|
133
|
+
ValueError
|
|
134
|
+
If the value is invalid according to the Pydantic model.
|
|
135
|
+
"""
|
|
136
|
+
data = load_app_data()
|
|
137
|
+
_set_by_path(data, path, value)
|
|
138
|
+
try:
|
|
139
|
+
settings = ConfigModel.model_validate(data)
|
|
140
|
+
except ValidationError as e:
|
|
141
|
+
raise ValueError(str(e)) from e
|
|
142
|
+
save_app_data(settings)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def get_default_value_by_path(path: str | None = None) -> Any:
|
|
146
|
+
"""Get the default value for a given config path.
|
|
147
|
+
|
|
148
|
+
Parameters
|
|
149
|
+
----------
|
|
150
|
+
path
|
|
151
|
+
Dot-separated path to the setting. If None, returns the entire default config.
|
|
152
|
+
|
|
153
|
+
Returns
|
|
154
|
+
-------
|
|
155
|
+
Any
|
|
156
|
+
The default value for the given path.
|
|
157
|
+
|
|
158
|
+
Raises
|
|
159
|
+
------
|
|
160
|
+
KeyError
|
|
161
|
+
If the path is invalid.
|
|
162
|
+
"""
|
|
163
|
+
model = ConfigModel()
|
|
164
|
+
if not path:
|
|
165
|
+
return model.model_dump()
|
|
166
|
+
keys = path.split(".")
|
|
167
|
+
current: Any = model
|
|
168
|
+
for k in keys:
|
|
169
|
+
if hasattr(current, k):
|
|
170
|
+
current = getattr(current, k)
|
|
171
|
+
elif isinstance(current, dict) and k in current: # pragma: no cover
|
|
172
|
+
current = current[k]
|
|
173
|
+
else:
|
|
174
|
+
msg = f"Invalid config path: {path}"
|
|
175
|
+
raise KeyError(msg)
|
|
176
|
+
|
|
177
|
+
if isinstance(current, BaseModel):
|
|
178
|
+
return current.model_dump()
|
|
179
|
+
return current
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def reset_to_defaults(path: str | None = None) -> None:
|
|
183
|
+
"""Reset the whole config, a section, or a single option to its default value.
|
|
184
|
+
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
path
|
|
188
|
+
Dot-separated path to reset. If None, resets the entire config.
|
|
189
|
+
"""
|
|
190
|
+
if path is None:
|
|
191
|
+
save_app_data(ConfigModel())
|
|
192
|
+
return
|
|
193
|
+
data = load_app_data()
|
|
194
|
+
default_value = get_default_value_by_path(path)
|
|
195
|
+
_set_by_path(data, path, default_value)
|
|
196
|
+
settings = ConfigModel.model_validate(data)
|
|
197
|
+
save_app_data(settings)
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Confluence commands for roundtripper."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import cyclopts
|
|
7
|
+
|
|
8
|
+
from roundtripper.api_client import get_confluence_client
|
|
9
|
+
from roundtripper.config_interactive import main_config_menu_loop
|
|
10
|
+
from roundtripper.config_store import get_settings
|
|
11
|
+
from roundtripper.pull_service import PullService
|
|
12
|
+
from roundtripper.push_service import PushService
|
|
13
|
+
|
|
14
|
+
#: Logger instance.
|
|
15
|
+
LOGGER = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
#: CLI application for Confluence commands.
|
|
18
|
+
app = cyclopts.App(name="confluence", help="Confluence-related commands")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@app.command
|
|
22
|
+
def config(
|
|
23
|
+
*,
|
|
24
|
+
jump_to: str | None = None,
|
|
25
|
+
show: bool = False,
|
|
26
|
+
) -> None:
|
|
27
|
+
"""Configure Confluence settings.
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
jump_to
|
|
32
|
+
Jump directly to a config submenu (e.g., 'auth.confluence').
|
|
33
|
+
show
|
|
34
|
+
Display current configuration as JSON instead of opening the interactive menu.
|
|
35
|
+
"""
|
|
36
|
+
if show:
|
|
37
|
+
current_settings = get_settings()
|
|
38
|
+
json_output = current_settings.model_dump_json(indent=2)
|
|
39
|
+
print(f"```json\n{json_output}\n```")
|
|
40
|
+
else:
|
|
41
|
+
main_config_menu_loop(jump_to)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@app.command
|
|
45
|
+
def ping() -> None:
|
|
46
|
+
"""Test Confluence API connection.
|
|
47
|
+
|
|
48
|
+
Verifies that the configured Confluence credentials are valid
|
|
49
|
+
and the API is accessible.
|
|
50
|
+
"""
|
|
51
|
+
settings = get_settings()
|
|
52
|
+
confluence_config = settings.auth.confluence
|
|
53
|
+
|
|
54
|
+
# Check if configuration is complete
|
|
55
|
+
if not confluence_config.url:
|
|
56
|
+
LOGGER.error("✗ Confluence URL is not configured")
|
|
57
|
+
LOGGER.info("Run 'roundtripper confluence config' to configure")
|
|
58
|
+
raise SystemExit(1)
|
|
59
|
+
|
|
60
|
+
url_str = str(confluence_config.url)
|
|
61
|
+
LOGGER.info("=" * 70)
|
|
62
|
+
LOGGER.info("Testing Confluence API Connection")
|
|
63
|
+
LOGGER.info("=" * 70)
|
|
64
|
+
LOGGER.info("")
|
|
65
|
+
LOGGER.info("API URL: %s", url_str)
|
|
66
|
+
|
|
67
|
+
# Determine authentication method
|
|
68
|
+
username = confluence_config.username.get_secret_value()
|
|
69
|
+
api_token = confluence_config.api_token.get_secret_value()
|
|
70
|
+
pat = confluence_config.pat.get_secret_value()
|
|
71
|
+
|
|
72
|
+
if pat:
|
|
73
|
+
LOGGER.info("Auth method: Personal Access Token (PAT)")
|
|
74
|
+
elif username and api_token:
|
|
75
|
+
LOGGER.info("Auth method: Basic Auth (username + API token)")
|
|
76
|
+
else:
|
|
77
|
+
LOGGER.error("✗ No authentication credentials configured")
|
|
78
|
+
LOGGER.info("Run 'roundtripper confluence config' to set credentials")
|
|
79
|
+
raise SystemExit(1)
|
|
80
|
+
|
|
81
|
+
LOGGER.info("")
|
|
82
|
+
LOGGER.info("Attempting to connect to Confluence API...")
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
# Use the real API client to test connection
|
|
86
|
+
client = get_confluence_client()
|
|
87
|
+
|
|
88
|
+
# Try to get space list (lightweight operation)
|
|
89
|
+
client.get_all_spaces(limit=1)
|
|
90
|
+
|
|
91
|
+
LOGGER.info("✓ Connection successful!")
|
|
92
|
+
LOGGER.info("✓ Successfully retrieved space list")
|
|
93
|
+
LOGGER.info("")
|
|
94
|
+
LOGGER.info("=" * 70)
|
|
95
|
+
LOGGER.info("✓ All checks passed!")
|
|
96
|
+
LOGGER.info("=" * 70)
|
|
97
|
+
|
|
98
|
+
except ConnectionError as e:
|
|
99
|
+
LOGGER.error("✗ Connection failed: %s", e)
|
|
100
|
+
LOGGER.error("Please check:")
|
|
101
|
+
LOGGER.error(" - Confluence URL is correct")
|
|
102
|
+
LOGGER.error(" - Authentication credentials are valid")
|
|
103
|
+
LOGGER.error(" - Network connectivity")
|
|
104
|
+
LOGGER.error(" - SSL/TLS settings")
|
|
105
|
+
raise SystemExit(1) from e
|
|
106
|
+
except Exception as e:
|
|
107
|
+
LOGGER.error("✗ Unexpected error: %s", e)
|
|
108
|
+
raise SystemExit(1) from e
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@app.command
|
|
112
|
+
def pull(
|
|
113
|
+
*,
|
|
114
|
+
space: str | None = None,
|
|
115
|
+
page_id: int | None = None,
|
|
116
|
+
output: Path = Path("./confluence-export"),
|
|
117
|
+
recursive: bool = True,
|
|
118
|
+
dry_run: bool = False,
|
|
119
|
+
verbose: bool = False,
|
|
120
|
+
) -> None:
|
|
121
|
+
"""Pull Confluence content to local storage.
|
|
122
|
+
|
|
123
|
+
Downloads pages and attachments from Confluence, preserving the original
|
|
124
|
+
Confluence storage format and all API metadata.
|
|
125
|
+
|
|
126
|
+
Parameters
|
|
127
|
+
----------
|
|
128
|
+
space
|
|
129
|
+
Space key to pull all pages from.
|
|
130
|
+
page_id
|
|
131
|
+
Specific page ID to pull.
|
|
132
|
+
output
|
|
133
|
+
Output directory for downloaded content.
|
|
134
|
+
recursive
|
|
135
|
+
When pulling a specific page, also pull all descendants.
|
|
136
|
+
dry_run
|
|
137
|
+
Show what would be downloaded without actually downloading.
|
|
138
|
+
verbose
|
|
139
|
+
Enable debug logging.
|
|
140
|
+
"""
|
|
141
|
+
if verbose:
|
|
142
|
+
logging.getLogger("roundtripper").setLevel(logging.DEBUG)
|
|
143
|
+
|
|
144
|
+
if not space and not page_id:
|
|
145
|
+
LOGGER.error("Either --space or --page-id must be specified")
|
|
146
|
+
raise SystemExit(1)
|
|
147
|
+
|
|
148
|
+
if space and page_id:
|
|
149
|
+
LOGGER.error("Cannot specify both --space and --page-id")
|
|
150
|
+
raise SystemExit(1)
|
|
151
|
+
|
|
152
|
+
# Get Confluence client
|
|
153
|
+
try:
|
|
154
|
+
client = get_confluence_client()
|
|
155
|
+
except ConnectionError as e:
|
|
156
|
+
LOGGER.error("Failed to connect to Confluence: %s", e)
|
|
157
|
+
LOGGER.info("Run 'roundtripper confluence ping' to test your connection")
|
|
158
|
+
raise SystemExit(1) from e
|
|
159
|
+
|
|
160
|
+
# Create pull service
|
|
161
|
+
service = PullService(client, output, dry_run=dry_run)
|
|
162
|
+
|
|
163
|
+
if dry_run:
|
|
164
|
+
LOGGER.info("[DRY RUN] Showing what would be downloaded...")
|
|
165
|
+
LOGGER.info("")
|
|
166
|
+
|
|
167
|
+
# Perform pull
|
|
168
|
+
if space:
|
|
169
|
+
LOGGER.info("Pulling space: %s", space)
|
|
170
|
+
result = service.pull_space(space)
|
|
171
|
+
else:
|
|
172
|
+
assert page_id is not None # for type checker
|
|
173
|
+
LOGGER.info("Pulling page: %d (recursive=%s)", page_id, recursive)
|
|
174
|
+
result = service.pull_page(page_id, recursive=recursive)
|
|
175
|
+
|
|
176
|
+
# Summary
|
|
177
|
+
LOGGER.info("")
|
|
178
|
+
LOGGER.info("=" * 70)
|
|
179
|
+
LOGGER.info("Pull Summary")
|
|
180
|
+
LOGGER.info("=" * 70)
|
|
181
|
+
LOGGER.info("Pages downloaded: %d", result.pages_downloaded)
|
|
182
|
+
LOGGER.info("Pages skipped (up to date): %d", result.pages_skipped)
|
|
183
|
+
LOGGER.info("Attachments downloaded: %d", result.attachments_downloaded)
|
|
184
|
+
LOGGER.info("Attachments skipped (up to date): %d", result.attachments_skipped)
|
|
185
|
+
|
|
186
|
+
if result.errors:
|
|
187
|
+
LOGGER.warning("Errors encountered: %d", len(result.errors))
|
|
188
|
+
for error in result.errors[:5]: # Show first 5 errors
|
|
189
|
+
LOGGER.warning(" - %s", error)
|
|
190
|
+
if len(result.errors) > 5:
|
|
191
|
+
LOGGER.warning(" ... and %d more errors", len(result.errors) - 5)
|
|
192
|
+
raise SystemExit(1)
|
|
193
|
+
|
|
194
|
+
LOGGER.info("")
|
|
195
|
+
LOGGER.info("✓ Pull completed successfully!")
|
|
196
|
+
LOGGER.info("Output directory: %s", output.absolute())
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@app.command
|
|
200
|
+
def push(
|
|
201
|
+
*,
|
|
202
|
+
page_path: Path | None = None,
|
|
203
|
+
space_path: Path | None = None,
|
|
204
|
+
recursive: bool = False,
|
|
205
|
+
dry_run: bool = False,
|
|
206
|
+
force: bool = False,
|
|
207
|
+
verbose: bool = False,
|
|
208
|
+
) -> None:
|
|
209
|
+
"""Push local content back to Confluence.
|
|
210
|
+
|
|
211
|
+
Uploads modified pages and attachments to Confluence, detecting changes
|
|
212
|
+
and handling version conflicts.
|
|
213
|
+
|
|
214
|
+
Parameters
|
|
215
|
+
----------
|
|
216
|
+
page_path
|
|
217
|
+
Path to a page directory to push (contains page.xml and page.json).
|
|
218
|
+
space_path
|
|
219
|
+
Path to a space directory to push all pages.
|
|
220
|
+
recursive
|
|
221
|
+
When pushing a specific page, also push all descendant pages.
|
|
222
|
+
dry_run
|
|
223
|
+
Show what would be pushed without actually pushing.
|
|
224
|
+
force
|
|
225
|
+
Push even if there are version conflicts (overwrites server content).
|
|
226
|
+
verbose
|
|
227
|
+
Enable debug logging.
|
|
228
|
+
"""
|
|
229
|
+
if verbose:
|
|
230
|
+
logging.getLogger("roundtripper").setLevel(logging.DEBUG)
|
|
231
|
+
|
|
232
|
+
if not page_path and not space_path:
|
|
233
|
+
LOGGER.error("Either --page-path or --space-path must be specified")
|
|
234
|
+
raise SystemExit(1)
|
|
235
|
+
|
|
236
|
+
if page_path and space_path:
|
|
237
|
+
LOGGER.error("Cannot specify both --page-path and --space-path")
|
|
238
|
+
raise SystemExit(1)
|
|
239
|
+
|
|
240
|
+
# Validate paths exist
|
|
241
|
+
target_path = page_path or space_path
|
|
242
|
+
assert target_path is not None # for type checker
|
|
243
|
+
if not target_path.exists():
|
|
244
|
+
LOGGER.error("Path does not exist: %s", target_path)
|
|
245
|
+
raise SystemExit(1)
|
|
246
|
+
|
|
247
|
+
# Get Confluence client
|
|
248
|
+
try:
|
|
249
|
+
client = get_confluence_client()
|
|
250
|
+
except ConnectionError as e:
|
|
251
|
+
LOGGER.error("Failed to connect to Confluence: %s", e)
|
|
252
|
+
LOGGER.info("Run 'roundtripper confluence ping' to test your connection")
|
|
253
|
+
raise SystemExit(1) from e
|
|
254
|
+
|
|
255
|
+
# Create push service
|
|
256
|
+
service = PushService(client, dry_run=dry_run, force=force)
|
|
257
|
+
|
|
258
|
+
if dry_run:
|
|
259
|
+
LOGGER.info("[DRY RUN] Analyzing changes...")
|
|
260
|
+
LOGGER.info("")
|
|
261
|
+
|
|
262
|
+
# Perform push
|
|
263
|
+
if page_path:
|
|
264
|
+
LOGGER.info("Pushing page: %s (recursive=%s)", page_path, recursive)
|
|
265
|
+
result = service.push_page(page_path, recursive=recursive)
|
|
266
|
+
else:
|
|
267
|
+
assert space_path is not None # for type checker
|
|
268
|
+
LOGGER.info("Pushing space: %s", space_path)
|
|
269
|
+
result = service.push_space(space_path)
|
|
270
|
+
|
|
271
|
+
# Summary
|
|
272
|
+
LOGGER.info("")
|
|
273
|
+
LOGGER.info("=" * 70)
|
|
274
|
+
LOGGER.info("Push Summary")
|
|
275
|
+
LOGGER.info("=" * 70)
|
|
276
|
+
LOGGER.info("Pages updated: %d", result.pages_updated)
|
|
277
|
+
LOGGER.info("Pages created: %d", result.pages_created)
|
|
278
|
+
LOGGER.info("Pages skipped (unchanged): %d", result.pages_skipped)
|
|
279
|
+
LOGGER.info("Attachments uploaded: %d", result.attachments_uploaded)
|
|
280
|
+
LOGGER.info("Attachments skipped: %d", result.attachments_skipped)
|
|
281
|
+
|
|
282
|
+
if result.conflicts:
|
|
283
|
+
LOGGER.warning("")
|
|
284
|
+
LOGGER.warning("Conflicts detected: %d", len(result.conflicts))
|
|
285
|
+
for conflict in result.conflicts[:5]:
|
|
286
|
+
LOGGER.warning(" ⚠ %s", conflict)
|
|
287
|
+
if len(result.conflicts) > 5:
|
|
288
|
+
LOGGER.warning(" ... and %d more conflicts", len(result.conflicts) - 5)
|
|
289
|
+
LOGGER.info("")
|
|
290
|
+
LOGGER.info("Use --force to overwrite server content, or pull latest changes first.")
|
|
291
|
+
|
|
292
|
+
if result.errors:
|
|
293
|
+
LOGGER.warning("")
|
|
294
|
+
LOGGER.warning("Errors encountered: %d", len(result.errors))
|
|
295
|
+
for error in result.errors[:5]:
|
|
296
|
+
LOGGER.warning(" - %s", error)
|
|
297
|
+
if len(result.errors) > 5:
|
|
298
|
+
LOGGER.warning(" ... and %d more errors", len(result.errors) - 5)
|
|
299
|
+
|
|
300
|
+
if result.conflicts or result.errors:
|
|
301
|
+
raise SystemExit(1)
|
|
302
|
+
|
|
303
|
+
LOGGER.info("")
|
|
304
|
+
if dry_run:
|
|
305
|
+
LOGGER.info("Run without --dry-run to apply changes.")
|
|
306
|
+
else:
|
|
307
|
+
LOGGER.info("✓ Push completed successfully!")
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Utility functions for file operations.
|
|
2
|
+
|
|
3
|
+
Adapted from confluence-markdown-exporter by Sebastian Penhouet.
|
|
4
|
+
https://github.com/Spenhouet/confluence-markdown-exporter
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import xml.dom.minidom
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def format_xml(xml_content: str, max_line_length: int = 120) -> str:
|
|
15
|
+
"""Format XML with proper indentation and line wrapping.
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
xml_content
|
|
20
|
+
Raw XML content to format.
|
|
21
|
+
max_line_length
|
|
22
|
+
Maximum line length before wrapping.
|
|
23
|
+
|
|
24
|
+
Returns
|
|
25
|
+
-------
|
|
26
|
+
str
|
|
27
|
+
Formatted XML string with proper indentation.
|
|
28
|
+
"""
|
|
29
|
+
try:
|
|
30
|
+
# Add XML declaration if not present for better parsing
|
|
31
|
+
if not xml_content.strip().startswith("<?xml"):
|
|
32
|
+
xml_content = '<?xml version="1.0" encoding="utf-8"?>' + xml_content
|
|
33
|
+
|
|
34
|
+
# Parse and pretty-print the XML
|
|
35
|
+
dom = xml.dom.minidom.parseString(xml_content)
|
|
36
|
+
pretty_xml = dom.toprettyxml(indent=" ", encoding="utf-8").decode("utf-8")
|
|
37
|
+
|
|
38
|
+
# Remove extra blank lines that minidom creates
|
|
39
|
+
lines = [line for line in pretty_xml.split("\n") if line.strip()]
|
|
40
|
+
|
|
41
|
+
# Join lines and handle wrapping for long lines
|
|
42
|
+
result_lines = []
|
|
43
|
+
for line in lines:
|
|
44
|
+
# If line is too long and contains attributes, try to wrap
|
|
45
|
+
if len(line) > max_line_length and "=" in line and "<" in line:
|
|
46
|
+
# Simple wrapping: could be enhanced in the future
|
|
47
|
+
result_lines.append(line)
|
|
48
|
+
else:
|
|
49
|
+
result_lines.append(line)
|
|
50
|
+
|
|
51
|
+
return "\n".join(result_lines)
|
|
52
|
+
except Exception:
|
|
53
|
+
# If parsing fails, return original content
|
|
54
|
+
return xml_content
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def save_file(file_path: Path, content: str | bytes) -> None:
|
|
58
|
+
"""Save content to a file, creating parent directories as needed.
|
|
59
|
+
|
|
60
|
+
Parameters
|
|
61
|
+
----------
|
|
62
|
+
file_path
|
|
63
|
+
Path to the file to create/overwrite.
|
|
64
|
+
content
|
|
65
|
+
Content to write (string or bytes).
|
|
66
|
+
|
|
67
|
+
Raises
|
|
68
|
+
------
|
|
69
|
+
TypeError
|
|
70
|
+
If content is neither string nor bytes.
|
|
71
|
+
"""
|
|
72
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
if isinstance(content, bytes):
|
|
74
|
+
with file_path.open("wb") as file:
|
|
75
|
+
file.write(content)
|
|
76
|
+
elif isinstance(content, str):
|
|
77
|
+
with file_path.open("w", encoding="utf-8") as file:
|
|
78
|
+
file.write(content)
|
|
79
|
+
else:
|
|
80
|
+
msg = "Content must be either a string or bytes."
|
|
81
|
+
raise TypeError(msg)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def save_json(file_path: Path, data: dict[str, Any]) -> None:
|
|
85
|
+
"""Save data as JSON to a file.
|
|
86
|
+
|
|
87
|
+
Parameters
|
|
88
|
+
----------
|
|
89
|
+
file_path
|
|
90
|
+
Path to the JSON file to create/overwrite.
|
|
91
|
+
data
|
|
92
|
+
Data to serialize as JSON.
|
|
93
|
+
"""
|
|
94
|
+
content = json.dumps(data, indent=2, ensure_ascii=False, default=str)
|
|
95
|
+
save_file(file_path, content)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def sanitize_filename(filename: str) -> str:
|
|
99
|
+
"""Sanitize a filename for cross-platform compatibility.
|
|
100
|
+
|
|
101
|
+
Removes or replaces characters that are not allowed in filenames
|
|
102
|
+
on Windows, macOS, and Linux.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
filename
|
|
107
|
+
The original filename.
|
|
108
|
+
|
|
109
|
+
Returns
|
|
110
|
+
-------
|
|
111
|
+
str
|
|
112
|
+
A sanitized filename string safe for all major operating systems.
|
|
113
|
+
"""
|
|
114
|
+
# Replace characters not allowed in Windows filenames
|
|
115
|
+
# Also replace characters that might be problematic on other systems
|
|
116
|
+
invalid_chars = r'[<>:"/\\|?*\x00-\x1f]'
|
|
117
|
+
sanitized = re.sub(invalid_chars, "_", filename)
|
|
118
|
+
|
|
119
|
+
# Trim spaces and dots from the end (Windows doesn't like them)
|
|
120
|
+
sanitized = sanitized.rstrip(" .")
|
|
121
|
+
|
|
122
|
+
# Trim spaces from the beginning
|
|
123
|
+
sanitized = sanitized.lstrip(" ")
|
|
124
|
+
|
|
125
|
+
# Reserved Windows names (case-insensitive)
|
|
126
|
+
reserved = {
|
|
127
|
+
"CON",
|
|
128
|
+
"PRN",
|
|
129
|
+
"AUX",
|
|
130
|
+
"NUL",
|
|
131
|
+
"COM1",
|
|
132
|
+
"COM2",
|
|
133
|
+
"COM3",
|
|
134
|
+
"COM4",
|
|
135
|
+
"COM5",
|
|
136
|
+
"COM6",
|
|
137
|
+
"COM7",
|
|
138
|
+
"COM8",
|
|
139
|
+
"COM9",
|
|
140
|
+
"LPT1",
|
|
141
|
+
"LPT2",
|
|
142
|
+
"LPT3",
|
|
143
|
+
"LPT4",
|
|
144
|
+
"LPT5",
|
|
145
|
+
"LPT6",
|
|
146
|
+
"LPT7",
|
|
147
|
+
"LPT8",
|
|
148
|
+
"LPT9",
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
# Check if the name (without extension) is reserved
|
|
152
|
+
name_without_ext = sanitized.split(".")[0].upper()
|
|
153
|
+
if name_without_ext in reserved:
|
|
154
|
+
sanitized = f"_{sanitized}"
|
|
155
|
+
|
|
156
|
+
# Ensure non-empty filename
|
|
157
|
+
if not sanitized:
|
|
158
|
+
sanitized = "_"
|
|
159
|
+
|
|
160
|
+
return sanitized
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def build_page_path(
|
|
164
|
+
output_dir: Path,
|
|
165
|
+
space_key: str,
|
|
166
|
+
ancestors: list[str],
|
|
167
|
+
page_title: str,
|
|
168
|
+
) -> Path:
|
|
169
|
+
"""Build the directory path for a page based on its hierarchy.
|
|
170
|
+
|
|
171
|
+
Parameters
|
|
172
|
+
----------
|
|
173
|
+
output_dir
|
|
174
|
+
Base output directory.
|
|
175
|
+
space_key
|
|
176
|
+
The space key.
|
|
177
|
+
ancestors
|
|
178
|
+
List of ancestor page titles (from root to parent).
|
|
179
|
+
page_title
|
|
180
|
+
Title of the current page.
|
|
181
|
+
|
|
182
|
+
Returns
|
|
183
|
+
-------
|
|
184
|
+
Path
|
|
185
|
+
Full path to the page directory.
|
|
186
|
+
"""
|
|
187
|
+
# Start with output_dir/SpaceKey
|
|
188
|
+
path = output_dir / sanitize_filename(space_key)
|
|
189
|
+
|
|
190
|
+
# Add ancestor directories
|
|
191
|
+
for ancestor in ancestors:
|
|
192
|
+
path = path / sanitize_filename(ancestor)
|
|
193
|
+
|
|
194
|
+
# Add the page directory itself
|
|
195
|
+
path = path / sanitize_filename(page_title)
|
|
196
|
+
|
|
197
|
+
return path
|