roundtripper 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: roundtripper
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Roundtripping with Confluence
5
5
  Project-URL: Documentation, https://github.com/holtgrewe/roundtripper
6
6
  Project-URL: Issues, https://github.com/holtgrewe/roundtripper/issues
@@ -4,7 +4,7 @@ requires = ["hatchling"]
4
4
 
5
5
  [project]
6
6
  name = "roundtripper"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Roundtripping with Confluence"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.13"
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -48,6 +48,14 @@ class ConfluenceClientFactory:
48
48
  If the connection to Confluence fails.
49
49
  """
50
50
  try:
51
+ LOGGER.debug("Creating Confluence API client for URL: %s", str(auth.url))
52
+
53
+ # Determine authentication method for logging
54
+ if auth.pat:
55
+ LOGGER.debug("Using Personal Access Token (PAT) authentication")
56
+ elif auth.api_token:
57
+ LOGGER.debug("Using Basic authentication (username + API token)")
58
+
51
59
  instance = ConfluenceApiSdk(
52
60
  url=str(auth.url),
53
61
  username=auth.username.get_secret_value() if auth.api_token else None,
@@ -56,8 +64,11 @@ class ConfluenceClientFactory:
56
64
  **self.connection_config,
57
65
  )
58
66
  # Test connection
67
+ LOGGER.debug("Testing connection by fetching space list...")
59
68
  instance.get_all_spaces(limit=1)
69
+ LOGGER.debug("Connection test successful")
60
70
  except Exception as e:
71
+ LOGGER.error("Confluence connection failed: %s", e)
61
72
  msg = f"Confluence connection failed: {e}"
62
73
  raise ConnectionError(msg) from e
63
74
  return instance
@@ -76,8 +87,10 @@ def get_confluence_client() -> ConfluenceApiSdk:
76
87
  ConnectionError
77
88
  If the connection to Confluence fails.
78
89
  """
90
+ LOGGER.debug("Loading Confluence settings from configuration")
79
91
  settings = get_settings()
80
92
  auth = settings.auth.confluence
81
93
  connection_config = settings.connection_config.model_dump()
82
94
 
95
+ LOGGER.debug("Initializing Confluence API client")
83
96
  return ConfluenceClientFactory(connection_config).create(auth)
@@ -10,6 +10,7 @@ from rich.logging import RichHandler
10
10
 
11
11
  from roundtripper import __version__
12
12
  from roundtripper.confluence import app as app_confluence
13
+ from roundtripper.file_utils import is_xmllint_available
13
14
 
14
15
  #: Logger instance.
15
16
  LOGGER = logging.getLogger(__name__)
@@ -45,6 +46,16 @@ def main(
45
46
  lvl = logging.DEBUG
46
47
  logging.basicConfig(level=lvl, handlers=[rich_handler], format=FORMAT, datefmt="[%X]")
47
48
 
49
+ # Check for xmllint availability
50
+ if not is_xmllint_available():
51
+ rich_console.print(
52
+ "[yellow]Warning: xmllint is not available. XML output will not be formatted.[/yellow]"
53
+ )
54
+ rich_console.print("[yellow]Install xmllint for pretty-printed XML output:[/yellow]")
55
+ rich_console.print("[yellow] - Ubuntu/Debian: sudo apt-get install libxml2-utils[/yellow]")
56
+ rich_console.print("[yellow] - macOS: brew install libxml2[/yellow]")
57
+ rich_console.print("[yellow] - Fedora/RHEL: sudo dnf install libxml2[/yellow]")
58
+
48
59
  # Parse CLI and get ignored (non-parsed) parameters
49
60
  command: Callable[..., Any]
50
61
  bound: BoundArguments
@@ -68,7 +79,7 @@ app.command(app_confluence)
68
79
 
69
80
  def cli() -> None:
70
81
  """CLI entry point for the roundtripper command."""
71
- app()
82
+ app.meta()
72
83
 
73
84
 
74
85
  if __name__ == "__main__":
@@ -8,6 +8,7 @@ import cyclopts
8
8
  from roundtripper.api_client import get_confluence_client
9
9
  from roundtripper.config_interactive import main_config_menu_loop
10
10
  from roundtripper.config_store import get_settings
11
+ from roundtripper.diff_service import DiffService
11
12
  from roundtripper.pull_service import PullService
12
13
  from roundtripper.push_service import PushService
13
14
 
@@ -198,12 +199,14 @@ def pull(
198
199
 
199
200
  @app.command
200
201
  def push(
202
+ message: str,
201
203
  *,
202
204
  page_path: Path | None = None,
203
205
  space_path: Path | None = None,
204
206
  recursive: bool = False,
205
207
  dry_run: bool = False,
206
208
  force: bool = False,
209
+ interactive: bool = True,
207
210
  verbose: bool = False,
208
211
  ) -> None:
209
212
  """Push local content back to Confluence.
@@ -213,6 +216,8 @@ def push(
213
216
 
214
217
  Parameters
215
218
  ----------
219
+ message
220
+ Version comment/message for the update (required).
216
221
  page_path
217
222
  Path to a page directory to push (contains page.xml and page.json).
218
223
  space_path
@@ -223,6 +228,8 @@ def push(
223
228
  Show what would be pushed without actually pushing.
224
229
  force
225
230
  Push even if there are version conflicts (overwrites server content).
231
+ interactive
232
+ Prompt for confirmation before updating each page (default: True).
226
233
  verbose
227
234
  Enable debug logging.
228
235
  """
@@ -253,7 +260,9 @@ def push(
253
260
  raise SystemExit(1) from e
254
261
 
255
262
  # Create push service
256
- service = PushService(client, dry_run=dry_run, force=force)
263
+ service = PushService(
264
+ client, message=message, dry_run=dry_run, force=force, interactive=interactive
265
+ )
257
266
 
258
267
  if dry_run:
259
268
  LOGGER.info("[DRY RUN] Analyzing changes...")
@@ -305,3 +314,86 @@ def push(
305
314
  LOGGER.info("Run without --dry-run to apply changes.")
306
315
  else:
307
316
  LOGGER.info("✓ Push completed successfully!")
317
+
318
+
319
+ @app.command
320
+ def diff(
321
+ *,
322
+ local_path: Path,
323
+ space: str | None = None,
324
+ page_id: int | None = None,
325
+ recursive: bool = True,
326
+ verbose: bool = False,
327
+ ) -> None:
328
+ """Compare local content with remote Confluence content.
329
+
330
+ Downloads the latest version from Confluence to a temporary location and
331
+ displays the differences using a colored diff viewer (like git).
332
+
333
+ Parameters
334
+ ----------
335
+ local_path
336
+ Path to the local page or space directory to compare.
337
+ space
338
+ Space key to compare with (for space-level comparison).
339
+ page_id
340
+ Specific page ID to compare with.
341
+ recursive
342
+ When comparing a specific page, also compare all descendants.
343
+ verbose
344
+ Enable debug logging.
345
+ """
346
+ if verbose:
347
+ logging.getLogger("roundtripper").setLevel(logging.DEBUG)
348
+
349
+ if not space and not page_id:
350
+ LOGGER.error("Either --space or --page-id must be specified")
351
+ raise SystemExit(1)
352
+
353
+ if space and page_id:
354
+ LOGGER.error("Cannot specify both --space and --page-id")
355
+ raise SystemExit(1)
356
+
357
+ # Validate local path exists
358
+ if not local_path.exists():
359
+ LOGGER.error("Local path does not exist: %s", local_path)
360
+ raise SystemExit(1)
361
+
362
+ # Get Confluence client
363
+ try:
364
+ client = get_confluence_client()
365
+ except ConnectionError as e:
366
+ LOGGER.error("Failed to connect to Confluence: %s", e)
367
+ LOGGER.info("Run 'roundtripper confluence ping' to test your connection")
368
+ raise SystemExit(1) from e
369
+
370
+ # Create diff service
371
+ service = DiffService(client, local_path)
372
+
373
+ # Perform diff
374
+ if space:
375
+ LOGGER.info("Comparing local content with Confluence space: %s", space)
376
+ result = service.diff_space(space)
377
+ else:
378
+ assert page_id is not None # for type checker
379
+ LOGGER.info(
380
+ "Comparing local content with Confluence page: %d (recursive=%s)",
381
+ page_id,
382
+ recursive,
383
+ )
384
+ result = service.diff_page(page_id, recursive=recursive)
385
+
386
+ # Summary
387
+ if result.errors:
388
+ LOGGER.error("")
389
+ LOGGER.error("Errors encountered during diff:")
390
+ for error in result.errors:
391
+ LOGGER.error(" - %s", error)
392
+ raise SystemExit(1)
393
+
394
+ if result.has_differences:
395
+ LOGGER.info("")
396
+ LOGGER.info("✓ Diff completed - differences found")
397
+ raise SystemExit(1) # Exit with error code when differences exist
398
+ else:
399
+ LOGGER.info("✓ Diff completed - no differences")
@@ -0,0 +1,195 @@
1
+ """Confluence diff service for comparing local and remote content.
2
+
3
+ This module contains the business logic for comparing local Confluence content
4
+ with remote content and displaying differences.
5
+ """
6
+
7
+ import logging
8
+ import os
9
+ import subprocess
10
+ import tempfile
11
+ from pathlib import Path
12
+
13
+ from atlassian import Confluence
14
+
15
+ from roundtripper.models import DiffResult
16
+ from roundtripper.pull_service import PullService
17
+
18
+ #: Logger instance.
19
+ LOGGER = logging.getLogger(__name__)
20
+
21
+
22
+ class DiffService:
23
+ """Service for comparing local and remote Confluence content."""
24
+
25
+ def __init__(
26
+ self,
27
+ client: Confluence,
28
+ local_path: Path,
29
+ ) -> None:
30
+ """Initialize the diff service.
31
+
32
+ Parameters
33
+ ----------
34
+ client
35
+ Confluence API client (atlassian-python-api Confluence instance).
36
+ local_path
37
+ Path to the local content to compare.
38
+ """
39
+ self.client = client
40
+ self.local_path = local_path
41
+ self.result = DiffResult()
42
+
43
+ def diff_space(self, space_key: str) -> DiffResult:
44
+ """Compare local space content with remote Confluence space.
45
+
46
+ Parameters
47
+ ----------
48
+ space_key
49
+ The space key to compare.
50
+
51
+ Returns
52
+ -------
53
+ DiffResult
54
+ Result of the diff operation.
55
+ """
56
+ with tempfile.TemporaryDirectory() as temp_dir:
57
+ temp_path = Path(temp_dir)
58
+
59
+ LOGGER.info("Pulling latest content from Confluence space: %s", space_key)
60
+ pull_service = PullService(self.client, temp_path)
61
+ pull_result = pull_service.pull_space(space_key)
62
+
63
+ if pull_result.errors:
64
+ LOGGER.warning("Errors occurred during pull:")
65
+ for error in pull_result.errors:
66
+ LOGGER.warning(" - %s", error)
67
+ self.result.errors.append(error)
68
+
69
+ # Run diff
70
+ self._run_diff(self.local_path, temp_path)
71
+
72
+ return self.result
73
+
74
+ def diff_page(self, page_id: int, *, recursive: bool = False) -> DiffResult:
75
+ """Compare local page content with remote Confluence page.
76
+
77
+ Parameters
78
+ ----------
79
+ page_id
80
+ The page ID to compare.
81
+ recursive
82
+ If True, also compare all descendant pages.
83
+
84
+ Returns
85
+ -------
86
+ DiffResult
87
+ Result of the diff operation.
88
+ """
89
+ with tempfile.TemporaryDirectory() as temp_dir:
90
+ temp_path = Path(temp_dir)
91
+
92
+ LOGGER.info("Pulling latest content from Confluence page: %d", page_id)
93
+ pull_service = PullService(self.client, temp_path)
94
+ pull_result = pull_service.pull_page(page_id, recursive=recursive)
95
+
96
+ if pull_result.errors:
97
+ LOGGER.warning("Errors occurred during pull:")
98
+ for error in pull_result.errors:
99
+ LOGGER.warning(" - %s", error)
100
+ self.result.errors.append(error)
101
+
102
+ # Run diff
103
+ self._run_diff(self.local_path, temp_path)
104
+
105
+ return self.result
106
+
107
+ def _run_diff(self, local_path: Path, remote_path: Path) -> None:
108
+ """Run diff and display results through pager.
109
+
110
+ Parameters
111
+ ----------
112
+ local_path
113
+ Path to local content.
114
+ remote_path
115
+ Path to remote (freshly pulled) content.
116
+ """
117
+ # Get the pager command from environment or use default
118
+ pager = os.environ.get("PAGER", "less -R")
119
+
120
+ # Build diff command
121
+ # Use unified diff format with colors and context
122
+ # Only compare XML files (like push does), exclude JSON metadata
123
+ diff_cmd = [
124
+ "diff",
125
+ "-urN", # unified format, recursive, show new files
126
+ "--color=always", # colored output
127
+ "--exclude=*.json", # exclude JSON metadata files
128
+ str(local_path),
129
+ str(remote_path),
130
+ ]
131
+
132
+ try:
133
+ # Run diff command
134
+ diff_result = subprocess.run(
135
+ diff_cmd,
136
+ capture_output=True,
137
+ text=True,
138
+ timeout=30,
139
+ )
140
+
141
+ # diff exits with 0 if no changes, 1 if changes found, >1 for errors
142
+ if diff_result.returncode > 1:
143
+ error_msg = f"Diff command failed: {diff_result.stderr}"
144
+ LOGGER.error(error_msg)
145
+ self.result.errors.append(error_msg)
146
+ return
147
+
148
+ diff_output = diff_result.stdout
149
+
150
+ if not diff_output:
151
+ LOGGER.info("")
152
+ LOGGER.info("=" * 70)
153
+ LOGGER.info("✓ No differences found")
154
+ LOGGER.info("=" * 70)
155
+ LOGGER.info("")
156
+ LOGGER.info("Local content is identical to remote Confluence content.")
157
+ self.result.has_differences = False
158
+ return
159
+
160
+ self.result.has_differences = True
161
+
162
+ # Display through pager
163
+ LOGGER.info("")
164
+ LOGGER.info("=" * 70)
165
+ LOGGER.info("Displaying differences")
166
+ LOGGER.info("=" * 70)
167
+ LOGGER.info("")
168
+
169
+ pager_cmd = pager.split()
170
+ pager_process = subprocess.Popen(
171
+ pager_cmd,
172
+ stdin=subprocess.PIPE,
173
+ text=True,
174
+ )
175
+
176
+ pager_process.communicate(input=diff_output)
177
+
178
+ if pager_process.returncode != 0:
179
+ # Fallback to direct print if pager fails
180
+ LOGGER.warning("Pager failed, printing diff directly:")
181
+ print(diff_output)
182
+
183
+ except subprocess.TimeoutExpired:
184
+ error_msg = "Diff command timed out"
185
+ LOGGER.error(error_msg)
186
+ self.result.errors.append(error_msg)
187
+ except FileNotFoundError as e:
188
+ error_msg = f"Command not found: {e.filename}"
189
+ LOGGER.error(error_msg)
190
+ LOGGER.error("Please ensure 'diff' is installed on your system")
191
+ self.result.errors.append(error_msg)
192
+ except Exception as e:
193
+ error_msg = f"Error running diff: {e}"
194
+ LOGGER.error(error_msg)
195
+ self.result.errors.append(error_msg)
@@ -5,52 +5,88 @@ https://github.com/Spenhouet/confluence-markdown-exporter
5
5
  """
6
6
 
7
7
  import json
8
+ import logging
8
9
  import re
9
- import xml.dom.minidom
10
+ import shutil
11
+ import subprocess
12
+ import textwrap
10
13
  from pathlib import Path
11
14
  from typing import Any
12
15
 
16
+ #: Logger instance.
17
+ LOGGER = logging.getLogger(__name__)
18
+
19
+
20
+ def is_xmllint_available() -> bool:
21
+ """Check if xmllint is available on the system.
22
+
23
+ Returns
24
+ -------
25
+ bool
26
+ True if xmllint is found in PATH.
27
+ """
28
+ return shutil.which("xmllint") is not None
29
+
13
30
 
14
31
  def format_xml(xml_content: str, max_line_length: int = 120) -> str:
15
- """Format XML with proper indentation and line wrapping.
32
+ """Format XML with proper indentation using xmllint.
16
33
 
17
34
  Parameters
18
35
  ----------
19
36
  xml_content
20
37
  Raw XML content to format.
21
38
  max_line_length
22
- Maximum line length before wrapping.
39
+ Maximum line length before wrapping (currently unused, kept for API compatibility).
23
40
 
24
41
  Returns
25
42
  -------
26
43
  str
27
44
  Formatted XML string with proper indentation.
28
45
  """
46
+ if not is_xmllint_available():
47
+ LOGGER.debug("xmllint not available, returning unformatted XML")
48
+ return xml_content
49
+
50
+ # Wrap XML fragments with a temporary root element to ensure valid XML
51
+ # This handles cases like <p>One</p><p>Two</p> which have multiple roots
52
+ wrapped_xml = f"<root>{xml_content}</root>"
53
+
29
54
  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
55
+ # Use xmllint to format the XML
56
+ result = subprocess.run(
57
+ ["xmllint", "--format", "-"],
58
+ input=wrapped_xml.encode("utf-8"),
59
+ capture_output=True,
60
+ check=True,
61
+ timeout=10,
62
+ )
63
+ formatted_output = result.stdout.decode("utf-8")
64
+
65
+ # Remove the temporary root wrapper and XML declaration
66
+ # Find content between <root> and </root>
67
+ start_tag = "<root>"
68
+ end_tag = "</root>"
69
+ start_idx = formatted_output.find(start_tag)
70
+ end_idx = formatted_output.find(end_tag)
71
+
72
+ if start_idx != -1 and end_idx != -1:
73
+ # Extract content between root tags
74
+ content = formatted_output[start_idx + len(start_tag) : end_idx]
75
+ # Remove leading/trailing whitespace and dedent to remove wrapper indentation
76
+ return textwrap.dedent(content).strip()
77
+ else:
78
+ # If we can't find the tags, return original content
79
+ LOGGER.warning("Could not find root tags in formatted output")
80
+ return xml_content
81
+
82
+ except subprocess.CalledProcessError as e:
83
+ LOGGER.warning("xmllint formatting failed: %s", e.stderr.decode("utf-8", errors="ignore"))
84
+ return xml_content
85
+ except subprocess.TimeoutExpired:
86
+ LOGGER.warning("xmllint formatting timed out")
87
+ return xml_content
88
+ except Exception as e: # pragma: no cover
89
+ LOGGER.warning("Unexpected error formatting XML: %s", e)
54
90
  return xml_content
55
91
 
56
92
 
@@ -252,3 +252,10 @@ class PushResult(BaseModel):
252
252
  attachments_skipped: int = 0
253
253
  conflicts: list[str] = Field(default_factory=list)
254
254
  errors: list[str] = Field(default_factory=list)
255
+
256
+
257
+ class DiffResult(BaseModel):
258
+ """Result of a diff operation."""
259
+
260
+ has_differences: bool = False
261
+ errors: list[str] = Field(default_factory=list)
@@ -58,20 +58,24 @@ class PullService:
58
58
  Summary of the pull operation.
59
59
  """
60
60
  LOGGER.info("Fetching space info for: %s", space_key)
61
+ LOGGER.info("Connecting to Confluence API...")
61
62
 
62
63
  space_data = self.client.get_space(space_key, expand="homepage")
63
64
  assert isinstance(space_data, dict) # atlassian SDK return type is too broad
64
65
  space = SpaceInfo.from_api_response(space_data)
66
+ LOGGER.info("Space found: %s (key=%s)", space.name, space_key)
65
67
 
66
68
  if space.homepage_id is None:
67
69
  LOGGER.warning("Space '%s' has no homepage. Nothing to pull.", space_key)
68
70
  return self.result
69
71
 
70
72
  # Get all descendant page IDs
73
+ LOGGER.info("Discovering all pages in space...")
71
74
  page_ids = self._get_all_descendant_ids(space.homepage_id)
72
75
  page_ids.insert(0, space.homepage_id)
73
76
 
74
77
  LOGGER.info("Found %d pages to pull", len(page_ids))
78
+ LOGGER.info("Starting download...")
75
79
 
76
80
  # Pull each page with progress bar
77
81
  for page_id in tqdm(page_ids, desc="Pulling pages", disable=self.dry_run):
@@ -95,9 +99,11 @@ class PullService:
95
99
  Summary of the pull operation.
96
100
  """
97
101
  if recursive:
102
+ LOGGER.info("Discovering descendant pages for page %d...", page_id)
98
103
  page_ids = self._get_all_descendant_ids(page_id)
99
104
  page_ids.insert(0, page_id)
100
105
  LOGGER.info("Found %d pages to pull (including descendants)", len(page_ids))
106
+ LOGGER.info("Starting download...")
101
107
 
102
108
  for pid in tqdm(page_ids, desc="Pulling pages", disable=self.dry_run):
103
109
  self._pull_page(pid)
@@ -125,6 +131,7 @@ class PullService:
125
131
  "limit": 100,
126
132
  }
127
133
  results: list[dict[str, Any]] = []
134
+ LOGGER.debug("Searching for descendants using CQL: type=page AND ancestor=%d", page_id)
128
135
 
129
136
  try:
130
137
  response = self.client.get(url, params=params)
@@ -133,6 +140,7 @@ class PullService:
133
140
  next_path = response.get("_links", {}).get("next")
134
141
 
135
142
  while next_path:
143
+ LOGGER.debug("Fetching next page of descendants (found %d so far)", len(results))
136
144
  response = self.client.get(next_path)
137
145
  assert isinstance(response, dict) # atlassian SDK return type is too broad
138
146
  results.extend(response.get("results", []))
@@ -153,6 +161,7 @@ class PullService:
153
161
  The page ID to pull.
154
162
  """
155
163
  try:
164
+ LOGGER.debug("Fetching page metadata from API: page_id=%d", page_id)
156
165
  page_data = self.client.get_page_by_id(
157
166
  page_id,
158
167
  expand="body.storage,body.view,body.export_view,body.editor2,"
@@ -160,6 +169,7 @@ class PullService:
160
169
  )
161
170
  assert isinstance(page_data, dict) # atlassian SDK return type is too broad
162
171
  page = PageInfo.from_api_response(page_data)
172
+ LOGGER.debug("Fetched page: %s (v%d)", page.title, page.version.number)
163
173
  except Exception as e:
164
174
  error_msg = f"Failed to fetch page {page_id}: {e}"
165
175
  LOGGER.warning(error_msg)
@@ -189,7 +199,9 @@ class PullService:
189
199
  self.result.pages_skipped += 1
190
200
  else:
191
201
  # Save page content (Confluence storage format)
202
+ LOGGER.debug("Saving page content to: %s", page_dir)
192
203
  self._save_page_content(page_dir, page)
204
+ LOGGER.info("Downloaded: %s", page.title)
193
205
  self.result.pages_downloaded += 1
194
206
 
195
207
  # Pull attachments
@@ -287,6 +299,7 @@ class PullService:
287
299
  attachments_dir = page_dir / "attachments"
288
300
  start = 0
289
301
  limit = 50
302
+ LOGGER.debug("Checking for attachments on page %d", page_id)
290
303
 
291
304
  while True:
292
305
  try:
@@ -305,6 +318,8 @@ class PullService:
305
318
  if not results:
306
319
  break
307
320
 
321
+ LOGGER.debug("Found %d attachments (batch starting at %d)", len(results), start)
322
+
308
323
  for att_data in results:
309
324
  attachment = AttachmentInfo.from_api_response(att_data)
310
325
  self._download_attachment(attachment, attachments_dir)
@@ -342,9 +357,11 @@ class PullService:
342
357
  # Download attachment content
343
358
  try:
344
359
  download_url = str(self.client.url) + attachment.download_link
360
+ LOGGER.debug("Downloading attachment: %s", filename)
345
361
  response = self.client._session.get(download_url)
346
362
  response.raise_for_status()
347
363
  content = response.content
364
+ LOGGER.debug("Downloaded %d bytes for attachment: %s", len(content), filename)
348
365
  except Exception as e:
349
366
  error_msg = f"Failed to download attachment '{filename}': {e}"
350
367
  LOGGER.warning(error_msg)
@@ -356,7 +373,7 @@ class PullService:
356
373
  save_json(json_path, attachment.raw_api_response)
357
374
 
358
375
  self.result.attachments_downloaded += 1
359
- LOGGER.debug("Downloaded attachment: %s", filename)
376
+ LOGGER.info("Downloaded attachment: %s", filename)
360
377
 
361
378
  def _is_attachment_up_to_date(self, json_path: Path, current_version: int) -> bool:
362
379
  """Check if an attachment is up to date based on version number.
@@ -3,6 +3,7 @@
3
3
  This module contains the business logic for pushing Confluence content.
4
4
  """
5
5
 
6
+ import difflib
6
7
  import hashlib
7
8
  import json
8
9
  import logging
@@ -11,7 +12,9 @@ from pathlib import Path
11
12
  from atlassian import Confluence
12
13
  from tqdm import tqdm
13
14
 
15
+ from roundtripper.file_utils import format_xml
14
16
  from roundtripper.models import PageInfo, PushResult
17
+ from roundtripper.pull_service import PullService
15
18
 
16
19
  #: Logger instance.
17
20
  LOGGER = logging.getLogger(__name__)
@@ -23,9 +26,11 @@ class PushService:
23
26
  def __init__(
24
27
  self,
25
28
  client: Confluence,
29
+ message: str,
26
30
  *,
27
31
  dry_run: bool = False,
28
32
  force: bool = False,
33
+ interactive: bool = True,
29
34
  ) -> None:
30
35
  """Initialize the push service.
31
36
 
@@ -33,14 +38,20 @@ class PushService:
33
38
  ----------
34
39
  client
35
40
  Confluence API client (atlassian-python-api Confluence instance).
41
+ message
42
+ Version comment/message for updates.
36
43
  dry_run
37
44
  If True, only show what would be pushed without actually pushing.
38
45
  force
39
46
  If True, push even if there are version conflicts.
47
+ interactive
48
+ If True, prompt for confirmation before updating each page.
40
49
  """
41
50
  self.client = client
51
+ self.message = message
42
52
  self.dry_run = dry_run
43
53
  self.force = force
54
+ self.interactive = interactive
44
55
  self.result = PushResult()
45
56
 
46
57
  def push_page(self, page_path: Path, *, recursive: bool = False) -> PushResult:
@@ -59,11 +70,15 @@ class PushService:
59
70
  Summary of the push operation.
60
71
  """
61
72
  LOGGER.debug("Starting push_page: path=%s, recursive=%s", page_path, recursive)
73
+ LOGGER.info("Analyzing page at: %s", page_path)
62
74
  self._push_page_at_path(page_path)
63
75
 
64
76
  if recursive:
77
+ LOGGER.info("Discovering child pages for recursive push...")
65
78
  child_pages = self._find_child_pages(page_path)
66
79
  LOGGER.debug("Found %d child pages to push", len(child_pages))
80
+ if child_pages:
81
+ LOGGER.info("Found %d child pages, starting push...", len(child_pages))
67
82
  for child_path in tqdm(child_pages, desc="Pushing child pages", disable=self.dry_run):
68
83
  self._push_page_at_path(child_path)
69
84
 
@@ -83,9 +98,11 @@ class PushService:
83
98
  Summary of the push operation.
84
99
  """
85
100
  LOGGER.debug("Starting push_space: path=%s", space_path)
101
+ LOGGER.info("Discovering all pages in space directory...")
86
102
  all_pages = self._find_all_pages(space_path)
87
103
  LOGGER.info("Found %d pages to analyze", len(all_pages))
88
104
  LOGGER.debug("Page paths: %s", [str(p) for p in all_pages])
105
+ LOGGER.info("Starting push operations...")
89
106
 
90
107
  for page_path in tqdm(all_pages, desc="Pushing pages", disable=self.dry_run):
91
108
  self._push_page_at_path(page_path)
@@ -122,8 +139,10 @@ class PushService:
122
139
  page_info.version.number,
123
140
  )
124
141
 
125
- # Check if content has changed
126
- if not self._has_content_changed(page_info, local_content):
142
+ # Check if content has changed and get server content for diff
143
+ LOGGER.debug("Checking if content has changed for: %s", page_info.title)
144
+ server_content = self._get_server_content(page_info)
145
+ if not self._has_content_changed_with_server(local_content, server_content):
127
146
  LOGGER.debug("Skipping %s: content unchanged", page_info.title)
128
147
  self.result.pages_skipped += 1
129
148
  return
@@ -152,7 +171,23 @@ class PushService:
152
171
  page_info.version.number,
153
172
  page_info.version.number + 1,
154
173
  )
174
+ # Show diff in dry-run mode
175
+ self._show_diff(page_info.title, server_content, local_content)
155
176
  else:
177
+ # Show diff if interactive mode
178
+ if self.interactive:
179
+ self._show_diff(page_info.title, server_content, local_content)
180
+ LOGGER.info("")
181
+ response = input(f"Update '{page_info.title}'? [Y/n/q]: ").strip().lower()
182
+ if response == "q":
183
+ LOGGER.info("Quitting at user request")
184
+ raise SystemExit(0)
185
+ if response == "n":
186
+ LOGGER.info("Skipped: %s", page_info.title)
187
+ self.result.pages_skipped += 1
188
+ return
189
+ # Empty or 'y' continues
190
+
156
191
  LOGGER.debug(
157
192
  "Calling update_page: page_id=%d, title=%s",
158
193
  page_info.id,
@@ -167,6 +202,10 @@ class PushService:
167
202
  )
168
203
  self.result.pages_updated += 1
169
204
 
205
+ # Immediately refresh local files to avoid version conflicts next time
206
+ LOGGER.debug("Refreshing local files after push: %s", page_path)
207
+ self._refresh_local_page(page_info.id, page_path)
208
+
170
209
  # Handle attachments
171
210
  self._push_attachments(page_path, page_info.id)
172
211
 
@@ -175,23 +214,123 @@ class PushService:
175
214
  LOGGER.warning(error_msg)
176
215
  self.result.errors.append(error_msg)
177
216
 
178
- def _has_content_changed(self, page_info: PageInfo, local_content: str) -> bool:
179
- """Check if local content differs from stored content.
217
+ def _get_server_content(self, page_info: PageInfo) -> str:
218
+ """Fetch current content from server.
180
219
 
181
220
  Parameters
182
221
  ----------
183
222
  page_info
184
223
  Page metadata from stored JSON.
224
+
225
+ Returns
226
+ -------
227
+ str
228
+ Server content or stored content as fallback, formatted for comparison.
229
+ """
230
+ try:
231
+ # Fetch current content from server with storage format
232
+ server_response = self.client.get_page_by_id(
233
+ page_info.id, expand="body.storage,version"
234
+ )
235
+ assert isinstance(server_response, dict)
236
+ server_content = server_response.get("body", {}).get("storage", {}).get("value", "")
237
+ # Format server XML to match local formatted XML for accurate comparison
238
+ return format_xml(server_content)
239
+ except Exception as e: # pragma: no cover
240
+ # If we can't fetch from server, fall back to stored content
241
+ LOGGER.warning(
242
+ "Could not fetch server content for page %d: %s. Using stored content.",
243
+ page_info.id,
244
+ e,
245
+ )
246
+ return page_info.body_storage
247
+
248
+ def _has_content_changed_with_server(self, local_content: str, server_content: str) -> bool:
249
+ """Check if local content differs from server content.
250
+
251
+ Parameters
252
+ ----------
185
253
  local_content
186
254
  Current content from page.xml file.
255
+ server_content
256
+ Current content from server.
187
257
 
188
258
  Returns
189
259
  -------
190
260
  bool
191
261
  True if content has changed, False otherwise.
192
262
  """
193
- stored_content = page_info.body_storage
194
- return local_content.strip() != stored_content.strip()
263
+ # Compare normalized content (strip whitespace)
264
+ local_normalized = local_content.strip()
265
+ server_normalized = server_content.strip()
266
+ return local_normalized != server_normalized
267
+
268
+ def _show_diff(self, title: str, server_content: str, local_content: str) -> None:
269
+ """Show unified diff between server and local content.
270
+
271
+ Parameters
272
+ ----------
273
+ title
274
+ Page title for display.
275
+ server_content
276
+ Current content from server.
277
+ local_content
278
+ New content from local file.
279
+ """
280
+ # Split into lines for difflib
281
+ server_lines = server_content.splitlines(keepends=True)
282
+ local_lines = local_content.splitlines(keepends=True)
283
+
284
+ # Generate unified diff
285
+ diff = difflib.unified_diff(
286
+ server_lines,
287
+ local_lines,
288
+ fromfile=f"server/{title}",
289
+ tofile=f"local/{title}",
290
+ lineterm="",
291
+ )
292
+
293
+ # Print diff with some formatting
294
+ diff_lines = list(diff)
295
+ if diff_lines:
296
+ LOGGER.info("")
297
+ LOGGER.info("=" * 70)
298
+ LOGGER.info("Diff for: %s", title)
299
+ LOGGER.info("=" * 70)
300
+ LOGGER.info("")
301
+ for line in diff_lines:
302
+ # Color the diff output
303
+ if line.startswith("+++") or line.startswith("---"):
304
+ print(f"\033[1m{line}\033[0m", end="") # Bold
305
+ elif line.startswith("+"):
306
+ print(f"\033[32m{line}\033[0m", end="") # Green
307
+ elif line.startswith("-"):
308
+ print(f"\033[31m{line}\033[0m", end="") # Red
309
+ elif line.startswith("@@"):
310
+ print(f"\033[36m{line}\033[0m", end="") # Cyan
311
+ else: # pragma: no cover
312
+ print(line, end="")
313
+ print()
314
+
315
+ def _refresh_local_page(self, page_id: int, page_path: Path) -> None:
316
+ """Refresh local page files after successful push.
317
+
318
+ Parameters
319
+ ----------
320
+ page_id
321
+ The page ID that was just updated.
322
+ page_path
323
+ Path to the local page directory.
324
+ """
325
+ try:
326
+ # Create a temporary PullService to refresh this page
327
+ # Use the page's parent directory as output since pull creates the page dir
328
+ pull_service = PullService(self.client, page_path.parent, dry_run=False)
329
+ pull_service._pull_page(page_id)
330
+ LOGGER.debug("Successfully refreshed local files for page %d", page_id)
331
+ except Exception as e: # pragma: no cover
332
+ LOGGER.warning("Failed to refresh local files after push: %s", e)
333
+ LOGGER.warning("You may need to manually pull this page to avoid version conflicts")
195
334
 
196
335
  def _check_version_conflict(self, page_info: PageInfo) -> str | None:
197
336
  """Check if server version is newer than local metadata.
@@ -238,12 +377,19 @@ class PushService:
238
377
  content
239
378
  New content to push.
240
379
  """
380
+ LOGGER.debug(
381
+ "Calling Confluence API update_page: page_id=%d, title=%s",
382
+ page_info.id,
383
+ page_info.title,
384
+ )
241
385
  self.client.update_page(
242
386
  page_id=page_info.id,
243
387
  title=page_info.title,
244
388
  body=content,
245
389
  type="page",
390
+ version_comment=self.message,
246
391
  )
392
+ LOGGER.debug("API call successful for page %d", page_info.id)
247
393
 
248
394
  def _push_attachments(self, page_path: Path, page_id: int) -> None:
249
395
  """Push attachments for a page.
@@ -263,6 +409,9 @@ class PushService:
263
409
  attachment_files = [f for f in attachments_dir.iterdir() if f.suffix != ".json"]
264
410
  LOGGER.debug("Found %d attachment files in %s", len(attachment_files), attachments_dir)
265
411
 
412
+ if attachment_files:
413
+ LOGGER.info("Analyzing %d attachments...", len(attachment_files))
414
+
266
415
  for attachment_file in attachment_files:
267
416
  metadata_file = attachment_file.with_suffix(attachment_file.suffix + ".json")
268
417
 
@@ -273,6 +422,7 @@ class PushService:
273
422
  LOGGER.debug(
274
423
  "Uploading attachment: %s to page %d", attachment_file.name, page_id
275
424
  )
425
+ LOGGER.info("Uploading: %s", attachment_file.name)
276
426
  self._upload_attachment(page_id, attachment_file)
277
427
  LOGGER.info("✓ Uploaded: %s", attachment_file.name)
278
428
  self.result.attachments_uploaded += 1
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"
File without changes
File without changes
File without changes