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 @@
1
+ __version__ = "0.2.0"
@@ -0,0 +1,83 @@
1
+ """Confluence API client for roundtripper.
2
+
3
+ Adapted from confluence-markdown-exporter by Sebastian Penhouet.
4
+ https://github.com/Spenhouet/confluence-markdown-exporter
5
+ """
6
+
7
+ import logging
8
+ from typing import Any
9
+
10
+ from atlassian import Confluence as ConfluenceApiSdk
11
+
12
+ from roundtripper.config import ApiDetails
13
+ from roundtripper.config_store import get_settings
14
+
15
+ #: Logger instance.
16
+ LOGGER = logging.getLogger(__name__)
17
+
18
+
19
+ class ConfluenceClientFactory:
20
+ """Factory for creating authenticated Confluence API clients with retry config."""
21
+
22
+ def __init__(self, connection_config: dict[str, Any]) -> None:
23
+ """Initialize the factory with connection configuration.
24
+
25
+ Parameters
26
+ ----------
27
+ connection_config
28
+ Connection configuration dictionary with retry/timeout settings.
29
+ """
30
+ self.connection_config = connection_config
31
+
32
+ def create(self, auth: ApiDetails) -> ConfluenceApiSdk:
33
+ """Create an authenticated Confluence client.
34
+
35
+ Parameters
36
+ ----------
37
+ auth
38
+ API details including URL and credentials.
39
+
40
+ Returns
41
+ -------
42
+ ConfluenceApiSdk
43
+ Authenticated Confluence API client.
44
+
45
+ Raises
46
+ ------
47
+ ConnectionError
48
+ If the connection to Confluence fails.
49
+ """
50
+ try:
51
+ instance = ConfluenceApiSdk(
52
+ url=str(auth.url),
53
+ username=auth.username.get_secret_value() if auth.api_token else None,
54
+ password=auth.api_token.get_secret_value() if auth.api_token else None,
55
+ token=auth.pat.get_secret_value() if auth.pat else None,
56
+ **self.connection_config,
57
+ )
58
+ # Test connection
59
+ instance.get_all_spaces(limit=1)
60
+ except Exception as e:
61
+ msg = f"Confluence connection failed: {e}"
62
+ raise ConnectionError(msg) from e
63
+ return instance
64
+
65
+
66
+ def get_confluence_client() -> ConfluenceApiSdk:
67
+ """Get an authenticated Confluence API client using current settings.
68
+
69
+ Returns
70
+ -------
71
+ ConfluenceApiSdk
72
+ Authenticated Confluence API client.
73
+
74
+ Raises
75
+ ------
76
+ ConnectionError
77
+ If the connection to Confluence fails.
78
+ """
79
+ settings = get_settings()
80
+ auth = settings.auth.confluence
81
+ connection_config = settings.connection_config.model_dump()
82
+
83
+ return ConfluenceClientFactory(connection_config).create(auth)
roundtripper/cli.py ADDED
@@ -0,0 +1,75 @@
1
+ """CLI entry point for roundtripper."""
2
+
3
+ import logging
4
+ from inspect import BoundArguments
5
+ from typing import Annotated, Any, Callable
6
+
7
+ import cyclopts
8
+ from rich.console import Console
9
+ from rich.logging import RichHandler
10
+
11
+ from roundtripper import __version__
12
+ from roundtripper.confluence import app as app_confluence
13
+
14
+ #: Logger instance.
15
+ LOGGER = logging.getLogger(__name__)
16
+
17
+ app = cyclopts.App(
18
+ name="roundtripper",
19
+ help="Roundtripping with Confluence",
20
+ version=__version__,
21
+ default_parameter=cyclopts.Parameter(parse=r"^[^_].*"),
22
+ )
23
+
24
+
25
+ @app.meta.default
26
+ def main(
27
+ *tokens: Annotated[str, cyclopts.Parameter(show=False, allow_leading_hyphen=True)],
28
+ verbose: bool = False,
29
+ ) -> Any: # pragma: no cover
30
+ """Roundtripping with Confluence.
31
+
32
+ Parameters
33
+ ----------
34
+ verbose
35
+ Enable verbose mode.
36
+ """
37
+ # Setup rich console.
38
+ rich_console = Console()
39
+ rich_handler = RichHandler(console=rich_console)
40
+
41
+ # Setup logging.
42
+ lvl = logging.INFO
43
+ FORMAT = "%(message)s"
44
+ if verbose:
45
+ lvl = logging.DEBUG
46
+ logging.basicConfig(level=lvl, handlers=[rich_handler], format=FORMAT, datefmt="[%X]")
47
+
48
+ # Parse CLI and get ignored (non-parsed) parameters
49
+ command: Callable[..., Any]
50
+ bound: BoundArguments
51
+ ignored: dict[str, Any]
52
+ command, bound, ignored = app.parse_args(tokens, console=rich_console) # type: ignore[assignment]
53
+
54
+ # Inject ignored parameters
55
+ ignored_kwargs: dict[str, Any] = {}
56
+ for name in ignored:
57
+ if name == "_console":
58
+ ignored_kwargs[name] = rich_console
59
+ elif name == "_handler":
60
+ ignored_kwargs[name] = rich_handler
61
+
62
+ return command(*bound.args, **bound.kwargs, **ignored_kwargs)
63
+
64
+
65
+ # Register sub-apps
66
+ app.command(app_confluence)
67
+
68
+
69
+ def cli() -> None:
70
+ """CLI entry point for the roundtripper command."""
71
+ app()
72
+
73
+
74
+ if __name__ == "__main__":
75
+ cli()
roundtripper/config.py ADDED
@@ -0,0 +1,110 @@
1
+ """Configuration models for roundtripper.
2
+
3
+ Adapted from confluence-markdown-exporter by Sebastian Penhouet.
4
+ https://github.com/Spenhouet/confluence-markdown-exporter
5
+ """
6
+
7
+ from typing import Literal
8
+
9
+ from pydantic import AnyHttpUrl, BaseModel, Field, SecretStr, field_serializer
10
+
11
+
12
+ class ConnectionConfig(BaseModel):
13
+ """Configuration for the connection like retry options."""
14
+
15
+ backoff_and_retry: bool = Field(
16
+ default=True,
17
+ title="Enable Retry",
18
+ description=(
19
+ "Enable or disable automatic retry with exponential backoff on network errors."
20
+ ),
21
+ )
22
+ backoff_factor: int = Field(
23
+ default=2,
24
+ title="Backoff Factor",
25
+ description=(
26
+ "Multiplier for exponential backoff between retries. "
27
+ "For example, 2 means each retry waits twice as long as the previous."
28
+ ),
29
+ )
30
+ max_backoff_seconds: int = Field(
31
+ default=60,
32
+ title="Max Backoff Seconds",
33
+ description="Maximum number of seconds to wait between retries.",
34
+ )
35
+ max_backoff_retries: int = Field(
36
+ default=5,
37
+ title="Max Retries",
38
+ description="Maximum number of retry attempts before giving up.",
39
+ )
40
+ retry_status_codes: list[int] = Field(
41
+ default_factory=lambda: [413, 429, 502, 503, 504],
42
+ title="Retry Status Codes",
43
+ description="HTTP status codes that should trigger a retry.",
44
+ )
45
+ verify_ssl: bool = Field(
46
+ default=True,
47
+ title="Verify SSL",
48
+ description=(
49
+ "Whether to verify SSL certificates for HTTPS requests. "
50
+ "Set to False only if you are sure about the security of your connection."
51
+ ),
52
+ )
53
+
54
+
55
+ class ApiDetails(BaseModel):
56
+ """API authentication details."""
57
+
58
+ url: AnyHttpUrl | Literal[""] = Field(
59
+ default="",
60
+ title="Instance URL",
61
+ description="Base URL of the Confluence instance.",
62
+ )
63
+ username: SecretStr = Field(
64
+ default=SecretStr(""),
65
+ title="Username (email)",
66
+ description="Username or email for API authentication.",
67
+ )
68
+ api_token: SecretStr = Field(
69
+ default=SecretStr(""),
70
+ title="API Token",
71
+ description=(
72
+ "API token for authentication (if required). "
73
+ "Create an Atlassian API token at "
74
+ "https://id.atlassian.com/manage-profile/security/api-tokens. "
75
+ "See Atlassian documentation for details."
76
+ ),
77
+ )
78
+ pat: SecretStr = Field(
79
+ default=SecretStr(""),
80
+ title="Personal Access Token (PAT)",
81
+ description=(
82
+ "Personal Access Token for authentication. "
83
+ "Set this if you use a PAT instead of username+API token. "
84
+ "See your Atlassian instance documentation for how to create a PAT."
85
+ ),
86
+ )
87
+
88
+ @field_serializer("username", "api_token", "pat", when_used="json")
89
+ def dump_secret(self, v: SecretStr) -> str:
90
+ """Serialize SecretStr fields as plain strings for JSON output."""
91
+ return v.get_secret_value()
92
+
93
+
94
+ class AuthConfig(BaseModel):
95
+ """Authentication configuration for Confluence."""
96
+
97
+ confluence: ApiDetails = Field(
98
+ default_factory=ApiDetails,
99
+ title="Confluence Account",
100
+ description="Authentication for Confluence.",
101
+ )
102
+
103
+
104
+ class ConfigModel(BaseModel):
105
+ """Top-level application configuration model."""
106
+
107
+ connection_config: ConnectionConfig = Field(
108
+ default_factory=ConnectionConfig, title="Connection Configuration"
109
+ )
110
+ auth: AuthConfig = Field(default_factory=AuthConfig, title="Authentication")