mpt-curl 1.0.8__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.
@@ -0,0 +1,32 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ publish:
10
+ runs-on: ubuntu-latest
11
+ permissions:
12
+ contents: read
13
+ id-token: write
14
+ steps:
15
+ - name: Checkout
16
+ uses: actions/checkout@v4
17
+ with:
18
+ fetch-depth: 0
19
+
20
+ - name: Install uv
21
+ uses: astral-sh/setup-uv@v5
22
+ with:
23
+ cache: true
24
+
25
+ - name: Run tests
26
+ run: uv run pytest
27
+
28
+ - name: Build distributions
29
+ run: uv build
30
+
31
+ - name: Publish to PyPI
32
+ run: uv publish --trusted-publishing=always
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ dist/
8
+ *.egg-info/
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.5
2
+ Name: mpt-curl
3
+ Version: 1.0.8
4
+ Summary: curl-like CLI for the MPT API with automatic collection paging
5
+ Requires-Python: <4,>=3.12
6
+ Requires-Dist: mpt-api-client>=6.3.1
7
+ Requires-Dist: mpt-cli>=5.3.0
8
+ Requires-Dist: pygments>=2.19
9
+ Description-Content-Type: text/markdown
10
+
11
+ # mpt-curl
12
+
13
+ Python replacement for `~/bin/mpt-curl` built on [mpt-api-python-client](https://github.com/softwareone-platform/mpt-api-python-client).
14
+
15
+ For GET requests to collection endpoints, pages are fetched automatically and streamed to stdout as a single JSON object (`{"data":[...], "$meta":{...}}`).
16
+
17
+ The first request is sent as-is. Auto-paging starts only if the response has `$meta.pagination`; further pages use `limit=1000` by default. With `total` in pagination, paging follows it; otherwise it continues while each page is full. Disabled when the URL contains `limit=` or `offset=`.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install mpt-curl
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ Uses the active account from `mpt-cli` accounts (`~/.swocli/accounts.json`, `is_active: true`), same as the shell wrapper.
28
+
29
+ Override with environment variables:
30
+
31
+ - `MPT_API_BASE_URL`
32
+ - `MPT_API_TOKEN`
33
+
34
+ ## Usage
35
+
36
+ ```bash
37
+ # List agreements (auto-paged)
38
+ mpt-curl /commerce/agreements
39
+
40
+ # Same with /public/v1 or /v1 prefix — resolved like the shell script
41
+ mpt-curl /public/v1/commerce/agreements
42
+ mpt-curl /v1/commerce/agreements
43
+ mpt-curl /commerce/agreements
44
+
45
+ # Filter with RQL
46
+ mpt-curl '/commerce/agreements?and(eq(status,Active))'
47
+
48
+ # Single page (limit= or offset= in URL disables auto-paging)
49
+ mpt-curl '/commerce/agreements?limit=10'
50
+
51
+ # POST (-d alone implies POST, like curl)
52
+ mpt-curl /commerce/orders -d '{"type":"Change","agreement":{"id":"AGR-123"}}'
53
+ mpt-curl -X POST /commerce/orders -d '{"type":"Change","agreement":{"id":"AGR-123"}}'
54
+
55
+ # PUT with body
56
+ mpt-curl -X PUT /commerce/orders/ORD-123 -d '{"status":"Processing"}'
57
+ ```
58
+
59
+ ## Options
60
+
61
+ | Flag | Description |
62
+ |------|-------------|
63
+ | `-X METHOD` | HTTP method (default: GET, or POST when `-d` is given) |
64
+ | `-d DATA` | Request body (JSON) |
65
+ | `-H NAME:VALUE` | Extra header |
66
+ | `--no-page` | Disable automatic paging |
67
+ | `--page-size N` | Page size for auto-paging (default: 1000) |
68
+ | `--compact` | Compact JSON output |
69
+ | `-v` | Log requests, status, and paging to stderr (gray when stderr is a TTY) |
70
+ | `-vv` | Also include response headers |
71
+
72
+ Automatic paging is also disabled when the URL already contains `limit=` or `offset=`.
73
+
74
+ ## Development
75
+
76
+ From a checkout:
77
+
78
+ ```bash
79
+ uv sync --group dev
80
+ uv run pytest
81
+ ```
82
+
@@ -0,0 +1,72 @@
1
+ # mpt-curl
2
+
3
+ Python replacement for `~/bin/mpt-curl` built on [mpt-api-python-client](https://github.com/softwareone-platform/mpt-api-python-client).
4
+
5
+ For GET requests to collection endpoints, pages are fetched automatically and streamed to stdout as a single JSON object (`{"data":[...], "$meta":{...}}`).
6
+
7
+ The first request is sent as-is. Auto-paging starts only if the response has `$meta.pagination`; further pages use `limit=1000` by default. With `total` in pagination, paging follows it; otherwise it continues while each page is full. Disabled when the URL contains `limit=` or `offset=`.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install mpt-curl
13
+ ```
14
+
15
+ ## Configuration
16
+
17
+ Uses the active account from `mpt-cli` accounts (`~/.swocli/accounts.json`, `is_active: true`), same as the shell wrapper.
18
+
19
+ Override with environment variables:
20
+
21
+ - `MPT_API_BASE_URL`
22
+ - `MPT_API_TOKEN`
23
+
24
+ ## Usage
25
+
26
+ ```bash
27
+ # List agreements (auto-paged)
28
+ mpt-curl /commerce/agreements
29
+
30
+ # Same with /public/v1 or /v1 prefix — resolved like the shell script
31
+ mpt-curl /public/v1/commerce/agreements
32
+ mpt-curl /v1/commerce/agreements
33
+ mpt-curl /commerce/agreements
34
+
35
+ # Filter with RQL
36
+ mpt-curl '/commerce/agreements?and(eq(status,Active))'
37
+
38
+ # Single page (limit= or offset= in URL disables auto-paging)
39
+ mpt-curl '/commerce/agreements?limit=10'
40
+
41
+ # POST (-d alone implies POST, like curl)
42
+ mpt-curl /commerce/orders -d '{"type":"Change","agreement":{"id":"AGR-123"}}'
43
+ mpt-curl -X POST /commerce/orders -d '{"type":"Change","agreement":{"id":"AGR-123"}}'
44
+
45
+ # PUT with body
46
+ mpt-curl -X PUT /commerce/orders/ORD-123 -d '{"status":"Processing"}'
47
+ ```
48
+
49
+ ## Options
50
+
51
+ | Flag | Description |
52
+ |------|-------------|
53
+ | `-X METHOD` | HTTP method (default: GET, or POST when `-d` is given) |
54
+ | `-d DATA` | Request body (JSON) |
55
+ | `-H NAME:VALUE` | Extra header |
56
+ | `--no-page` | Disable automatic paging |
57
+ | `--page-size N` | Page size for auto-paging (default: 1000) |
58
+ | `--compact` | Compact JSON output |
59
+ | `-v` | Log requests, status, and paging to stderr (gray when stderr is a TTY) |
60
+ | `-vv` | Also include response headers |
61
+
62
+ Automatic paging is also disabled when the URL already contains `limit=` or `offset=`.
63
+
64
+ ## Development
65
+
66
+ From a checkout:
67
+
68
+ ```bash
69
+ uv sync --group dev
70
+ uv run pytest
71
+ ```
72
+
@@ -0,0 +1,3 @@
1
+ from mpt_curl.cli import main
2
+
3
+ __all__ = ["main"]
@@ -0,0 +1,248 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ import signal
5
+ import sys
6
+ from typing import Any, IO
7
+
8
+ from mpt_api_client import MPTClient
9
+ from mpt_api_client.auth import BearerTokenAuthentication
10
+ from mpt_api_client.exceptions import MPTError
11
+
12
+ from mpt_curl.config import resolve_credentials
13
+ from mpt_curl.errors import write_error
14
+ from mpt_curl.output import render_json
15
+ from mpt_curl.paging import DEFAULT_PAGE_SIZE, should_auto_page, stream_all_pages
16
+ from mpt_curl.urls import (
17
+ build_url,
18
+ has_explicit_pagination,
19
+ query_limit,
20
+ resolve_absolute_url,
21
+ to_request_target,
22
+ )
23
+ from mpt_curl.verbose import VerboseLogger
24
+
25
+
26
+ def _ignore_sigpipe() -> None:
27
+ if hasattr(signal, "SIGPIPE"):
28
+ signal.signal(signal.SIGPIPE, signal.SIG_IGN)
29
+
30
+
31
+ def _silence_broken_pipe(stream: IO[Any]) -> None:
32
+ # Redirecting the fd to devnull (instead of closing the stream) keeps any
33
+ # later flush attempts, including the implicit one at interpreter
34
+ # shutdown, from raising BrokenPipeError again.
35
+ try:
36
+ devnull = os.open(os.devnull, os.O_WRONLY)
37
+ try:
38
+ os.dup2(devnull, stream.fileno())
39
+ finally:
40
+ os.close(devnull)
41
+ except OSError:
42
+ pass
43
+
44
+
45
+ def _safe_write(stream: IO[str], data: str) -> None:
46
+ try:
47
+ stream.write(data)
48
+ except BrokenPipeError:
49
+ _silence_broken_pipe(stream)
50
+ raise SystemExit(0) from None
51
+
52
+
53
+ def _safe_write_bytes(stream: IO[bytes], data: bytes) -> None:
54
+ try:
55
+ stream.write(data)
56
+ stream.flush()
57
+ except BrokenPipeError:
58
+ _silence_broken_pipe(stream)
59
+ raise SystemExit(0) from None
60
+
61
+
62
+ def _parse_header(value: str) -> tuple[str, str]:
63
+ if ":" not in value:
64
+ raise argparse.ArgumentTypeError(f"Header must be NAME:VALUE, got: {value}")
65
+ name, header_value = value.split(":", 1)
66
+ return name.strip(), header_value.strip()
67
+
68
+
69
+ def _parse_data(value: str) -> Any:
70
+ try:
71
+ return json.loads(value)
72
+ except json.JSONDecodeError:
73
+ return value
74
+
75
+
76
+ def _build_parser() -> argparse.ArgumentParser:
77
+ parser = argparse.ArgumentParser(
78
+ prog="mpt-curl",
79
+ description="curl-like CLI for the MPT API with automatic collection paging",
80
+ )
81
+ parser.add_argument("url", help="API path (/commerce/agreements) or absolute URL")
82
+ parser.add_argument(
83
+ "-X",
84
+ "--request",
85
+ default=None,
86
+ help="HTTP method (default: GET, or POST when -d is given)",
87
+ )
88
+ parser.add_argument(
89
+ "-d",
90
+ "--data",
91
+ action="append",
92
+ default=[],
93
+ type=_parse_data,
94
+ help="Request body (JSON)",
95
+ )
96
+ parser.add_argument(
97
+ "-H",
98
+ "--header",
99
+ action="append",
100
+ default=[],
101
+ type=_parse_header,
102
+ help="Extra request header NAME:VALUE",
103
+ )
104
+ parser.add_argument(
105
+ "--no-page",
106
+ action="store_true",
107
+ help="Disable automatic paging for collection responses",
108
+ )
109
+ parser.add_argument(
110
+ "--page-size",
111
+ type=int,
112
+ default=None,
113
+ help="Page size when auto-paging (default: 1000)",
114
+ )
115
+ parser.add_argument(
116
+ "--config",
117
+ default="~/.swocli/accounts.json",
118
+ help="swocli accounts file (default: ~/.swocli/accounts.json)",
119
+ )
120
+ parser.add_argument(
121
+ "--compact",
122
+ action="store_true",
123
+ help="Print JSON without indentation",
124
+ )
125
+ parser.add_argument(
126
+ "-v",
127
+ "--verbose",
128
+ action="count",
129
+ default=0,
130
+ help="Log requests, status, and paging to stderr (-vv includes response headers)",
131
+ )
132
+ return parser
133
+
134
+
135
+ def _merge_data(data_parts: list[Any]) -> Any | None:
136
+ if not data_parts:
137
+ return None
138
+ if len(data_parts) == 1:
139
+ return data_parts[0]
140
+ return data_parts
141
+
142
+
143
+ def _resolve_method_and_body(request: str | None, body: Any) -> tuple[str, Any | None]:
144
+ """Return (method, json_body). Like curl: -d alone implies POST."""
145
+ if request is not None:
146
+ return request.upper(), body
147
+ if body is not None:
148
+ return "POST", body
149
+ return "GET", None
150
+
151
+
152
+ def _print_response(response, compact: bool) -> None:
153
+ if not response.content:
154
+ return
155
+
156
+ try:
157
+ payload = response.json()
158
+ except json.JSONDecodeError:
159
+ _safe_write_bytes(sys.stdout.buffer, response.content)
160
+ return
161
+
162
+ text = render_json(payload, compact=compact)
163
+ _safe_write(sys.stdout, f"{text}\n")
164
+
165
+
166
+ def _safe_write_stdout(text: str) -> None:
167
+ _safe_write(sys.stdout, text)
168
+
169
+
170
+ def _safe_flush_stdout() -> None:
171
+ try:
172
+ sys.stdout.flush()
173
+ except BrokenPipeError:
174
+ _silence_broken_pipe(sys.stdout)
175
+ raise SystemExit(0) from None
176
+
177
+
178
+ def main(argv: list[str] | None = None) -> int:
179
+ _ignore_sigpipe()
180
+ parser = _build_parser()
181
+ args = parser.parse_args(argv)
182
+
183
+ try:
184
+ return _run(args)
185
+ except KeyboardInterrupt:
186
+ return 130
187
+
188
+
189
+ def _run(args: argparse.Namespace) -> int:
190
+ base_url, token = resolve_credentials(args.config)
191
+ environment = base_url
192
+ absolute_url = resolve_absolute_url(environment, args.url)
193
+ path, query_string = to_request_target(absolute_url)
194
+
195
+ headers = dict(args.header)
196
+ body = _merge_data(args.data)
197
+ method, body = _resolve_method_and_body(args.request, body)
198
+ log = VerboseLogger(args.verbose)
199
+
200
+ auto_page = not args.no_page and not has_explicit_pagination(query_string)
201
+ page_size = args.page_size or query_limit(query_string)
202
+
203
+ client = MPTClient.from_config(
204
+ authentication=BearerTokenAuthentication(token),
205
+ base_url=base_url,
206
+ )
207
+
208
+ def request_fn(page_query: str) -> Any:
209
+ url = build_url(path, page_query)
210
+ return client.http_client.request(
211
+ method,
212
+ url,
213
+ json=body,
214
+ headers=headers or None,
215
+ )
216
+
217
+ effective_page_size = page_size or DEFAULT_PAGE_SIZE
218
+
219
+ log.request(method, path, query_string)
220
+ try:
221
+ response = request_fn(query_string)
222
+ except MPTError as exc:
223
+ write_error(exc, verbose=args.verbose, log=log)
224
+ return 1
225
+ log.response(response)
226
+
227
+ payload = response.json()
228
+
229
+ if should_auto_page(method, auto_page, payload, page_size=effective_page_size):
230
+ stream_all_pages(
231
+ request_fn,
232
+ response,
233
+ query_string,
234
+ effective_page_size,
235
+ _safe_write_stdout,
236
+ compact=args.compact,
237
+ method=method,
238
+ path=path,
239
+ log=log if args.verbose >= 1 else None,
240
+ flush=_safe_flush_stdout,
241
+ )
242
+ else:
243
+ _print_response(response, args.compact)
244
+ return 0 if response.status_code < 400 else 1
245
+
246
+
247
+ if __name__ == "__main__":
248
+ raise SystemExit(main())
@@ -0,0 +1,29 @@
1
+ import json
2
+ import os
3
+
4
+ DEFAULT_CONFIG_FILE = "~/.swocli/accounts.json"
5
+
6
+
7
+ def load_active_account(config_file: str = DEFAULT_CONFIG_FILE) -> dict:
8
+ path = os.path.expanduser(config_file)
9
+ with open(path, encoding="utf-8") as handle:
10
+ accounts = json.load(handle)
11
+
12
+ active = [account for account in accounts if account.get("is_active")]
13
+ if not active:
14
+ raise SystemExit(f"No account with is_active=true found in {path}")
15
+ if len(active) > 1:
16
+ ids = ", ".join(account.get("id", "?") for account in active)
17
+ raise SystemExit(f"Multiple active accounts found in {path}: {ids}")
18
+ return active[0]
19
+
20
+
21
+ def resolve_credentials(config_file: str) -> tuple[str, str]:
22
+ base_url = os.environ.get("MPT_API_BASE_URL")
23
+ token = os.environ.get("MPT_API_TOKEN")
24
+
25
+ if base_url and token:
26
+ return base_url, token
27
+
28
+ account = load_active_account(config_file)
29
+ return base_url or account["environment"], token or account["token"]
@@ -0,0 +1,69 @@
1
+ import json
2
+ import sys
3
+ from typing import Any
4
+
5
+ from mpt_api_client.exceptions import MPTAPIError, MPTError, MPTHttpError
6
+
7
+ from mpt_curl.output import format_json, render_json
8
+ from mpt_curl.verbose import VerboseLogger, use_stderr_color
9
+
10
+ RED_BOLD = "\033[1;31m"
11
+ RESET = "\033[0m"
12
+
13
+
14
+ def error_payload(exc: MPTError) -> Any | None:
15
+ if isinstance(exc, MPTAPIError):
16
+ return exc.payload
17
+ if isinstance(exc, MPTHttpError):
18
+ try:
19
+ return json.loads(exc.body)
20
+ except json.JSONDecodeError:
21
+ return exc.body
22
+ return None
23
+
24
+
25
+ def format_error_summary(exc: MPTError) -> str:
26
+ return str(exc)
27
+
28
+
29
+ def format_error_json(exc: MPTError) -> str | None:
30
+ payload = error_payload(exc)
31
+ if payload is None or isinstance(payload, str):
32
+ return None
33
+ return format_json(payload, compact=False)
34
+
35
+
36
+ def format_error(exc: MPTError, *, verbose: int) -> str:
37
+ if verbose >= 1:
38
+ json_text = format_error_json(exc)
39
+ if json_text is not None:
40
+ return json_text
41
+ payload = error_payload(exc)
42
+ if isinstance(payload, str):
43
+ return payload
44
+ return format_error_summary(exc)
45
+
46
+
47
+ def _style_summary(text: str) -> str:
48
+ if use_stderr_color():
49
+ return f"{RED_BOLD}{text}{RESET}"
50
+ return text
51
+
52
+
53
+ def error_response_headers(exc: MPTError) -> dict[str, str] | None:
54
+ cause = exc.__cause__
55
+ if cause is not None and hasattr(cause, "response"):
56
+ return dict(cause.response.headers)
57
+ return None
58
+
59
+
60
+ def write_error(exc: MPTError, *, verbose: int, log: VerboseLogger | None = None) -> None:
61
+ if verbose >= 1 and log is not None and isinstance(exc, MPTHttpError):
62
+ log.error_response(exc.status_code, error_response_headers(exc))
63
+
64
+ sys.stderr.write(f"{_style_summary(format_error_summary(exc))}\n")
65
+
66
+ if verbose >= 1:
67
+ payload = error_payload(exc)
68
+ if payload is not None and not isinstance(payload, str):
69
+ sys.stdout.write(f"{render_json(payload, compact=False)}\n")
@@ -0,0 +1,46 @@
1
+ import json
2
+ import os
3
+ import sys
4
+ from typing import Any
5
+
6
+ from pygments import highlight
7
+ from pygments.formatters import TerminalFormatter
8
+ from pygments.lexers import JsonLexer
9
+
10
+
11
+ def use_json_highlight() -> bool:
12
+ if os.environ.get("NO_COLOR"):
13
+ return False
14
+ if os.environ.get("FORCE_COLOR"):
15
+ return True
16
+ return sys.stdout.isatty()
17
+
18
+
19
+ def use_stderr_json_highlight() -> bool:
20
+ if os.environ.get("NO_COLOR"):
21
+ return False
22
+ if os.environ.get("FORCE_COLOR"):
23
+ return True
24
+ return sys.stderr.isatty()
25
+
26
+
27
+ def format_json(payload: Any, *, compact: bool) -> str:
28
+ if compact:
29
+ return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
30
+ return json.dumps(payload, indent=2, ensure_ascii=False)
31
+
32
+
33
+ def highlight_json_text(text: str) -> str:
34
+ if not use_json_highlight():
35
+ return text
36
+ return highlight(text, JsonLexer(), TerminalFormatter()).rstrip("\n")
37
+
38
+
39
+ def highlight_stderr_json_text(text: str) -> str:
40
+ if not use_stderr_json_highlight():
41
+ return text
42
+ return highlight(text, JsonLexer(), TerminalFormatter()).rstrip("\n")
43
+
44
+
45
+ def render_json(payload: Any, *, compact: bool) -> str:
46
+ return highlight_json_text(format_json(payload, compact=compact))