atli 0.5.1__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.
atli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """atli — Lightweight CLI for self-hosted Jira and Confluence."""
2
+
3
+ __version__ = "0.5.1"
atli/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Allow running atli as `python -m atli`."""
2
+
3
+ from atli.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
atli/cli.py ADDED
@@ -0,0 +1,66 @@
1
+ """Root CLI entry point for `atli`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from atli import __version__
8
+ from atli.config import Config, ConfigError
9
+ from atli.config_commands import config_cmd
10
+ from atli.confluence.commands import conf
11
+ from atli.jira.commands import jira
12
+ from atli.output import fail
13
+ from atli.skills_commands import skills_cmd
14
+
15
+
16
+ def _ensure_config(ctx: click.Context) -> Config:
17
+ """Lazy-load config on first access. Fails with friendly error if broken."""
18
+ if ctx.obj["config"] is None:
19
+ try:
20
+ ctx.obj["config"] = Config.load(ctx.obj["profile"])
21
+ except ConfigError as e:
22
+ fail(str(e))
23
+ return ctx.obj["config"]
24
+
25
+
26
+ @click.group(context_settings={"help_option_names": ["-h", "--help"]})
27
+ @click.version_option(version=__version__, prog_name="atli")
28
+ @click.option("--profile", default="default", show_default=True, help="Config profile to use")
29
+ @click.option("--json", "json_output", is_flag=True, help="Output raw JSON")
30
+ @click.option("--quiet", is_flag=True, help="Suppress progress messages")
31
+ @click.pass_context
32
+ def cli(ctx: click.Context, profile: str, json_output: bool, quiet: bool) -> None:
33
+ """atli — lightweight CLI for self-hosted Jira and Confluence."""
34
+ ctx.ensure_object(dict)
35
+ ctx.obj["json"] = json_output
36
+ ctx.obj["quiet"] = quiet
37
+ ctx.obj["profile"] = profile
38
+ # Defer config loading: let config subcommands run even if config is broken
39
+ ctx.obj["config"] = None
40
+
41
+
42
+ cli.add_command(jira)
43
+ cli.add_command(conf)
44
+ cli.add_command(config_cmd)
45
+ cli.add_command(skills_cmd)
46
+
47
+
48
+ @cli.command("completion")
49
+ @click.argument("shell", type=click.Choice(["bash", "zsh", "fish"]))
50
+ def completion(shell: str) -> None:
51
+ """Print shell completion script. Example: eval \"$(atli completion zsh)\""""
52
+ from click.shell_completion import get_completion_class
53
+
54
+ cls = get_completion_class(shell)
55
+ if cls is None:
56
+ fail(f"unsupported shell: {shell}")
57
+ comp = cls(cli=cli, ctx_args={}, prog_name="atli", complete_var="_ATLI_COMPLETE")
58
+ click.echo(comp.source())
59
+
60
+
61
+ def main() -> None:
62
+ cli()
63
+
64
+
65
+ if __name__ == "__main__":
66
+ main()
atli/client.py ADDED
@@ -0,0 +1,153 @@
1
+ """Base HTTP client for Atlassian REST APIs.
2
+
3
+ Wraps `httpx.Client` with bearer-token auth, JSON content type, and
4
+ exception wrapping that turns HTTPStatusError into a friendly
5
+ `AtlassianAPIError` so command code can show clean errors instead of
6
+ tracebacks.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+
16
+ class AtlassianAPIError(Exception):
17
+ """Raised when an Atlassian REST call returns a non-2xx response."""
18
+
19
+ def __init__(self, status: int, message: str, url: str = "") -> None:
20
+ super().__init__(f"HTTP {status}: {message} ({url})" if url else f"HTTP {status}: {message}")
21
+ self.status = status
22
+ self.message = message
23
+ self.url = url
24
+
25
+
26
+ class AtlassianClient:
27
+ """Thin HTTP wrapper for Jira / Confluence REST APIs.
28
+
29
+ `base_url` should be the host root (e.g. `https://jira.company.com`),
30
+ and each method takes the API path (e.g. `/rest/api/2/issue/PROJ-1`).
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ base_url: str,
36
+ token: str,
37
+ *,
38
+ timeout: float = 30.0,
39
+ client: httpx.Client | None = None,
40
+ ) -> None:
41
+ if not base_url or not token:
42
+ raise ValueError("base_url and token must be non-empty")
43
+ self.base_url = base_url.rstrip("/")
44
+ self.token = token
45
+ self._owned_client = client is None
46
+ self.client = client or httpx.Client(
47
+ headers={
48
+ "Authorization": f"Bearer {token}",
49
+ "Content-Type": "application/json",
50
+ "Accept": "application/json",
51
+ },
52
+ timeout=timeout,
53
+ )
54
+
55
+ def close(self) -> None:
56
+ if self._owned_client:
57
+ self.client.close()
58
+
59
+ def __enter__(self) -> "AtlassianClient":
60
+ return self
61
+
62
+ def __exit__(self, *exc_info: Any) -> None:
63
+ self.close()
64
+
65
+ def request(self, method: str, path: str, **kwargs: Any) -> dict:
66
+ url = f"{self.base_url}{path}"
67
+
68
+ # Special handling for file uploads: httpx needs to set Content-Type with boundary.
69
+ # Temporarily remove Content-Type from client headers, let httpx auto-set it,
70
+ # then restore. This is cleaner than trying to merge headers manually.
71
+ if "files" in kwargs:
72
+ original_content_type = self.client.headers.get("content-type")
73
+ if original_content_type:
74
+ del self.client.headers["content-type"]
75
+ try:
76
+ resp = self.client.request(method, url, **kwargs)
77
+ except httpx.RequestError as e:
78
+ raise AtlassianAPIError(0, f"network error: {e}", url) from e
79
+ finally:
80
+ if original_content_type:
81
+ self.client.headers["content-type"] = original_content_type
82
+ else:
83
+ # Normal request: merge any caller-supplied headers.
84
+ # A value of None means "remove this header".
85
+ extra_headers = kwargs.pop("headers", {})
86
+ if extra_headers:
87
+ headers: dict[str, str] = {}
88
+ for key, value in self.client.headers.items():
89
+ headers[key] = value
90
+ for key, value in extra_headers.items():
91
+ lower_key = key.lower()
92
+ if value is None:
93
+ headers.pop(lower_key, None)
94
+ else:
95
+ headers[lower_key] = value
96
+ kwargs["headers"] = headers
97
+
98
+ try:
99
+ resp = self.client.request(method, url, **kwargs)
100
+ except httpx.RequestError as e:
101
+ raise AtlassianAPIError(0, f"network error: {e}", url) from e
102
+
103
+ # Common response handling: only 2xx is success
104
+ if not (200 <= resp.status_code < 300):
105
+ raise AtlassianAPIError(resp.status_code, _extract_error(resp), url)
106
+
107
+ if not resp.content:
108
+ return {}
109
+ try:
110
+ return resp.json()
111
+ except ValueError:
112
+ # Non-JSON response with 2xx status
113
+ if resp.content.strip():
114
+ # Non-empty non-JSON is unexpected for successful API calls
115
+ raise AtlassianAPIError(
116
+ resp.status_code,
117
+ f"unexpected non-JSON response: {resp.text[:200]}",
118
+ url,
119
+ )
120
+ # Empty body or whitespace-only: treat as empty dict
121
+ return {}
122
+
123
+ def get(self, path: str, **kwargs: Any) -> dict:
124
+ return self.request("GET", path, **kwargs)
125
+
126
+ def post(self, path: str, **kwargs: Any) -> dict:
127
+ return self.request("POST", path, **kwargs)
128
+
129
+ def put(self, path: str, **kwargs: Any) -> dict:
130
+ return self.request("PUT", path, **kwargs)
131
+
132
+ def delete(self, path: str, **kwargs: Any) -> dict:
133
+ return self.request("DELETE", path, **kwargs)
134
+
135
+
136
+ def _extract_error(resp: httpx.Response) -> str:
137
+ """Pull a useful message out of an Atlassian error response."""
138
+ try:
139
+ data = resp.json()
140
+ except ValueError:
141
+ return resp.text.strip()[:200] or resp.reason_phrase
142
+
143
+ # Atlassian shapes vary: errorMessages list, errors dict, or message field.
144
+ if isinstance(data, dict):
145
+ if msgs := data.get("errorMessages"):
146
+ return "; ".join(str(m) for m in msgs)
147
+ if errors := data.get("errors"):
148
+ if isinstance(errors, dict):
149
+ return "; ".join(f"{k}: {v}" for k, v in errors.items())
150
+ return str(errors)
151
+ if msg := data.get("message"):
152
+ return str(msg)
153
+ return resp.text.strip()[:200] or resp.reason_phrase
atli/commands_util.py ADDED
@@ -0,0 +1,45 @@
1
+ """Shared utilities for CLI commands across all Atlassian products."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from atli.client import AtlassianAPIError
8
+ from atli.config import Config, ConfigError
9
+ from atli.confluence.client import ConfluenceClient
10
+ from atli.jira.client import JiraClient
11
+ from atli.output import fail
12
+
13
+
14
+ def make_jira_client(ctx: click.Context) -> JiraClient:
15
+ """Create a JiraClient from context config, or fail with a user-friendly error."""
16
+ cfg: Config = ctx.obj["config"]
17
+ try:
18
+ cfg.require_jira()
19
+ except ConfigError as e:
20
+ fail(str(e))
21
+ return JiraClient(cfg.jira_url, cfg.jira_token)
22
+
23
+
24
+ def make_confluence_client(ctx: click.Context) -> ConfluenceClient:
25
+ """Create a ConfluenceClient from context config, or fail with a user-friendly error."""
26
+ cfg: Config = ctx.obj["config"]
27
+ try:
28
+ cfg.require_confluence()
29
+ except ConfigError as e:
30
+ fail(str(e))
31
+ return ConfluenceClient(cfg.confluence_url, cfg.confluence_token)
32
+
33
+
34
+ def _name(d: dict) -> str:
35
+ """Extract human-readable name from a Jira entity dict (issue, field, user, etc)."""
36
+ if d is None:
37
+ return ""
38
+ return d.get("name") or d.get("displayName") or d.get("key") or d.get("id") or "?"
39
+
40
+
41
+ def _person(d: dict | None) -> str:
42
+ """Extract person name from a Jira user dict."""
43
+ if d is None:
44
+ return ""
45
+ return d.get("displayName") or d.get("name") or d.get("emailAddress") or "?"
atli/config.py ADDED
@@ -0,0 +1,110 @@
1
+ """Configuration management for atli.
2
+
3
+ Reads `~/.config/atli/config.toml`, supports multiple profiles, and lets
4
+ environment variables override file values. Designed so that a missing config
5
+ file is not fatal — env vars alone are enough to run.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ if sys.version_info >= (3, 11):
16
+ import tomllib
17
+ else:
18
+ try:
19
+ import tomli as tomllib
20
+ except ModuleNotFoundError as e:
21
+ raise ImportError(
22
+ "tomli is required for Python 3.10. "
23
+ "Install it with: pip install tomli"
24
+ ) from e
25
+
26
+ def default_config_dir() -> Path:
27
+ """Resolve the config dir at call time so HOME changes are honored."""
28
+ return Path.home() / ".config" / "atli"
29
+
30
+
31
+ def default_config_file() -> Path:
32
+ return default_config_dir() / "config.toml"
33
+
34
+
35
+ ENV_VARS = {
36
+ "jira_url": "ATLI_JIRA_URL",
37
+ "jira_token": "ATLI_JIRA_TOKEN",
38
+ "confluence_url": "ATLI_CONFLUENCE_URL",
39
+ "confluence_token": "ATLI_CONFLUENCE_TOKEN",
40
+ }
41
+
42
+
43
+ class ConfigError(Exception):
44
+ """Raised when required config values are missing or unreadable."""
45
+
46
+
47
+ @dataclass
48
+ class Config:
49
+ """Resolved configuration for one profile."""
50
+
51
+ profile: str = "default"
52
+ jira_url: str = ""
53
+ jira_token: str = ""
54
+ confluence_url: str = ""
55
+ confluence_token: str = ""
56
+
57
+ @classmethod
58
+ def load(
59
+ cls,
60
+ profile: str = "default",
61
+ config_file: Path | None = None,
62
+ env: dict[str, str] | None = None,
63
+ ) -> "Config":
64
+ """Load config for `profile`. Env vars override file values.
65
+
66
+ Missing config file is fine — env vars alone may be enough. Missing
67
+ profile is also fine when env vars supply the values; an explicit
68
+ profile request that has no file *and* no env vars will yield an
69
+ empty Config and let `require_jira()` / `require_confluence()` raise
70
+ a useful error at the point of use.
71
+ """
72
+ path = config_file or default_config_file()
73
+ env = os.environ if env is None else env
74
+
75
+ file_section: dict[str, str] = {}
76
+ if path.exists():
77
+ try:
78
+ with path.open("rb") as f:
79
+ data = tomllib.load(f)
80
+ except Exception as e:
81
+ raise ConfigError(f"failed to parse {path}: {e}")
82
+ if profile not in data and profile != "default":
83
+ raise ConfigError(
84
+ f"profile '{profile}' not found in {path}. "
85
+ f"Available: {sorted(data.keys())}"
86
+ )
87
+ file_section = data.get(profile, {})
88
+
89
+ resolved: dict[str, str] = {}
90
+ for field, env_var in ENV_VARS.items():
91
+ resolved[field] = env.get(env_var) or file_section.get(field, "")
92
+
93
+ return cls(profile=profile, **resolved)
94
+
95
+ def require_jira(self) -> None:
96
+ if not self.jira_url or not self.jira_token:
97
+ raise ConfigError(
98
+ "Jira not configured. Set jira_url + jira_token in "
99
+ f"{default_config_file()} (profile '{self.profile}') or export "
100
+ "ATLI_JIRA_URL and ATLI_JIRA_TOKEN."
101
+ )
102
+
103
+ def require_confluence(self) -> None:
104
+ if not self.confluence_url or not self.confluence_token:
105
+ raise ConfigError(
106
+ "Confluence not configured. Set confluence_url + "
107
+ f"confluence_token in {default_config_file()} (profile "
108
+ f"'{self.profile}') or export ATLI_CONFLUENCE_URL and "
109
+ "ATLI_CONFLUENCE_TOKEN."
110
+ )
@@ -0,0 +1,256 @@
1
+ """`atli config ...` click commands — show, init, path."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ import click
9
+
10
+ from atli.config import (
11
+ ENV_VARS,
12
+ Config,
13
+ ConfigError,
14
+ default_config_dir,
15
+ default_config_file,
16
+ )
17
+ from atli.output import emit_json, emit_kv, fail
18
+
19
+
20
+ CONFIG_STUB = """\
21
+ # atli config — see https://github.com/...
22
+ # Tokens are bearer / Personal Access Tokens (PATs).
23
+
24
+ [default]
25
+ jira_url = "https://jira.example.com"
26
+ jira_token = "REPLACE_WITH_JIRA_PAT"
27
+ confluence_url = "https://wiki.example.com"
28
+ confluence_token = "REPLACE_WITH_CONF_PAT"
29
+
30
+ # Add more profiles as needed:
31
+ #
32
+ # [staging]
33
+ # jira_url = "https://jira-staging.example.com"
34
+ # jira_token = "STAGING_PAT"
35
+ """
36
+
37
+
38
+ @click.group("config")
39
+ def config_cmd() -> None:
40
+ """Inspect and bootstrap atli configuration."""
41
+
42
+
43
+ @config_cmd.command("path")
44
+ @click.pass_context
45
+ def path_cmd(ctx: click.Context) -> None:
46
+ """Print the resolved config file path."""
47
+ p = default_config_file()
48
+ if ctx.obj["json"]:
49
+ emit_json({"path": str(p), "exists": p.exists()})
50
+ return
51
+ click.echo(str(p))
52
+
53
+
54
+ @config_cmd.command("show")
55
+ @click.option("--show-secrets", is_flag=True, help="Print tokens in clear text")
56
+ @click.option("--raw", is_flag=True, help="Print the raw TOML file content")
57
+ @click.pass_context
58
+ def show_cmd(ctx: click.Context, show_secrets: bool, raw: bool) -> None:
59
+ """Show resolved config for the active profile (tokens redacted)."""
60
+ config_path = default_config_file()
61
+
62
+ if raw:
63
+ if not config_path.exists():
64
+ fail(f"no config file at {config_path}")
65
+ click.echo(config_path.read_text(encoding="utf-8"))
66
+ return
67
+
68
+ # Load config for this command (allow it to fail gracefully)
69
+ try:
70
+ cfg = Config.load(ctx.obj["profile"])
71
+ except ConfigError as e:
72
+ fail(str(e))
73
+
74
+ sources = _resolve_sources(cfg.profile, env=os.environ, file_path=config_path)
75
+
76
+ if ctx.obj["json"]:
77
+ emit_json(
78
+ {
79
+ "profile": cfg.profile,
80
+ "config_file": str(config_path),
81
+ "config_file_exists": config_path.exists(),
82
+ "fields": {
83
+ field: {
84
+ "value": (
85
+ getattr(cfg, field)
86
+ if show_secrets or "token" not in field
87
+ else _redact(getattr(cfg, field))
88
+ ),
89
+ "source": sources[field],
90
+ }
91
+ for field in ENV_VARS
92
+ },
93
+ }
94
+ )
95
+ return
96
+
97
+ rows: list[tuple[str, str]] = [
98
+ ("Profile", cfg.profile),
99
+ ("Config file", f"{config_path} ({'exists' if config_path.exists() else 'missing'})"),
100
+ ]
101
+ for field in ENV_VARS:
102
+ value = getattr(cfg, field)
103
+ display = value if show_secrets or "token" not in field else _redact(value)
104
+ rows.append((field, f"{display} ({sources[field]})"))
105
+ emit_kv(rows, json_mode=False)
106
+
107
+
108
+ @config_cmd.command("init")
109
+ @click.option("--force", is_flag=True, help="Overwrite existing config file")
110
+ @click.pass_context
111
+ def init_cmd(ctx: click.Context, force: bool) -> None:
112
+ """Write a stub config file to ~/.config/atli/config.toml."""
113
+ config_dir = default_config_dir()
114
+ config_path = default_config_file()
115
+
116
+ if config_path.exists() and not force:
117
+ fail(f"config already exists at {config_path}. Use --force to overwrite.")
118
+
119
+ config_dir.mkdir(parents=True, exist_ok=True)
120
+ config_path.write_text(CONFIG_STUB, encoding="utf-8")
121
+ # Restrict permissions: tokens are stored here.
122
+ try:
123
+ config_path.chmod(0o600)
124
+ except OSError:
125
+ pass
126
+
127
+ if ctx.obj["json"]:
128
+ emit_json({"path": str(config_path), "wrote": True})
129
+ return
130
+ emit_kv(
131
+ [
132
+ ("Wrote", str(config_path)),
133
+ ("Next", "edit the file and replace REPLACE_WITH_* tokens"),
134
+ ],
135
+ json_mode=False,
136
+ )
137
+
138
+
139
+ def _redact(value: str) -> str:
140
+ if not value:
141
+ return ""
142
+ if len(value) <= 8:
143
+ return "***"
144
+ return f"{value[:4]}***{value[-4:]}"
145
+
146
+
147
+ def _resolve_sources(profile: str, env: dict[str, str], file_path: Path) -> dict[str, str]:
148
+ """Return where each config field came from: 'env' / 'file' / 'default'."""
149
+ in_file: dict[str, bool] = {f: False for f in ENV_VARS}
150
+ if file_path.exists():
151
+ # Use the same TOML library as config.py for Python 3.10 compatibility
152
+ try:
153
+ import tomllib
154
+ except ModuleNotFoundError:
155
+ import tomli as tomllib # type: ignore
156
+
157
+ try:
158
+ with file_path.open("rb") as f:
159
+ data = tomllib.load(f)
160
+ section = data.get(profile, {})
161
+ for field in ENV_VARS:
162
+ if field in section and section[field]:
163
+ in_file[field] = True
164
+ except (OSError, ValueError):
165
+ pass
166
+
167
+ sources: dict[str, str] = {}
168
+ for field, env_var in ENV_VARS.items():
169
+ if env.get(env_var):
170
+ sources[field] = "env"
171
+ elif in_file[field]:
172
+ sources[field] = "file"
173
+ else:
174
+ sources[field] = "(unset)"
175
+ return sources
176
+
177
+
178
+ @config_cmd.command("validate")
179
+ @click.pass_context
180
+ def validate_cmd(ctx: click.Context) -> None:
181
+ """Test connectivity and validate credentials."""
182
+ try:
183
+ cfg = Config.load(ctx.obj["profile"])
184
+ except ConfigError as e:
185
+ fail(str(e))
186
+
187
+ results = {"jira": None, "confluence": None}
188
+ errors = []
189
+
190
+ # Test Jira
191
+ if cfg.jira_url and cfg.jira_token:
192
+ try:
193
+ from atli.jira.client import JiraClient
194
+ client = JiraClient(cfg.jira_url, cfg.jira_token)
195
+ # Try to get current user
196
+ me = client.get("/rest/api/2/myself")
197
+ results["jira"] = {
198
+ "status": "ok",
199
+ "url": cfg.jira_url,
200
+ "user": me.get("displayName") or me.get("name", "unknown"),
201
+ }
202
+ except Exception as e:
203
+ results["jira"] = {"status": "error", "url": cfg.jira_url, "error": str(e)}
204
+ errors.append(f"Jira: {e}")
205
+ else:
206
+ results["jira"] = {"status": "not_configured"}
207
+
208
+ # Test Confluence
209
+ if cfg.confluence_url and cfg.confluence_token:
210
+ try:
211
+ from atli.confluence.client import ConfluenceClient
212
+ client = ConfluenceClient(cfg.confluence_url, cfg.confluence_token)
213
+ # Try to list spaces
214
+ spaces = client.get("/rest/api/space", params={"limit": 1})
215
+ results["confluence"] = {
216
+ "status": "ok",
217
+ "url": cfg.confluence_url,
218
+ "spaces_accessible": len(spaces.get("results", [])) > 0,
219
+ }
220
+ except Exception as e:
221
+ results["confluence"] = {"status": "error", "url": cfg.confluence_url, "error": str(e)}
222
+ errors.append(f"Confluence: {e}")
223
+ else:
224
+ results["confluence"] = {"status": "not_configured"}
225
+
226
+ if ctx.obj["json"]:
227
+ emit_json(results)
228
+ if errors:
229
+ raise SystemExit(1)
230
+ return
231
+
232
+ # Human-readable output
233
+ click.echo("Configuration validation:\n")
234
+
235
+ for service, result in results.items():
236
+ status = result["status"] if result else "not_configured"
237
+ click.echo(f"{service.upper()}:")
238
+ if status == "ok":
239
+ click.echo(f" ✓ Connected to {result['url']}")
240
+ if "user" in result:
241
+ click.echo(f" User: {result['user']}")
242
+ if "spaces_accessible" in result:
243
+ accessible = "yes" if result["spaces_accessible"] else "no spaces found"
244
+ click.echo(f" Spaces accessible: {accessible}")
245
+ elif status == "error":
246
+ click.echo(f" ✗ Failed to connect to {result['url']}")
247
+ click.echo(f" Error: {result['error']}", err=True)
248
+ else:
249
+ click.echo(" - Not configured")
250
+ click.echo()
251
+
252
+ if errors:
253
+ fail(f"{len(errors)} validation error(s)")
254
+ else:
255
+ click.echo("All configured services validated successfully!")
256
+
@@ -0,0 +1 @@
1
+ """Confluence REST API client and CLI commands."""