expedait-cli 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,5 @@
1
+ """Expedait CLI — download project specs, post comments."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("expedait-cli")
expedait_cli/auth.py ADDED
@@ -0,0 +1,55 @@
1
+ """Token resolution: env var > config file > error."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ import click
8
+
9
+ from .config import load_config
10
+
11
+
12
+ def resolve_token(config_path=None) -> str:
13
+ """Return a bearer token or raise click.UsageError."""
14
+ # 1. Environment variable
15
+ token = os.environ.get("EXPEDAIT_TOKEN")
16
+ if token:
17
+ return token
18
+
19
+ # 2. Config file
20
+ cfg = load_config(config_path)
21
+ token = cfg.get("token")
22
+ if token:
23
+ return token
24
+
25
+ raise click.UsageError(
26
+ "Not authenticated. Run 'expedait auth login' or set EXPEDAIT_TOKEN."
27
+ )
28
+
29
+
30
+ def resolve_api_url(explicit: str | None = None, config_path=None) -> str:
31
+ """Return API URL from flag > env > config > default."""
32
+ if explicit:
33
+ return explicit.rstrip("/")
34
+ env = os.environ.get("EXPEDAIT_API_URL")
35
+ if env:
36
+ return env.rstrip("/")
37
+ cfg = load_config(config_path)
38
+ url = cfg.get("api_url")
39
+ if url:
40
+ return url.rstrip("/")
41
+ return "https://app.expedait.org"
42
+
43
+
44
+ def resolve_tenant_id(explicit: int | None = None, config_path=None) -> int | None:
45
+ """Return tenant ID from flag > env > config."""
46
+ if explicit is not None:
47
+ return explicit
48
+ env = os.environ.get("EXPEDAIT_TENANT_ID")
49
+ if env:
50
+ return int(env)
51
+ cfg = load_config(config_path)
52
+ tid = cfg.get("tenant_id")
53
+ if tid is not None:
54
+ return int(tid)
55
+ return None
expedait_cli/client.py ADDED
@@ -0,0 +1,130 @@
1
+ """HTTP client wrapper for Expedait API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import click
8
+ import httpx
9
+
10
+
11
+ class ExpedaitClient:
12
+ """Thin wrapper around httpx with auth and tenant headers."""
13
+
14
+ def __init__(self, api_url: str, token: str, tenant_id: int | None = None):
15
+ headers: dict[str, str] = {"Authorization": f"Bearer {token}"}
16
+ if tenant_id is not None:
17
+ headers["X-Active-Tenant-Id"] = str(tenant_id)
18
+ self._http = httpx.Client(base_url=api_url, headers=headers, timeout=30.0)
19
+
20
+ def close(self) -> None:
21
+ self._http.close()
22
+
23
+ # -- helpers ----------------------------------------------------------
24
+
25
+ def _request(self, method: str, path: str, **kwargs: Any) -> Any:
26
+ """Make request, handle errors, return parsed JSON."""
27
+ resp = self._http.request(method, path, **kwargs)
28
+ if resp.status_code == 401:
29
+ raise click.UsageError(
30
+ "Authentication failed (401). Run 'expedait auth login'."
31
+ )
32
+ if resp.status_code == 403:
33
+ raise click.UsageError(
34
+ "Permission denied (403). Check your tenant access."
35
+ )
36
+ if resp.status_code == 404:
37
+ raise click.UsageError("Resource not found (404).")
38
+ if resp.status_code >= 400:
39
+ detail = ""
40
+ try:
41
+ detail = resp.json().get("detail", resp.text)
42
+ except Exception:
43
+ detail = resp.text
44
+ raise click.ClickException(f"API error {resp.status_code}: {detail}")
45
+ return resp.json()
46
+
47
+ def _request_raw(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
48
+ """Make request, handle errors, return raw response."""
49
+ resp = self._http.request(method, path, **kwargs)
50
+ if resp.status_code == 401:
51
+ raise click.UsageError(
52
+ "Authentication failed (401). Run 'expedait auth login'."
53
+ )
54
+ if resp.status_code == 403:
55
+ raise click.UsageError(
56
+ "Permission denied (403). Check your tenant access."
57
+ )
58
+ if resp.status_code == 404:
59
+ raise click.UsageError("Resource not found (404).")
60
+ if resp.status_code >= 400:
61
+ detail = ""
62
+ try:
63
+ detail = resp.json().get("detail", resp.text)
64
+ except Exception:
65
+ detail = resp.text
66
+ raise click.ClickException(f"API error {resp.status_code}: {detail}")
67
+ return resp
68
+
69
+ # -- auth -------------------------------------------------------------
70
+
71
+ @staticmethod
72
+ def login(api_url: str, email: str, password: str) -> dict[str, Any]:
73
+ """POST /api/v1/auth/login — returns token payload."""
74
+ resp = httpx.post(
75
+ f"{api_url}/api/v1/auth/login",
76
+ json={"email": email, "password": password},
77
+ timeout=15.0,
78
+ )
79
+ if resp.status_code == 401:
80
+ raise click.UsageError("Invalid email or password.")
81
+ if resp.status_code >= 400:
82
+ raise click.ClickException(f"Login failed ({resp.status_code}).")
83
+ return resp.json()
84
+
85
+ def get_me(self) -> dict[str, Any]:
86
+ return self._request("GET", "/api/v1/auth/me")
87
+
88
+ # -- projects ---------------------------------------------------------
89
+
90
+ def list_projects(self) -> list[dict[str, Any]]:
91
+ return self._request("GET", "/api/v1/projects")
92
+
93
+ def get_project(self, project_id: int) -> dict[str, Any]:
94
+ return self._request("GET", f"/api/v1/projects/{project_id}")
95
+
96
+ def get_workspace(self, project_id: int) -> dict[str, Any]:
97
+ return self._request("GET", f"/api/v1/projects/{project_id}/workspace")
98
+
99
+ def download_project(self, project_id: int) -> bytes:
100
+ resp = self._request_raw("GET", f"/api/v1/projects/{project_id}/download")
101
+ return resp.content
102
+
103
+ # -- pages ------------------------------------------------------------
104
+
105
+ def list_pages(self, project_id: int) -> list[dict[str, Any]]:
106
+ return self._request("GET", "/api/v1/pages", params={"project_id": project_id})
107
+
108
+ def get_page(self, page_id: int) -> dict[str, Any]:
109
+ return self._request("GET", f"/api/v1/pages/{page_id}")
110
+
111
+ def get_page_full(self, page_id: int) -> dict[str, Any]:
112
+ return self._request("GET", f"/api/v1/pages/{page_id}/full")
113
+
114
+ def download_page(self, page_id: int) -> bytes:
115
+ resp = self._request_raw("GET", f"/api/v1/pages/{page_id}/download")
116
+ return resp.content
117
+
118
+ # -- comments ---------------------------------------------------------
119
+
120
+ def list_comments(self, page_id: int) -> list[dict[str, Any]]:
121
+ return self._request("GET", f"/api/v1/pages/{page_id}/comments")
122
+
123
+ def create_comment(self, page_id: int, data: dict[str, Any]) -> dict[str, Any]:
124
+ return self._request("POST", f"/api/v1/pages/{page_id}/comments", json=data)
125
+
126
+ def resolve_comment(self, comment_id: int) -> dict[str, Any]:
127
+ return self._request("PUT", f"/api/v1/pages/comments/{comment_id}/resolve")
128
+
129
+ def delete_comment(self, comment_id: int) -> dict[str, Any]:
130
+ return self._request("DELETE", f"/api/v1/pages/comments/{comment_id}")
File without changes
@@ -0,0 +1,175 @@
1
+ """Auth commands: login, status, logout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ import webbrowser
7
+
8
+ import click
9
+ import httpx
10
+
11
+ from ..auth import resolve_api_url, resolve_token
12
+ from ..client import ExpedaitClient
13
+ from ..config import clear_config, load_config, save_config
14
+ from ..formatters import output
15
+
16
+
17
+ @click.group()
18
+ def auth() -> None:
19
+ """Authenticate with the Expedait API."""
20
+
21
+
22
+ def _select_tenant(ctx: click.Context, memberships: list[dict]) -> int | None:
23
+ """Prompt user to pick a tenant when multiple are available."""
24
+ tenant_id = ctx.obj.get("tenant_id")
25
+ if tenant_id:
26
+ return tenant_id
27
+ if len(memberships) == 1:
28
+ return memberships[0]["tenant_id"]
29
+ if len(memberships) > 1:
30
+ click.echo("Available tenants:")
31
+ for m in memberships:
32
+ click.echo(f" [{m['tenant_id']}] {m.get('tenant_name', 'Unknown')} ({m['role']})")
33
+ return click.prompt("Select tenant ID", type=int)
34
+ return None
35
+
36
+
37
+ def _login_password(api_url: str) -> tuple[str, dict]:
38
+ """Interactive email/password login. Returns (token, user_info)."""
39
+ email = click.prompt("Email")
40
+ password = click.prompt("Password", hide_input=True)
41
+
42
+ try:
43
+ token_data = ExpedaitClient.login(api_url, email, password)
44
+ except httpx.RequestError as exc:
45
+ raise click.ClickException(f"Cannot reach {api_url}: {exc}")
46
+ token = token_data["access_token"]
47
+
48
+ client = ExpedaitClient(api_url, token)
49
+ try:
50
+ me = client.get_me()
51
+ finally:
52
+ client.close()
53
+ return token, me
54
+
55
+
56
+ def _login_sso(api_url: str) -> tuple[str, dict]:
57
+ """Browser-based SSO login via device-code-like flow. Returns (token, user_info)."""
58
+ # Initiate CLI auth session on the server
59
+ try:
60
+ resp = httpx.post(f"{api_url}/api/v1/auth/cli/initiate", timeout=15.0)
61
+ except httpx.RequestError as exc:
62
+ raise click.ClickException(f"Cannot reach {api_url}: {exc}")
63
+ if resp.status_code >= 400:
64
+ raise click.ClickException(f"Failed to initiate SSO login ({resp.status_code}).")
65
+ data = resp.json()
66
+ session_id = data["session_id"]
67
+ login_url = data["login_url"]
68
+
69
+ click.echo()
70
+ click.echo(f"Open this URL in your browser to sign in:\n")
71
+ click.echo(f" {login_url}")
72
+ click.echo()
73
+
74
+ # Try to open browser automatically
75
+ try:
76
+ webbrowser.open(login_url)
77
+ click.echo("(Browser opened automatically)")
78
+ except Exception:
79
+ click.echo("(Could not open browser — please open the URL manually)")
80
+
81
+ click.echo()
82
+ click.echo("Waiting for authentication...", nl=False)
83
+
84
+ poll_url = f"{api_url}/api/v1/auth/cli/poll/{session_id}"
85
+ poll_interval = 2 # seconds
86
+ max_wait = 300 # 5 minutes
87
+ elapsed = 0
88
+
89
+ while elapsed < max_wait:
90
+ time.sleep(poll_interval)
91
+ elapsed += poll_interval
92
+ click.echo(".", nl=False)
93
+
94
+ try:
95
+ poll_resp = httpx.get(poll_url, timeout=10.0)
96
+ except httpx.RequestError:
97
+ continue
98
+
99
+ if poll_resp.status_code == 404:
100
+ click.echo()
101
+ raise click.ClickException("Login session expired. Please try again.")
102
+
103
+ if poll_resp.status_code >= 400:
104
+ continue
105
+
106
+ result = poll_resp.json()
107
+ if result["status"] == "completed":
108
+ click.echo(" done!")
109
+ return result["access_token"], result["user"]
110
+
111
+ click.echo()
112
+ raise click.ClickException("Login timed out after 5 minutes. Please try again.")
113
+
114
+
115
+ @auth.command()
116
+ @click.pass_context
117
+ def login(ctx: click.Context) -> None:
118
+ """Login interactively via browser SSO or email/password."""
119
+ api_url = resolve_api_url(ctx.obj.get("api_url"))
120
+ api_url = click.prompt("API URL", default=api_url)
121
+
122
+ method = click.prompt(
123
+ "Login method",
124
+ type=click.Choice(["sso", "password"], case_sensitive=False),
125
+ default="sso",
126
+ )
127
+
128
+ if method == "sso":
129
+ token, me = _login_sso(api_url)
130
+ else:
131
+ token, me = _login_password(api_url)
132
+
133
+ memberships = me.get("tenant_memberships", [])
134
+ tenant_id = _select_tenant(ctx, memberships)
135
+
136
+ save_config({"api_url": api_url, "token": token, "tenant_id": tenant_id})
137
+ click.echo(f"Logged in as {me['email']} (tenant {tenant_id}).")
138
+
139
+
140
+ @auth.command()
141
+ @click.pass_context
142
+ def status(ctx: click.Context) -> None:
143
+ """Show current authentication status."""
144
+ fmt = ctx.obj.get("fmt")
145
+ try:
146
+ token = resolve_token()
147
+ except click.UsageError:
148
+ click.echo("Not authenticated.")
149
+ return
150
+
151
+ api_url = resolve_api_url(ctx.obj.get("api_url"))
152
+ client = ExpedaitClient(api_url, token, ctx.obj.get("tenant_id"))
153
+ try:
154
+ me = client.get_me()
155
+ except click.UsageError as exc:
156
+ click.echo(f"Token invalid: {exc}")
157
+ return
158
+ finally:
159
+ client.close()
160
+
161
+ cfg = load_config()
162
+ info = {
163
+ "email": me["email"],
164
+ "user_id": me["id"],
165
+ "tenant_id": cfg.get("tenant_id"),
166
+ "api_url": cfg.get("api_url"),
167
+ }
168
+ output(info, fmt)
169
+
170
+
171
+ @auth.command()
172
+ def logout() -> None:
173
+ """Clear stored credentials."""
174
+ clear_config()
175
+ click.echo("Logged out.")
@@ -0,0 +1,102 @@
1
+ """Comment commands: list, create, resolve, delete."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from ..auth import resolve_api_url, resolve_tenant_id, resolve_token
8
+ from ..client import ExpedaitClient
9
+ from ..formatters import output
10
+
11
+
12
+ def _make_client(ctx: click.Context) -> ExpedaitClient:
13
+ token = resolve_token()
14
+ api_url = resolve_api_url(ctx.obj.get("api_url"))
15
+ tenant_id = resolve_tenant_id(ctx.obj.get("tenant_id"))
16
+ return ExpedaitClient(api_url, token, tenant_id)
17
+
18
+
19
+ @click.group()
20
+ def comments() -> None:
21
+ """Manage page comments."""
22
+
23
+
24
+ @comments.command("list")
25
+ @click.argument("page_id", type=int)
26
+ @click.pass_context
27
+ def list_comments(ctx: click.Context, page_id: int) -> None:
28
+ """List comments on a page."""
29
+ client = _make_client(ctx)
30
+ try:
31
+ data = client.list_comments(page_id)
32
+ finally:
33
+ client.close()
34
+ output(data, ctx.obj.get("fmt"))
35
+
36
+
37
+ @comments.command("create")
38
+ @click.argument("page_id", type=int)
39
+ @click.option("--text", required=True, help="Comment content.")
40
+ @click.option("--selected-text", required=True, help="The text being commented on.")
41
+ @click.option("--start-offset", required=True, type=int, help="Start character offset.")
42
+ @click.option("--end-offset", required=True, type=int, help="End character offset.")
43
+ @click.option("--source-page-id", type=int, default=None, help="Agent's source page ID.")
44
+ @click.option("--parent-comment-id", type=int, default=None, help="Reply to comment ID.")
45
+ @click.pass_context
46
+ def create_comment(
47
+ ctx: click.Context,
48
+ page_id: int,
49
+ text: str,
50
+ selected_text: str,
51
+ start_offset: int,
52
+ end_offset: int,
53
+ source_page_id: int | None,
54
+ parent_comment_id: int | None,
55
+ ) -> None:
56
+ """Create a comment on a page."""
57
+ payload: dict = {
58
+ "comment_text": text,
59
+ "selected_text": selected_text,
60
+ "start_offset": start_offset,
61
+ "end_offset": end_offset,
62
+ "is_agent_comment": True,
63
+ }
64
+ if source_page_id is not None:
65
+ payload["source_page_id"] = source_page_id
66
+ if parent_comment_id is not None:
67
+ payload["parent_comment_id"] = parent_comment_id
68
+
69
+ client = _make_client(ctx)
70
+ try:
71
+ data = client.create_comment(page_id, payload)
72
+ finally:
73
+ client.close()
74
+ output(data, ctx.obj.get("fmt"))
75
+
76
+
77
+ @comments.command("resolve")
78
+ @click.argument("page_id", type=int)
79
+ @click.argument("comment_id", type=int)
80
+ @click.pass_context
81
+ def resolve_comment(ctx: click.Context, page_id: int, comment_id: int) -> None:
82
+ """Mark a comment as resolved."""
83
+ client = _make_client(ctx)
84
+ try:
85
+ data = client.resolve_comment(comment_id)
86
+ finally:
87
+ client.close()
88
+ output(data, ctx.obj.get("fmt"))
89
+
90
+
91
+ @comments.command("delete")
92
+ @click.argument("page_id", type=int)
93
+ @click.argument("comment_id", type=int)
94
+ @click.pass_context
95
+ def delete_comment(ctx: click.Context, page_id: int, comment_id: int) -> None:
96
+ """Delete a comment."""
97
+ client = _make_client(ctx)
98
+ try:
99
+ data = client.delete_comment(comment_id)
100
+ finally:
101
+ client.close()
102
+ click.echo("Comment deleted.")
@@ -0,0 +1,104 @@
1
+ """Page commands: list, get, full, download."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import zipfile
7
+ from pathlib import Path
8
+
9
+ import click
10
+
11
+ from ..auth import resolve_api_url, resolve_tenant_id, resolve_token
12
+ from ..client import ExpedaitClient
13
+ from ..formatters import output
14
+
15
+
16
+ def _make_client(ctx: click.Context) -> ExpedaitClient:
17
+ token = resolve_token()
18
+ api_url = resolve_api_url(ctx.obj.get("api_url"))
19
+ tenant_id = resolve_tenant_id(ctx.obj.get("tenant_id"))
20
+ return ExpedaitClient(api_url, token, tenant_id)
21
+
22
+
23
+ @click.group()
24
+ def pages() -> None:
25
+ """Manage pages."""
26
+
27
+
28
+ @pages.command("list")
29
+ @click.option("--project-id", required=True, type=int, help="Project ID to list pages for.")
30
+ @click.pass_context
31
+ def list_pages(ctx: click.Context, project_id: int) -> None:
32
+ """List pages in a project."""
33
+ client = _make_client(ctx)
34
+ try:
35
+ data = client.list_pages(project_id)
36
+ finally:
37
+ client.close()
38
+
39
+ fmt = ctx.obj.get("fmt")
40
+ if fmt == "json" or (fmt is None and not _is_tty()):
41
+ output(data, "json")
42
+ else:
43
+ rows = [
44
+ {"id": p["id"], "title": p["title"], "state": p.get("state", ""), "version": p.get("version", "")}
45
+ for p in data
46
+ ]
47
+ output(rows, "text")
48
+
49
+
50
+ @pages.command("get")
51
+ @click.argument("page_id", type=int)
52
+ @click.pass_context
53
+ def get_page(ctx: click.Context, page_id: int) -> None:
54
+ """Print page content (markdown)."""
55
+ client = _make_client(ctx)
56
+ try:
57
+ data = client.get_page(page_id)
58
+ finally:
59
+ client.close()
60
+
61
+ fmt = ctx.obj.get("fmt")
62
+ if fmt == "json":
63
+ output(data, "json")
64
+ else:
65
+ click.echo(data.get("content") or "(empty page)")
66
+
67
+
68
+ @pages.command("full")
69
+ @click.argument("page_id", type=int)
70
+ @click.pass_context
71
+ def full_page(ctx: click.Context, page_id: int) -> None:
72
+ """Get page with full context (comments, dependencies, lock status)."""
73
+ client = _make_client(ctx)
74
+ try:
75
+ data = client.get_page_full(page_id)
76
+ finally:
77
+ client.close()
78
+ output(data, ctx.obj.get("fmt"))
79
+
80
+
81
+ @pages.command("download")
82
+ @click.argument("page_id", type=int)
83
+ @click.option("--output-dir", type=click.Path(), default=".", help="Extract to directory.")
84
+ @click.pass_context
85
+ def download_page(ctx: click.Context, page_id: int, output_dir: str) -> None:
86
+ """Download page as ZIP and extract."""
87
+ client = _make_client(ctx)
88
+ try:
89
+ data = client.download_page(page_id)
90
+ finally:
91
+ client.close()
92
+
93
+ dest = Path(output_dir)
94
+ dest.mkdir(parents=True, exist_ok=True)
95
+
96
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
97
+ zf.extractall(dest)
98
+
99
+ click.echo(f"Extracted to {dest.resolve()}")
100
+
101
+
102
+ def _is_tty() -> bool:
103
+ import sys
104
+ return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
@@ -0,0 +1,85 @@
1
+ """Project commands: list, get, download."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import zipfile
7
+ from pathlib import Path
8
+
9
+ import click
10
+
11
+ from ..auth import resolve_api_url, resolve_tenant_id, resolve_token
12
+ from ..client import ExpedaitClient
13
+ from ..formatters import output
14
+
15
+
16
+ def _make_client(ctx: click.Context) -> ExpedaitClient:
17
+ token = resolve_token()
18
+ api_url = resolve_api_url(ctx.obj.get("api_url"))
19
+ tenant_id = resolve_tenant_id(ctx.obj.get("tenant_id"))
20
+ return ExpedaitClient(api_url, token, tenant_id)
21
+
22
+
23
+ @click.group()
24
+ def projects() -> None:
25
+ """Manage projects."""
26
+
27
+
28
+ @projects.command("list")
29
+ @click.pass_context
30
+ def list_projects(ctx: click.Context) -> None:
31
+ """List all projects in the tenant."""
32
+ client = _make_client(ctx)
33
+ try:
34
+ data = client.list_projects()
35
+ finally:
36
+ client.close()
37
+
38
+ fmt = ctx.obj.get("fmt")
39
+ if fmt == "json" or (fmt is None and not _is_tty()):
40
+ output(data, "json")
41
+ else:
42
+ rows = [
43
+ {"id": p["id"], "name": p["name"], "type": p.get("project_type_name", ""), "state": p.get("state", "")}
44
+ for p in data
45
+ ]
46
+ output(rows, "text")
47
+
48
+
49
+ @projects.command("get")
50
+ @click.argument("project_id", type=int)
51
+ @click.pass_context
52
+ def get_project(ctx: click.Context, project_id: int) -> None:
53
+ """Get project details."""
54
+ client = _make_client(ctx)
55
+ try:
56
+ data = client.get_project(project_id)
57
+ finally:
58
+ client.close()
59
+ output(data, ctx.obj.get("fmt"))
60
+
61
+
62
+ @projects.command("download")
63
+ @click.argument("project_id", type=int)
64
+ @click.option("--output-dir", type=click.Path(), default=".", help="Extract to directory.")
65
+ @click.pass_context
66
+ def download_project(ctx: click.Context, project_id: int, output_dir: str) -> None:
67
+ """Download all project pages as a ZIP and extract."""
68
+ client = _make_client(ctx)
69
+ try:
70
+ data = client.download_project(project_id)
71
+ finally:
72
+ client.close()
73
+
74
+ dest = Path(output_dir)
75
+ dest.mkdir(parents=True, exist_ok=True)
76
+
77
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
78
+ zf.extractall(dest)
79
+
80
+ click.echo(f"Extracted to {dest.resolve()}")
81
+
82
+
83
+ def _is_tty() -> bool:
84
+ import sys
85
+ return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
expedait_cli/config.py ADDED
@@ -0,0 +1,33 @@
1
+ """Configuration file management for ~/.expedait/config.json."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ CONFIG_DIR = Path.home() / ".expedait"
11
+ CONFIG_FILE = CONFIG_DIR / "config.json"
12
+
13
+
14
+ def load_config(path: Path | None = None) -> dict[str, Any]:
15
+ """Load config from disk. Returns empty dict if missing."""
16
+ p = path or CONFIG_FILE
17
+ if not p.exists():
18
+ return {}
19
+ return json.loads(p.read_text())
20
+
21
+
22
+ def save_config(data: dict[str, Any], path: Path | None = None) -> None:
23
+ """Write config to disk, creating directory if needed."""
24
+ p = path or CONFIG_FILE
25
+ p.parent.mkdir(parents=True, exist_ok=True)
26
+ p.write_text(json.dumps(data, indent=2) + "\n")
27
+
28
+
29
+ def clear_config(path: Path | None = None) -> None:
30
+ """Remove config file."""
31
+ p = path or CONFIG_FILE
32
+ if p.exists():
33
+ p.unlink()
@@ -0,0 +1,66 @@
1
+ """Output formatting: JSON vs human-readable text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from typing import Any
8
+
9
+
10
+ def is_tty() -> bool:
11
+ return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
12
+
13
+
14
+ def output(data: Any, fmt: str | None = None) -> None:
15
+ """Print data in the requested format."""
16
+ effective = fmt or ("text" if is_tty() else "json")
17
+ if effective == "json":
18
+ click_echo_json(data)
19
+ else:
20
+ click_echo_text(data)
21
+
22
+
23
+ def click_echo_json(data: Any) -> None:
24
+ import click
25
+ click.echo(json.dumps(data, indent=2, default=str))
26
+
27
+
28
+ def click_echo_text(data: Any) -> None:
29
+ import click
30
+ if isinstance(data, list):
31
+ _print_table(data)
32
+ elif isinstance(data, dict):
33
+ _print_dict(data)
34
+ else:
35
+ click.echo(str(data))
36
+
37
+
38
+ def _print_table(rows: list[dict[str, Any]]) -> None:
39
+ import click
40
+ if not rows:
41
+ click.echo("No results.")
42
+ return
43
+ keys = list(rows[0].keys())
44
+ # Compute column widths
45
+ widths = {k: len(k) for k in keys}
46
+ for row in rows:
47
+ for k in keys:
48
+ widths[k] = max(widths[k], len(str(row.get(k, ""))))
49
+ # Header
50
+ header = " ".join(k.ljust(widths[k]) for k in keys)
51
+ click.echo(header)
52
+ click.echo(" ".join("-" * widths[k] for k in keys))
53
+ # Rows
54
+ for row in rows:
55
+ line = " ".join(str(row.get(k, "")).ljust(widths[k]) for k in keys)
56
+ click.echo(line)
57
+
58
+
59
+ def _print_dict(d: dict[str, Any]) -> None:
60
+ import click
61
+ if not d:
62
+ click.echo("Empty.")
63
+ return
64
+ max_key = max(len(str(k)) for k in d)
65
+ for k, v in d.items():
66
+ click.echo(f"{str(k).ljust(max_key)} {v}")
expedait_cli/main.py ADDED
@@ -0,0 +1,31 @@
1
+ """Expedait CLI entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from . import __version__
8
+ from .commands.auth_cmd import auth
9
+ from .commands.projects import projects
10
+ from .commands.pages import pages
11
+ from .commands.comments import comments
12
+
13
+
14
+ @click.group()
15
+ @click.option("--api-url", envvar="EXPEDAIT_API_URL", default=None, help="API base URL.")
16
+ @click.option("--tenant-id", envvar="EXPEDAIT_TENANT_ID", type=int, default=None, help="Tenant ID.")
17
+ @click.option("--format", "fmt", type=click.Choice(["json", "text"]), default=None, help="Output format.")
18
+ @click.version_option(__version__)
19
+ @click.pass_context
20
+ def cli(ctx: click.Context, api_url: str | None, tenant_id: int | None, fmt: str | None) -> None:
21
+ """Expedait CLI — download project specs, post comments."""
22
+ ctx.ensure_object(dict)
23
+ ctx.obj["api_url"] = api_url
24
+ ctx.obj["tenant_id"] = tenant_id
25
+ ctx.obj["fmt"] = fmt
26
+
27
+
28
+ cli.add_command(auth)
29
+ cli.add_command(projects)
30
+ cli.add_command(pages)
31
+ cli.add_command(comments)
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: expedait-cli
3
+ Version: 0.2.0
4
+ Summary: CLI for Expedait project management — download specs, post comments
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: click>=8.1
8
+ Requires-Dist: httpx>=0.27
@@ -0,0 +1,16 @@
1
+ expedait_cli/__init__.py,sha256=Otm6QK4tMQENEK7UD8xYe0OSg2HsZlfKuBCgunLXd-Y,141
2
+ expedait_cli/auth.py,sha256=pEe3s8SpqseyTvzN3QqYfspCh4HoFNTaUKTAc6ooCI4,1427
3
+ expedait_cli/client.py,sha256=3NzK2KQLbFHW-411q7bSRApsd4m79aXlJQ-L1xlWNbc,5231
4
+ expedait_cli/config.py,sha256=Cr18C6cvrTGEUfGNqHZdtelZIkcQda21GzSHVcyIyzM,892
5
+ expedait_cli/formatters.py,sha256=kb-1MS-9pi7yZPIcMVTxwt4dQeIOu4SA_6DGc97obvk,1687
6
+ expedait_cli/main.py,sha256=pGNXXWoca7cNRQZVwEIMfRBk639f19209cupKOLYQqo,1015
7
+ expedait_cli/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ expedait_cli/commands/auth_cmd.py,sha256=NXHrPrC0KsN6hEoYoRtzRFsdWt-ukTuQJoZO88ZOVeU,5169
9
+ expedait_cli/commands/comments.py,sha256=FZ7Jqwe8BvxsjxmAK-bvSLrrJV9jJX4MvyckU4mZtC8,3116
10
+ expedait_cli/commands/pages.py,sha256=G2Hf-pOaJ-5RN1bvgFj5hkiZvfM0gdsqw-aNVXL-c2c,2820
11
+ expedait_cli/commands/projects.py,sha256=VQbqXlYLchdHv8eyyEg_yiNBRNq1bmN-5NveagwFGv0,2281
12
+ expedait_cli-0.2.0.dist-info/METADATA,sha256=Nrv2PTDu9681_YGdisrHFSTSDw9vHfIKEqw7_PV_8vA,234
13
+ expedait_cli-0.2.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
14
+ expedait_cli-0.2.0.dist-info/entry_points.txt,sha256=eEe1rlUrOErSqQQFHEq2ZvbntKFoYJeFFl3QyuzxcHY,51
15
+ expedait_cli-0.2.0.dist-info/licenses/LICENSE,sha256=WviGskM8xXl9ANQUWBbF9Vc_3EoKCel-UT-Qz8eXNyM,10759
16
+ expedait_cli-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ expedait = expedait_cli.main:cli
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Expedait
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.