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.
@@ -0,0 +1,394 @@
1
+ """Confluence push service for uploading content.
2
+
3
+ This module contains the business logic for pushing Confluence content.
4
+ """
5
+
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ from pathlib import Path
10
+
11
+ from atlassian import Confluence
12
+ from tqdm import tqdm
13
+
14
+ from roundtripper.models import PageInfo, PushResult
15
+
16
+ #: Logger instance.
17
+ LOGGER = logging.getLogger(__name__)
18
+
19
+
20
+ class PushService:
21
+ """Service for pushing local content to Confluence."""
22
+
23
+ def __init__(
24
+ self,
25
+ client: Confluence,
26
+ *,
27
+ dry_run: bool = False,
28
+ force: bool = False,
29
+ ) -> None:
30
+ """Initialize the push service.
31
+
32
+ Parameters
33
+ ----------
34
+ client
35
+ Confluence API client (atlassian-python-api Confluence instance).
36
+ dry_run
37
+ If True, only show what would be pushed without actually pushing.
38
+ force
39
+ If True, push even if there are version conflicts.
40
+ """
41
+ self.client = client
42
+ self.dry_run = dry_run
43
+ self.force = force
44
+ self.result = PushResult()
45
+
46
+ def push_page(self, page_path: Path, *, recursive: bool = False) -> PushResult:
47
+ """Push a single page (and optionally descendants) to Confluence.
48
+
49
+ Parameters
50
+ ----------
51
+ page_path
52
+ Path to the page directory containing page.xml and page.json.
53
+ recursive
54
+ If True, also push all child pages in subdirectories.
55
+
56
+ Returns
57
+ -------
58
+ PushResult
59
+ Summary of the push operation.
60
+ """
61
+ LOGGER.debug("Starting push_page: path=%s, recursive=%s", page_path, recursive)
62
+ self._push_page_at_path(page_path)
63
+
64
+ if recursive:
65
+ child_pages = self._find_child_pages(page_path)
66
+ LOGGER.debug("Found %d child pages to push", len(child_pages))
67
+ for child_path in tqdm(child_pages, desc="Pushing child pages", disable=self.dry_run):
68
+ self._push_page_at_path(child_path)
69
+
70
+ return self.result
71
+
72
+ def push_space(self, space_path: Path) -> PushResult:
73
+ """Push all pages in a space directory to Confluence.
74
+
75
+ Parameters
76
+ ----------
77
+ space_path
78
+ Path to the space directory containing page subdirectories.
79
+
80
+ Returns
81
+ -------
82
+ PushResult
83
+ Summary of the push operation.
84
+ """
85
+ LOGGER.debug("Starting push_space: path=%s", space_path)
86
+ all_pages = self._find_all_pages(space_path)
87
+ LOGGER.info("Found %d pages to analyze", len(all_pages))
88
+ LOGGER.debug("Page paths: %s", [str(p) for p in all_pages])
89
+
90
+ for page_path in tqdm(all_pages, desc="Pushing pages", disable=self.dry_run):
91
+ self._push_page_at_path(page_path)
92
+
93
+ return self.result
94
+
95
+ def _push_page_at_path(self, page_path: Path) -> None:
96
+ """Push a single page at the given path.
97
+
98
+ Parameters
99
+ ----------
100
+ page_path
101
+ Path to the page directory.
102
+ """
103
+ xml_file = page_path / "page.xml"
104
+ json_file = page_path / "page.json"
105
+
106
+ if not xml_file.exists() or not json_file.exists():
107
+ LOGGER.warning("Skipping %s: missing page.xml or page.json", page_path)
108
+ return
109
+
110
+ try:
111
+ # Load local content and metadata
112
+ LOGGER.debug("Loading page files from %s", page_path)
113
+ local_content = xml_file.read_text(encoding="utf-8")
114
+ with json_file.open(encoding="utf-8") as f:
115
+ local_metadata = json.load(f)
116
+
117
+ page_info = PageInfo.from_api_response(local_metadata)
118
+ LOGGER.debug(
119
+ "Loaded page: id=%d, title=%s, version=%d",
120
+ page_info.id,
121
+ page_info.title,
122
+ page_info.version.number,
123
+ )
124
+
125
+ # Check if content has changed
126
+ if not self._has_content_changed(page_info, local_content):
127
+ LOGGER.debug("Skipping %s: content unchanged", page_info.title)
128
+ self.result.pages_skipped += 1
129
+ return
130
+
131
+ # Check for version conflicts
132
+ LOGGER.debug("Checking version conflict for page %d", page_info.id)
133
+ conflict = self._check_version_conflict(page_info)
134
+ if conflict and not self.force:
135
+ LOGGER.debug("Version conflict detected: %s", conflict)
136
+ self.result.conflicts.append(conflict)
137
+ return
138
+
139
+ # Push the page
140
+ if self.dry_run:
141
+ if conflict:
142
+ LOGGER.info(
143
+ "📝 WOULD UPDATE (force): %s (v%d → v%d)",
144
+ page_info.title,
145
+ page_info.version.number,
146
+ page_info.version.number + 1,
147
+ )
148
+ else:
149
+ LOGGER.info(
150
+ "📝 WOULD UPDATE: %s (v%d → v%d)",
151
+ page_info.title,
152
+ page_info.version.number,
153
+ page_info.version.number + 1,
154
+ )
155
+ else:
156
+ LOGGER.debug(
157
+ "Calling update_page: page_id=%d, title=%s",
158
+ page_info.id,
159
+ page_info.title,
160
+ )
161
+ self._update_page(page_info, local_content)
162
+ LOGGER.info(
163
+ "✓ Updated: %s (v%d → v%d)",
164
+ page_info.title,
165
+ page_info.version.number,
166
+ page_info.version.number + 1,
167
+ )
168
+ self.result.pages_updated += 1
169
+
170
+ # Handle attachments
171
+ self._push_attachments(page_path, page_info.id)
172
+
173
+ except Exception as e:
174
+ error_msg = f"Failed to push {page_path}: {e}"
175
+ LOGGER.warning(error_msg)
176
+ self.result.errors.append(error_msg)
177
+
178
+ def _has_content_changed(self, page_info: PageInfo, local_content: str) -> bool:
179
+ """Check if local content differs from stored content.
180
+
181
+ Parameters
182
+ ----------
183
+ page_info
184
+ Page metadata from stored JSON.
185
+ local_content
186
+ Current content from page.xml file.
187
+
188
+ Returns
189
+ -------
190
+ bool
191
+ True if content has changed, False otherwise.
192
+ """
193
+ stored_content = page_info.body_storage
194
+ return local_content.strip() != stored_content.strip()
195
+
196
+ def _check_version_conflict(self, page_info: PageInfo) -> str | None:
197
+ """Check if server version is newer than local metadata.
198
+
199
+ Parameters
200
+ ----------
201
+ page_info
202
+ Page metadata from local JSON.
203
+
204
+ Returns
205
+ -------
206
+ str | None
207
+ Conflict message if conflict detected, None otherwise.
208
+ """
209
+ try:
210
+ server_response = self.client.get_page_by_id(page_info.id, expand="version")
211
+ assert isinstance(server_response, dict)
212
+ server_version = server_response.get("version", {}).get("number", 0)
213
+ LOGGER.debug(
214
+ "Version check: page_id=%d, local=%d, server=%d",
215
+ page_info.id,
216
+ page_info.version.number,
217
+ server_version,
218
+ )
219
+
220
+ if server_version > page_info.version.number:
221
+ return (
222
+ f"Conflict: {page_info.title} - "
223
+ f"local version {page_info.version.number}, "
224
+ f"server version {server_version}"
225
+ )
226
+ except Exception as e:
227
+ LOGGER.debug("Could not check version for page %d: %s", page_info.id, e)
228
+
229
+ return None
230
+
231
+ def _update_page(self, page_info: PageInfo, content: str) -> None:
232
+ """Update a page on Confluence.
233
+
234
+ Parameters
235
+ ----------
236
+ page_info
237
+ Page metadata.
238
+ content
239
+ New content to push.
240
+ """
241
+ self.client.update_page(
242
+ page_id=page_info.id,
243
+ title=page_info.title,
244
+ body=content,
245
+ type="page",
246
+ )
247
+
248
+ def _push_attachments(self, page_path: Path, page_id: int) -> None:
249
+ """Push attachments for a page.
250
+
251
+ Parameters
252
+ ----------
253
+ page_path
254
+ Path to the page directory.
255
+ page_id
256
+ Confluence page ID.
257
+ """
258
+ attachments_dir = page_path / "attachments"
259
+ if not attachments_dir.exists():
260
+ LOGGER.debug("No attachments directory at %s", attachments_dir)
261
+ return
262
+
263
+ attachment_files = [f for f in attachments_dir.iterdir() if f.suffix != ".json"]
264
+ LOGGER.debug("Found %d attachment files in %s", len(attachment_files), attachments_dir)
265
+
266
+ for attachment_file in attachment_files:
267
+ metadata_file = attachment_file.with_suffix(attachment_file.suffix + ".json")
268
+
269
+ if self._should_push_attachment(attachment_file, metadata_file):
270
+ if self.dry_run:
271
+ LOGGER.info("📎 WOULD UPLOAD: %s", attachment_file.name)
272
+ else:
273
+ LOGGER.debug(
274
+ "Uploading attachment: %s to page %d", attachment_file.name, page_id
275
+ )
276
+ self._upload_attachment(page_id, attachment_file)
277
+ LOGGER.info("✓ Uploaded: %s", attachment_file.name)
278
+ self.result.attachments_uploaded += 1
279
+ else:
280
+ LOGGER.debug("Skipping unchanged attachment: %s", attachment_file.name)
281
+ self.result.attachments_skipped += 1
282
+
283
+ def _should_push_attachment(self, attachment_file: Path, metadata_file: Path) -> bool:
284
+ """Check if an attachment should be pushed.
285
+
286
+ Parameters
287
+ ----------
288
+ attachment_file
289
+ Path to the attachment file.
290
+ metadata_file
291
+ Path to the attachment metadata JSON file.
292
+
293
+ Returns
294
+ -------
295
+ bool
296
+ True if the attachment should be pushed.
297
+ """
298
+ if not metadata_file.exists():
299
+ # New attachment, should push
300
+ return True
301
+
302
+ # Compare file hash with stored metadata
303
+ with metadata_file.open(encoding="utf-8") as f:
304
+ metadata = json.load(f)
305
+
306
+ stored_size = metadata.get("extensions", {}).get("fileSize", 0)
307
+ current_size = attachment_file.stat().st_size
308
+
309
+ return current_size != stored_size
310
+
311
+ def _upload_attachment(self, page_id: int, attachment_file: Path) -> None:
312
+ """Upload an attachment to a page.
313
+
314
+ Parameters
315
+ ----------
316
+ page_id
317
+ Confluence page ID.
318
+ attachment_file
319
+ Path to the attachment file.
320
+ """
321
+ self.client.attach_file(
322
+ filename=str(attachment_file),
323
+ page_id=str(page_id),
324
+ name=attachment_file.name,
325
+ )
326
+
327
+ def _find_child_pages(self, page_path: Path) -> list[Path]:
328
+ """Find all child page directories under a page.
329
+
330
+ Parameters
331
+ ----------
332
+ page_path
333
+ Path to the parent page directory.
334
+
335
+ Returns
336
+ -------
337
+ list[Path]
338
+ List of paths to child page directories.
339
+ """
340
+ child_pages: list[Path] = []
341
+
342
+ for item in page_path.iterdir():
343
+ if item.is_dir() and item.name != "attachments":
344
+ xml_file = item / "page.xml"
345
+ if xml_file.exists():
346
+ child_pages.append(item)
347
+ # Recursively find grandchildren
348
+ child_pages.extend(self._find_child_pages(item))
349
+
350
+ return child_pages
351
+
352
+ def _find_all_pages(self, space_path: Path) -> list[Path]:
353
+ """Find all page directories in a space.
354
+
355
+ Parameters
356
+ ----------
357
+ space_path
358
+ Path to the space directory.
359
+
360
+ Returns
361
+ -------
362
+ list[Path]
363
+ List of paths to all page directories.
364
+ """
365
+ all_pages: list[Path] = []
366
+
367
+ def find_pages_recursive(directory: Path) -> None:
368
+ for item in directory.iterdir():
369
+ if item.is_dir():
370
+ xml_file = item / "page.xml"
371
+ if xml_file.exists():
372
+ all_pages.append(item)
373
+ # Always search subdirectories (except attachments)
374
+ if item.name != "attachments":
375
+ find_pages_recursive(item)
376
+
377
+ find_pages_recursive(space_path)
378
+ return all_pages
379
+
380
+
381
+ def compute_content_hash(content: str) -> str:
382
+ """Compute SHA256 hash of content.
383
+
384
+ Parameters
385
+ ----------
386
+ content
387
+ Content to hash.
388
+
389
+ Returns
390
+ -------
391
+ str
392
+ Hex digest of the hash.
393
+ """
394
+ return hashlib.sha256(content.encode("utf-8")).hexdigest()
roundtripper/py.typed ADDED
File without changes
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: roundtripper
3
+ Version: 0.2.0
4
+ Summary: Roundtripping with Confluence
5
+ Project-URL: Documentation, https://github.com/holtgrewe/roundtripper
6
+ Project-URL: Issues, https://github.com/holtgrewe/roundtripper/issues
7
+ Project-URL: Source, https://github.com/holtgrewe/roundtripper
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.13
10
+ Requires-Dist: atlassian-python-api>=3.41.0
11
+ Requires-Dist: cyclopts>=4.4.4
12
+ Requires-Dist: httpx>=0.28.1
13
+ Requires-Dist: jmespath>=1.0.1
14
+ Requires-Dist: pydantic-settings>=2.7.0
15
+ Requires-Dist: pydantic>=2.10.6
16
+ Requires-Dist: questionary>=2.0.1
17
+ Requires-Dist: rich>=13.9.4
18
+ Requires-Dist: tqdm>=4.66.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # roundtripper
22
+
23
+ Roundtripping with Confluence
24
+
25
+ ## Setup
26
+
27
+ Setup Python with uv
28
+
29
+ ```bash
30
+ curl -LsSf https://astral.sh/uv/install.sh | sh
31
+ uv python install 3.13
32
+ ```
33
+
34
+ Clone the repository
35
+
36
+ ```bash
37
+ git clone https://github.com/mholtgrewe/roundtripper.git
38
+ ```
39
+
40
+ Run Tests
41
+
42
+ ```bash
43
+ cd roundtripper
44
+ uv sync --group dev
45
+ make test
46
+ ```
47
+
48
+ ## Development
49
+
50
+ ### Check Code Quality
51
+
52
+ ```bash
53
+ make check
54
+ ```
55
+
56
+ ### Format Code
57
+
58
+ ```bash
59
+ make fix
60
+ ```
61
+
62
+ ### Run Tests
63
+
64
+ ```bash
65
+ make test
66
+ ```
67
+
68
+ ### Update Dependencies
69
+
70
+ ```bash
71
+ make lock
72
+ ```
73
+
74
+ ## Usage
75
+
76
+ ```bash
77
+ roundtripper --help
78
+ ```
79
+
80
+ ### Configure Confluence
81
+
82
+ Configure your Confluence credentials and connection settings:
83
+
84
+ ```bash
85
+ roundtripper confluence config
86
+ ```
87
+
88
+ This will open an interactive configuration menu. Configuration is stored in `~/.config/roundtripper/config.json` following the XDG Base Directory specification.
89
+
90
+ To view your current configuration:
91
+
92
+ ```bash
93
+ roundtripper confluence config --show
94
+ ```
95
+
96
+ To jump directly to a specific configuration section:
97
+
98
+ ```bash
99
+ roundtripper confluence config --jump-to auth.confluence
100
+ ```
101
+
102
+ ## Acknowledgments
103
+
104
+ This project includes code adapted from [confluence-markdown-exporter](https://github.com/Spenhouet/confluence-markdown-exporter) by Sebastian Penhouet.
@@ -0,0 +1,17 @@
1
+ roundtripper/__init__.py,sha256=Zn1KFblwuFHiDRdRAiRnDBRkbPttWh44jKa5zG2ov0E,22
2
+ roundtripper/api_client.py,sha256=TvjeGgYxeVfuoBv0wntJzPzkHvqRYjTwieqDWmfoIYU,2458
3
+ roundtripper/cli.py,sha256=Fs4ro-QJMCZI342aaQPo0nASry66EKNJLi9J7ensIfw,1906
4
+ roundtripper/config.py,sha256=utYS2RQ49YcJ0F7SXEC-bap7yZvgMbKC3s5Zi0CXWDY,3607
5
+ roundtripper/config_interactive.py,sha256=hU0SZhgDChW3unK2rK7OJNHxSDAwAGEhZOTxxqeJRRU,21613
6
+ roundtripper/config_store.py,sha256=OtzcW1M_Yjcxx29_8nqBuZowzabLINgdEzQF1_3PBcw,5394
7
+ roundtripper/confluence.py,sha256=Bl71LbaAnVDZilJ7BAT0LfAQhvCs9eM_1dABfMTiEKo,10048
8
+ roundtripper/file_utils.py,sha256=5auQ2GfT0bwUcsyRkfuANx_XcY9T3-WD0QDgZ35MH0I,5184
9
+ roundtripper/models.py,sha256=fSZTWNIf8QcZTkwrIXLa60sNTyinMi5VXYok-KqzNyU,7032
10
+ roundtripper/pull_service.py,sha256=U-QuilbbuKaphvk7TD5yXKzqi4J7XAlto0sRC7di4Sc,12785
11
+ roundtripper/push_service.py,sha256=I5QoyN9ziFgnK0oQTeO95suOuC68qyof3Jfm9794Jrc,12861
12
+ roundtripper/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ roundtripper-0.2.0.dist-info/METADATA,sha256=ORcZPMJFDUeQijiRXxbNBlmtl8FuFiuEjOAg-KDF7GQ,1922
14
+ roundtripper-0.2.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
15
+ roundtripper-0.2.0.dist-info/entry_points.txt,sha256=4_5Kc0VbV00FflxhXMiK42XsyM0lb0JDv6pttd1dgdo,54
16
+ roundtripper-0.2.0.dist-info/licenses/LICENSE,sha256=HPJ6VZ9w3iwEZM0H2CQvy2ruB_G_u57DlhHhl89Y-gM,1388
17
+ roundtripper-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ roundtripper = roundtripper.cli:cli
@@ -0,0 +1,31 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manuel Holtgrewe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ This project includes code adapted from confluence-markdown-exporter:
26
+ https://github.com/Spenhouet/confluence-markdown-exporter
27
+
28
+ Copyright (c) Sebastian Penhouet
29
+
30
+ The adapted code (config.py, config_store.py, and config_interactive.py) is
31
+ licensed under the MIT License. See the original project for details.