minman 0.1.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.
minman-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sangam Singh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
minman-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: minman
3
+ Version: 0.1.0
4
+ Summary: MinMan - a tiny local API client.
5
+ Author-email: Sangam Singh <sangam.ai.work@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sangamsingh01/MinMan
8
+ Project-URL: Issues, https://github.com/sangamsingh01/MinMan/issues
9
+ Keywords: api,http,client,rest
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Framework :: Flask
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Software Development :: Testing
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: Flask>=3
18
+ Requires-Dist: requests>=2.31
19
+ Requires-Dist: truststore>=0.9
20
+ Provides-Extra: test
21
+ Requires-Dist: pytest>=8; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ # MinMan
25
+
26
+ A tiny API client that runs locally in your browser. Build and send HTTP requests, organise them in folders, and keep everything as plain JSON files on your own computer. No account, no cloud.
27
+
28
+ ## Install
29
+
30
+ ```
31
+ pip install minman
32
+ ```
33
+
34
+ Requires Python 3.10+.
35
+
36
+ ## Run
37
+
38
+ ```
39
+ minman
40
+ ```
41
+
42
+ If `minman` is not found (Python's Scripts folder is not on PATH), run:
43
+
44
+ ```
45
+ python -m minman
46
+ ```
47
+
48
+ Your browser opens http://127.0.0.1:3326. Stop it with `Ctrl+C`.
49
+
50
+ Options:
51
+ - `--port 5050`: use another port
52
+ - `--no-browser`: don't open the browser
53
+ - `--logs` / `--no-logs`: show or hide request logs in the terminal (off by default)
54
+ - `--data-dir <path>`: where your data is kept (default `~/.minman`, or set `MINMAN_HOME`)
55
+ - `--version`: show the version
56
+
57
+ Example:
58
+
59
+ ```
60
+ minman --port 5050 --no-browser
61
+ ```
62
+
63
+ ## Features
64
+
65
+ - **Requests**: GET, POST, PUT, PATCH, DELETE with Params, Headers, Auth and Body tabs. Untick a row to keep it but not send it. Params and Headers also have a Raw mode.
66
+ - **Collections**: nested folders in the sidebar. Hover an item to duplicate (⧉), rename (✎), move (⇄) or delete (×). Use the search box to filter.
67
+ - **Auth**: Token box (default), Bearer, Basic or API key (header or query).
68
+ - **Body**: None, JSON, Text, URL-encoded or Form-data with file upload.
69
+ - **Environments**: reusable `{{name}}` variables (e.g. `{{base_url}}`) in several environments such as Dev and Prod. Switch between them in the top bar.
70
+ - **Token box**: shows when a JWT expires; the eye button shows or hides it. The token is remembered in your browser's local storage (not in `~/.minman`); clear the box to forget it.
71
+ - **cURL**: **Import cURL** fills a request from a command; **Export cURL** gives a command to copy or download.
72
+ - **Responses**: status, time and size. **Pretty** shows JSON as a collapsible tree, **Raw** shows plain text, **Preview** renders HTML or images, and search highlights matches.
73
+ - **Saved versions**: **Save response** stores numbered versions (`_v1`, `_v2`, ...) that you can reopen later.
74
+ - **Shortcuts**: `Ctrl+Enter` sends, `Ctrl+S` saves, `Esc` cancels. A ● marks unsaved changes.
75
+ - Dark and light themes, resizable panes.
76
+ - **About** (ⓘ in the top bar): version, license and contact.
77
+
78
+
79
+ ## License
80
+
81
+ MIT. See [LICENSE](LICENSE).
minman-0.1.0/README.md ADDED
@@ -0,0 +1,58 @@
1
+ # MinMan
2
+
3
+ A tiny API client that runs locally in your browser. Build and send HTTP requests, organise them in folders, and keep everything as plain JSON files on your own computer. No account, no cloud.
4
+
5
+ ## Install
6
+
7
+ ```
8
+ pip install minman
9
+ ```
10
+
11
+ Requires Python 3.10+.
12
+
13
+ ## Run
14
+
15
+ ```
16
+ minman
17
+ ```
18
+
19
+ If `minman` is not found (Python's Scripts folder is not on PATH), run:
20
+
21
+ ```
22
+ python -m minman
23
+ ```
24
+
25
+ Your browser opens http://127.0.0.1:3326. Stop it with `Ctrl+C`.
26
+
27
+ Options:
28
+ - `--port 5050`: use another port
29
+ - `--no-browser`: don't open the browser
30
+ - `--logs` / `--no-logs`: show or hide request logs in the terminal (off by default)
31
+ - `--data-dir <path>`: where your data is kept (default `~/.minman`, or set `MINMAN_HOME`)
32
+ - `--version`: show the version
33
+
34
+ Example:
35
+
36
+ ```
37
+ minman --port 5050 --no-browser
38
+ ```
39
+
40
+ ## Features
41
+
42
+ - **Requests**: GET, POST, PUT, PATCH, DELETE with Params, Headers, Auth and Body tabs. Untick a row to keep it but not send it. Params and Headers also have a Raw mode.
43
+ - **Collections**: nested folders in the sidebar. Hover an item to duplicate (⧉), rename (✎), move (⇄) or delete (×). Use the search box to filter.
44
+ - **Auth**: Token box (default), Bearer, Basic or API key (header or query).
45
+ - **Body**: None, JSON, Text, URL-encoded or Form-data with file upload.
46
+ - **Environments**: reusable `{{name}}` variables (e.g. `{{base_url}}`) in several environments such as Dev and Prod. Switch between them in the top bar.
47
+ - **Token box**: shows when a JWT expires; the eye button shows or hides it. The token is remembered in your browser's local storage (not in `~/.minman`); clear the box to forget it.
48
+ - **cURL**: **Import cURL** fills a request from a command; **Export cURL** gives a command to copy or download.
49
+ - **Responses**: status, time and size. **Pretty** shows JSON as a collapsible tree, **Raw** shows plain text, **Preview** renders HTML or images, and search highlights matches.
50
+ - **Saved versions**: **Save response** stores numbered versions (`_v1`, `_v2`, ...) that you can reopen later.
51
+ - **Shortcuts**: `Ctrl+Enter` sends, `Ctrl+S` saves, `Esc` cancels. A ● marks unsaved changes.
52
+ - Dark and light themes, resizable panes.
53
+ - **About** (ⓘ in the top bar): version, license and contact.
54
+
55
+
56
+ ## License
57
+
58
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "minman"
7
+ dynamic = ["version"]
8
+ description = "MinMan - a tiny local API client."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Sangam Singh", email = "sangam.ai.work@gmail.com" }]
14
+ keywords = ["api", "http", "client", "rest"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Framework :: Flask",
18
+ "Operating System :: OS Independent",
19
+ "Topic :: Software Development :: Testing",
20
+ ]
21
+ dependencies = ["Flask>=3", "requests>=2.31", "truststore>=0.9"]
22
+
23
+ [project.optional-dependencies]
24
+ test = ["pytest>=8"]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/sangamsingh01/MinMan"
28
+ Issues = "https://github.com/sangamsingh01/MinMan/issues"
29
+
30
+ [project.scripts]
31
+ minman = "minman.cli:main"
32
+
33
+ [tool.setuptools.dynamic]
34
+ version = { attr = "minman.__version__" }
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.setuptools.package-data]
40
+ minman = ["static/index.html"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
minman-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from minman.cli import main
2
+
3
+ main()
@@ -0,0 +1,347 @@
1
+ import json
2
+ import shutil
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+
6
+ import requests
7
+ from flask import Flask, jsonify, request, send_from_directory
8
+
9
+ from minman import __version__, storage
10
+ from minman.curl import parse_curl
11
+ from minman.http_client import RequestError, send
12
+ from minman.storage import (
13
+ NAME_PATTERN, clean_variables, collection_path, copy_name, load_variables,
14
+ read_environments, read_json, request_path, response_versions, safe_name, write_json,
15
+ )
16
+
17
+ __author__ = "Sangam Singh"
18
+
19
+
20
+ PACKAGE_DIR = Path(__file__).resolve().parent
21
+
22
+ app = Flask(__name__)
23
+ # Room for file uploads, which arrive base64-encoded inside the JSON body.
24
+ app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024
25
+
26
+
27
+ def error(message, status=400):
28
+ return jsonify(error=str(message)), status
29
+
30
+
31
+ @app.before_request
32
+ def local_only():
33
+ # Blocks DNS-rebinding: other sites must not reach this API through a hostname pointing at 127.0.0.1.
34
+ if request.host.rsplit(":", 1)[0] not in ("127.0.0.1", "localhost"):
35
+ return error("Forbidden host.", 403)
36
+ # Blocks other websites open in the browser from calling this API (CSRF).
37
+ origin = request.headers.get("Origin")
38
+ if origin is not None and origin != f"{request.scheme}://{request.host}":
39
+ return error("Forbidden origin.", 403)
40
+
41
+
42
+ @app.errorhandler(413)
43
+ def too_large(_):
44
+ return error("Request is too large (limit 50 MB).", 413)
45
+
46
+
47
+ @app.get("/")
48
+ def home():
49
+ return send_from_directory(PACKAGE_DIR / "static", "index.html")
50
+
51
+
52
+ @app.get("/api/about")
53
+ def about():
54
+ return jsonify(version=__version__)
55
+
56
+
57
+ @app.get("/api/tree")
58
+ def get_tree():
59
+ tree = {}
60
+ for folder in sorted(storage.COLLECTIONS.rglob("*"), key=lambda item: item.as_posix().lower()):
61
+ if folder.is_dir():
62
+ folder_name = folder.relative_to(storage.COLLECTIONS).as_posix()
63
+ requests_in_folder = []
64
+ for path in sorted(folder.glob("*.json"), key=lambda item: item.stem.lower()):
65
+ method = "REQ"
66
+ try:
67
+ method = read_json(path).get("method", method)
68
+ except (OSError, ValueError, AttributeError):
69
+ pass
70
+ requests_in_folder.append({"name": path.stem, "method": method})
71
+ tree[folder_name] = requests_in_folder
72
+ return jsonify(tree)
73
+
74
+
75
+ @app.post("/api/folders")
76
+ def create_folder():
77
+ data = request.get_json(silent=True) or {}
78
+ try:
79
+ name = safe_name(data.get("name"))
80
+ parent = data.get("parent", "")
81
+ parent_path = storage.COLLECTIONS if not parent else collection_path(parent)
82
+ except ValueError as exc:
83
+ return error(exc)
84
+ if not parent_path.is_dir():
85
+ return error("Parent folder not found.", 404)
86
+ path = parent_path / name
87
+ if path.exists():
88
+ return error("That folder already exists.", 400)
89
+ path.mkdir()
90
+ return jsonify(name=name), 201
91
+
92
+
93
+ @app.delete("/api/folders/<path:folder>")
94
+ def delete_folder(folder):
95
+ try:
96
+ path = collection_path(folder)
97
+ except ValueError as exc:
98
+ return error(exc)
99
+ if not path.is_dir():
100
+ return error("Folder not found.", 404)
101
+ shutil.rmtree(path)
102
+ shutil.rmtree(collection_path(folder, storage.RESPONSES), ignore_errors=True)
103
+ return jsonify(ok=True)
104
+
105
+
106
+ @app.get("/api/requests/<path:item>")
107
+ def get_request(item):
108
+ try:
109
+ folder, name = item.rsplit("/", 1)
110
+ path = request_path(folder, name)
111
+ except (ValueError, TypeError) as exc:
112
+ return error(exc)
113
+ if not path.is_file():
114
+ return error("Request not found.", 404)
115
+ try:
116
+ return jsonify(read_json(path))
117
+ except (OSError, ValueError) as exc:
118
+ return error(f"Could not read request: {exc}", 500)
119
+
120
+
121
+ @app.put("/api/requests/<path:item>")
122
+ def save_request(item):
123
+ try:
124
+ folder, name = item.rsplit("/", 1)
125
+ path = request_path(folder, name)
126
+ except (ValueError, TypeError) as exc:
127
+ return error(exc)
128
+ if not path.parent.is_dir():
129
+ return error("Folder not found.", 404)
130
+ data = request.get_json(silent=True)
131
+ if not isinstance(data, dict):
132
+ return error("Request data must be a JSON object.")
133
+ form = data.get("form") if isinstance(data.get("form"), list) else []
134
+ saved = {
135
+ "name": name,
136
+ "method": data.get("method", "GET"),
137
+ "url": data.get("url", ""),
138
+ "params": data.get("params", []),
139
+ "headers": data.get("headers", []),
140
+ "auth": data.get("auth", {"type": "tokenbox"}),
141
+ "body_type": data.get("body_type", "none"),
142
+ "body": data.get("body", ""),
143
+ # File contents are never saved; only the file name is kept.
144
+ "form": [{key: row.get(key) for key in ("key", "value", "enabled", "type", "filename") if key in row}
145
+ for row in form if isinstance(row, dict)],
146
+ }
147
+ write_json(path, saved)
148
+ return jsonify(saved)
149
+
150
+
151
+ @app.delete("/api/requests/<path:item>")
152
+ def delete_request(item):
153
+ try:
154
+ folder, name = item.rsplit("/", 1)
155
+ path = request_path(folder, name)
156
+ except (ValueError, TypeError) as exc:
157
+ return error(exc)
158
+ if not path.is_file():
159
+ return error("Request not found.", 404)
160
+ path.unlink()
161
+ for _, version_path in response_versions(folder, name):
162
+ version_path.unlink()
163
+ return jsonify(ok=True)
164
+
165
+
166
+ @app.post("/api/move")
167
+ def move_request():
168
+ data = request.get_json(silent=True) or {}
169
+ try:
170
+ folder, name, target = data.get("folder"), data.get("name"), data.get("target")
171
+ source = request_path(folder, name)
172
+ destination = request_path(target, name)
173
+ except ValueError as exc:
174
+ return error(exc)
175
+ if not source.is_file():
176
+ return error("Request not found.", 404)
177
+ if not destination.parent.is_dir():
178
+ return error("Target folder not found.", 404)
179
+ if destination.exists():
180
+ return error("A request with that name already exists in the target folder.")
181
+ source.rename(destination)
182
+ versions = response_versions(folder, name)
183
+ if versions:
184
+ target_dir = collection_path(target, storage.RESPONSES)
185
+ target_dir.mkdir(parents=True, exist_ok=True)
186
+ for _, version_path in versions:
187
+ version_path.rename(target_dir / version_path.name)
188
+ return jsonify(folder=target, name=name)
189
+
190
+
191
+ @app.post("/api/rename")
192
+ def rename_item():
193
+ data = request.get_json(silent=True) or {}
194
+ kind, folder, name = data.get("kind"), data.get("folder"), data.get("name")
195
+ try:
196
+ new_name = safe_name(str(data.get("new_name", "")).strip())
197
+ if kind == "folder":
198
+ source = collection_path(folder)
199
+ target = source.parent / new_name
200
+ else:
201
+ source = request_path(folder, name)
202
+ target = request_path(folder, new_name)
203
+ except ValueError as exc:
204
+ return error(exc)
205
+ if not source.exists():
206
+ return error("Item not found.", 404)
207
+ if target.exists():
208
+ return error("That name is already used here.")
209
+ if kind == "folder":
210
+ source.rename(target)
211
+ old_responses = collection_path(folder, storage.RESPONSES)
212
+ if old_responses.is_dir():
213
+ old_responses.rename(old_responses.parent / new_name)
214
+ return jsonify(folder=target.relative_to(storage.COLLECTIONS).as_posix())
215
+ versions = response_versions(folder, name)
216
+ saved = read_json(source)
217
+ saved["name"] = new_name
218
+ write_json(target, saved)
219
+ source.unlink()
220
+ for number, path in versions:
221
+ path.rename(path.with_name(f"{new_name}_v{number}.json"))
222
+ return jsonify(folder=folder, name=new_name)
223
+
224
+
225
+ @app.post("/api/duplicate")
226
+ def duplicate_item():
227
+ data = request.get_json(silent=True) or {}
228
+ kind, folder, name = data.get("kind"), data.get("folder"), data.get("name")
229
+ try:
230
+ if kind == "folder":
231
+ source = collection_path(folder)
232
+ if not source.is_dir():
233
+ return error("Folder not found.", 404)
234
+ new_name = copy_name(source.name, lambda candidate: (source.parent / candidate).exists())
235
+ target = source.parent / new_name
236
+ shutil.copytree(source, target)
237
+ return jsonify(folder=target.relative_to(storage.COLLECTIONS).as_posix()), 201
238
+ source = request_path(folder, name)
239
+ if not source.is_file():
240
+ return error("Request not found.", 404)
241
+ new_name = copy_name(name, lambda candidate: request_path(folder, candidate).exists())
242
+ except ValueError as exc:
243
+ return error(exc)
244
+ saved = read_json(source)
245
+ saved["name"] = new_name
246
+ write_json(request_path(folder, new_name), saved)
247
+ return jsonify(folder=folder, name=new_name), 201
248
+
249
+
250
+ @app.get("/api/responses/<path:item>")
251
+ def get_responses(item):
252
+ try:
253
+ folder, name = item.rsplit("/", 1)
254
+ versions = response_versions(folder, name)
255
+ except (ValueError, TypeError) as exc:
256
+ return error(exc)
257
+ wanted = request.args.get("version", type=int)
258
+ if wanted is None:
259
+ return jsonify([{"version": number, "file": path.name} for number, path in versions])
260
+ for number, path in versions:
261
+ if number == wanted:
262
+ return jsonify(read_json(path))
263
+ return error("Response version not found.", 404)
264
+
265
+
266
+ @app.post("/api/responses/<path:item>")
267
+ def save_response(item):
268
+ try:
269
+ folder, name = item.rsplit("/", 1)
270
+ source = request_path(folder, name)
271
+ versions = response_versions(folder, name)
272
+ except (ValueError, TypeError) as exc:
273
+ return error(exc)
274
+ if not source.is_file():
275
+ return error("Save the request before saving its response.", 404)
276
+ data = request.get_json(silent=True)
277
+ if not isinstance(data, dict):
278
+ return error("Response data must be a JSON object.")
279
+ version = (versions[-1][0] if versions else 0) + 1
280
+ directory = collection_path(folder, storage.RESPONSES)
281
+ directory.mkdir(parents=True, exist_ok=True)
282
+ path = directory / f"{name}_v{version}.json"
283
+ write_json(path, {
284
+ "version": version,
285
+ "saved_at": datetime.now().isoformat(timespec="seconds"),
286
+ "request": read_json(source),
287
+ "response": {key: data.get(key) for key in ("status", "reason", "elapsed_ms", "size_bytes", "headers", "body", "is_json", "body_base64")},
288
+ })
289
+ return jsonify(version=version, file=path.name), 201
290
+
291
+
292
+ @app.route("/api/variables", methods=["GET", "PUT"])
293
+ def variables():
294
+ if request.method == "GET":
295
+ try:
296
+ return jsonify(read_environments())
297
+ except (OSError, ValueError) as exc:
298
+ return error(f"Could not read variables: {exc}", 500)
299
+ data = request.get_json(silent=True)
300
+ environments = data.get("environments") if isinstance(data, dict) else None
301
+ if not isinstance(environments, dict) or not environments or not all(
302
+ isinstance(name, str) and NAME_PATTERN.fullmatch(name) and isinstance(values, dict)
303
+ and all(isinstance(key, str) and isinstance(value, (str, int, float, bool)) for key, value in values.items())
304
+ for name, values in environments.items()
305
+ ):
306
+ return error("Environments must have valid names and simple key/value variables.")
307
+ if data.get("active") not in environments:
308
+ return error("The active environment does not exist.")
309
+ saved = {
310
+ "active": data["active"],
311
+ "environments": {name: clean_variables(values) for name, values in environments.items()},
312
+ }
313
+ write_json(storage.VARIABLES_FILE, saved)
314
+ return jsonify(saved)
315
+
316
+
317
+ @app.post("/api/parse-curl")
318
+ def parse_curl_route():
319
+ command = (request.get_json(silent=True) or {}).get("curl", "")
320
+ try:
321
+ return jsonify(parse_curl(command))
322
+ except (ValueError, TypeError) as exc:
323
+ return error(exc)
324
+
325
+
326
+ @app.post("/api/send")
327
+ def send_request():
328
+ data = request.get_json(silent=True)
329
+ if not isinstance(data, dict):
330
+ return error("Request data must be a JSON object.")
331
+ try:
332
+ return jsonify(send(data, load_variables()))
333
+ # RequestException subclasses OSError, so it must be caught first.
334
+ except requests.RequestException as exc:
335
+ if isinstance(exc, requests.exceptions.SSLError) or "ssl" in str(exc).lower():
336
+ return error(
337
+ "SSL error: if you are using Zscaler, please authenticate yourself "
338
+ f"(sign in to Zscaler) and try again.\n\nActual error: {exc}",
339
+ 502,
340
+ )
341
+ return error(f"Request failed: {exc}", 502)
342
+ except RequestError as exc:
343
+ return error(exc)
344
+ except (OSError, json.JSONDecodeError) as exc:
345
+ return error(f"Could not load variables: {exc}")
346
+ except ValueError as exc:
347
+ return error(f"Invalid request data: {exc}")
@@ -0,0 +1,32 @@
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import threading
5
+ import webbrowser
6
+ from pathlib import Path
7
+
8
+ import truststore
9
+
10
+ from minman import __version__
11
+ from minman.app import app
12
+ from minman.storage import configure
13
+
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser(prog="minman", description="MinMan - a tiny local API client.")
17
+ # 3326 avoids Flask's busy default 5000 (macOS AirPlay, ASP.NET, Docker registry).
18
+ parser.add_argument("--port", type=int, default=3326)
19
+ parser.add_argument("--data-dir", default=os.environ.get("MINMAN_HOME") or Path.home() / ".minman")
20
+ parser.add_argument("--no-browser", action="store_true", help="do not open the browser")
21
+ parser.add_argument("--logs", action=argparse.BooleanOptionalAction, default=False, help="show request logs")
22
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
23
+ args = parser.parse_args()
24
+
25
+ data_dir = configure(args.data_dir)
26
+ truststore.inject_into_ssl()
27
+ url = f"http://127.0.0.1:{args.port}"
28
+ print(f"MinMan running at {url} (data: {data_dir})")
29
+ if not args.no_browser:
30
+ threading.Timer(1, webbrowser.open, [url]).start()
31
+ logging.getLogger("werkzeug").disabled = not args.logs
32
+ app.run(host="127.0.0.1", port=args.port, debug=False)
@@ -0,0 +1,64 @@
1
+ import json
2
+ import shlex
3
+
4
+
5
+ def parse_curl(command):
6
+ for continuation in ("\\\n", "^\n", "`\n"):
7
+ command = command.replace(continuation, " ")
8
+ tokens = shlex.split(command.strip())
9
+ if tokens and tokens[0].lower() in ("curl", "curl.exe"):
10
+ tokens = tokens[1:]
11
+
12
+ method, url, headers, body = None, None, [], ""
13
+ value_flags = {
14
+ "-X", "--request", "-H", "--header", "--url",
15
+ "-d", "--data", "--data-raw", "--data-binary",
16
+ }
17
+ index = 0
18
+ while index < len(tokens):
19
+ token = tokens[index]
20
+ value = tokens[index + 1] if token in value_flags and index + 1 < len(tokens) else None
21
+ if token in ("-X", "--request") and value is not None:
22
+ method = value.upper()
23
+ elif token in ("-H", "--header") and value is not None:
24
+ key, separator, header_value = value.partition(":")
25
+ if separator:
26
+ headers.append({"key": key.strip(), "value": header_value.strip()})
27
+ elif token == "--url" and value is not None:
28
+ url = value
29
+ elif token in ("-d", "--data", "--data-raw", "--data-binary") and value is not None:
30
+ body = value
31
+ elif not token.startswith("-") and url is None:
32
+ url = token
33
+ index += 2 if value is not None else 1
34
+
35
+ if not url:
36
+ raise ValueError("No URL was found in the cURL command.")
37
+
38
+ token_value = ""
39
+ remaining_headers = []
40
+ for header in headers:
41
+ if header["key"].lower() == "authorization_token":
42
+ token_value = header["value"]
43
+ else:
44
+ remaining_headers.append(header)
45
+
46
+ return {
47
+ "method": method or ("POST" if body else "GET"),
48
+ "url": url,
49
+ "headers": remaining_headers,
50
+ "params": [],
51
+ "body": body,
52
+ "body_type": body_type_for(body),
53
+ "token": token_value,
54
+ }
55
+
56
+
57
+ def body_type_for(body):
58
+ if not body:
59
+ return "none"
60
+ try:
61
+ json.loads(body)
62
+ return "json"
63
+ except ValueError:
64
+ return "text"