feincms3-api-cli 0.0.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.
- feincms3_api_cli/__init__.py +3 -0
- feincms3_api_cli/__main__.py +4 -0
- feincms3_api_cli/client.py +76 -0
- feincms3_api_cli/config.py +106 -0
- feincms3_api_cli/main.py +479 -0
- feincms3_api_cli-0.0.1.dist-info/METADATA +101 -0
- feincms3_api_cli-0.0.1.dist-info/RECORD +9 -0
- feincms3_api_cli-0.0.1.dist-info/WHEEL +4 -0
- feincms3_api_cli-0.0.1.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""HTTP for the content API, with the standard library only"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import mimetypes
|
|
5
|
+
import os
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
import uuid
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class APIError(Exception):
|
|
13
|
+
def __init__(self, status, data):
|
|
14
|
+
super().__init__(status, data)
|
|
15
|
+
self.status = status
|
|
16
|
+
self.data = data
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Client:
|
|
20
|
+
def __init__(self, url, token):
|
|
21
|
+
self.url = url.rstrip("/") + "/"
|
|
22
|
+
self.token = token
|
|
23
|
+
|
|
24
|
+
def request(self, method, path, *, params=None, body=None, headers=None):
|
|
25
|
+
url = self.url + path.lstrip("/")
|
|
26
|
+
if params := {
|
|
27
|
+
key: value for key, value in (params or {}).items() if value is not None
|
|
28
|
+
}:
|
|
29
|
+
url += "?" + urllib.parse.urlencode(params, doseq=True)
|
|
30
|
+
headers = {"Accept": "application/json", **(headers or {})}
|
|
31
|
+
if self.token:
|
|
32
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
33
|
+
data = None
|
|
34
|
+
if body is not None:
|
|
35
|
+
data = json.dumps(body).encode()
|
|
36
|
+
headers["Content-Type"] = "application/json"
|
|
37
|
+
return self._send(urllib.request.Request(url, data, headers, method=method))
|
|
38
|
+
|
|
39
|
+
def upload(self, path):
|
|
40
|
+
boundary = uuid.uuid4().hex
|
|
41
|
+
name = os.path.basename(path)
|
|
42
|
+
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
43
|
+
with open(path, "rb") as f:
|
|
44
|
+
content = f.read()
|
|
45
|
+
data = b"".join(
|
|
46
|
+
[
|
|
47
|
+
f"--{boundary}\r\n".encode(),
|
|
48
|
+
f'Content-Disposition: form-data; name="file"; filename="{name}"\r\n'.encode(),
|
|
49
|
+
f"Content-Type: {content_type}\r\n\r\n".encode(),
|
|
50
|
+
content,
|
|
51
|
+
f"\r\n--{boundary}--\r\n".encode(),
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
headers = {
|
|
55
|
+
"Accept": "application/json",
|
|
56
|
+
"Content-Type": f"multipart/form-data; boundary={boundary}",
|
|
57
|
+
}
|
|
58
|
+
if self.token:
|
|
59
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
60
|
+
request = urllib.request.Request(
|
|
61
|
+
self.url + "uploads/", data, headers, method="POST"
|
|
62
|
+
)
|
|
63
|
+
return self._send(request)
|
|
64
|
+
|
|
65
|
+
def _send(self, request):
|
|
66
|
+
try:
|
|
67
|
+
with urllib.request.urlopen(request) as response:
|
|
68
|
+
content = response.read()
|
|
69
|
+
return response.status, json.loads(content) if content else None
|
|
70
|
+
except urllib.error.HTTPError as exc:
|
|
71
|
+
content = exc.read()
|
|
72
|
+
try:
|
|
73
|
+
data = json.loads(content)
|
|
74
|
+
except ValueError:
|
|
75
|
+
data = {"detail": content.decode(errors="replace") or exc.reason}
|
|
76
|
+
raise APIError(exc.code, data) from None
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sites (URL and token) and the ETags of what was read
|
|
3
|
+
|
|
4
|
+
``F3API_URL`` and ``F3API_TOKEN`` override the configured site;
|
|
5
|
+
``F3API_CONFIG`` and ``F3API_CACHE`` move the files (for tests).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _dir(env, xdg, default):
|
|
14
|
+
if path := os.environ.get(env):
|
|
15
|
+
return Path(path)
|
|
16
|
+
return Path(os.environ.get(xdg) or Path.home() / default) / "f3api"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def config_dir():
|
|
20
|
+
return _dir("F3API_CONFIG", "XDG_CONFIG_HOME", ".config")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def cache_dir():
|
|
24
|
+
return _dir("F3API_CACHE", "XDG_CACHE_HOME", ".cache")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _load(path):
|
|
28
|
+
try:
|
|
29
|
+
return json.loads(path.read_text())
|
|
30
|
+
except FileNotFoundError:
|
|
31
|
+
return {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _save(path, data, *, private=False):
|
|
35
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
36
|
+
tmp = path.with_suffix(".tmp")
|
|
37
|
+
tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
|
|
38
|
+
if private:
|
|
39
|
+
tmp.chmod(0o600)
|
|
40
|
+
tmp.replace(path)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Sites:
|
|
44
|
+
def __init__(self):
|
|
45
|
+
self.path = config_dir() / "sites.json"
|
|
46
|
+
self.data = _load(self.path) or {"default": None, "sites": {}}
|
|
47
|
+
|
|
48
|
+
def save(self):
|
|
49
|
+
_save(self.path, self.data, private=True)
|
|
50
|
+
|
|
51
|
+
def add(self, name, url, token):
|
|
52
|
+
self.data["sites"][name] = {"url": url, "token": token}
|
|
53
|
+
if not self.data.get("default"):
|
|
54
|
+
self.data["default"] = name
|
|
55
|
+
self.save()
|
|
56
|
+
|
|
57
|
+
def remove(self, name):
|
|
58
|
+
self.data["sites"].pop(name)
|
|
59
|
+
if self.data.get("default") == name:
|
|
60
|
+
self.data["default"] = next(iter(self.data["sites"]), None)
|
|
61
|
+
self.save()
|
|
62
|
+
|
|
63
|
+
def set_default(self, name):
|
|
64
|
+
if name not in self.data["sites"]:
|
|
65
|
+
raise KeyError(name)
|
|
66
|
+
self.data["default"] = name
|
|
67
|
+
self.save()
|
|
68
|
+
|
|
69
|
+
def resolve(self, name=None):
|
|
70
|
+
"""``(url, token)``"""
|
|
71
|
+
if url := os.environ.get("F3API_URL"):
|
|
72
|
+
return url, os.environ.get("F3API_TOKEN")
|
|
73
|
+
name = name or os.environ.get("F3API_SITE") or self.data.get("default")
|
|
74
|
+
if not name or name not in self.data["sites"]:
|
|
75
|
+
raise LookupError(
|
|
76
|
+
"No site: add one with `f3api site add NAME URL`, or set"
|
|
77
|
+
" F3API_URL and F3API_TOKEN."
|
|
78
|
+
)
|
|
79
|
+
site = self.data["sites"][name]
|
|
80
|
+
return site["url"], os.environ.get("F3API_TOKEN") or site["token"]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ETags:
|
|
84
|
+
"""The ETag of each object as last read, per site"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, url):
|
|
87
|
+
self.path = cache_dir() / "etags.json"
|
|
88
|
+
self.url = url.rstrip("/")
|
|
89
|
+
|
|
90
|
+
def _key(self, resource, pk):
|
|
91
|
+
return f"{self.url} {resource}/{pk}"
|
|
92
|
+
|
|
93
|
+
def get(self, resource, pk):
|
|
94
|
+
return _load(self.path).get(self._key(resource, pk))
|
|
95
|
+
|
|
96
|
+
def update(self, entries):
|
|
97
|
+
"""``entries``: ``{(resource, id): etag or None}``"""
|
|
98
|
+
if not entries:
|
|
99
|
+
return
|
|
100
|
+
data = _load(self.path)
|
|
101
|
+
for (resource, pk), etag in entries.items():
|
|
102
|
+
if etag is None:
|
|
103
|
+
data.pop(self._key(resource, pk), None)
|
|
104
|
+
else:
|
|
105
|
+
data[self._key(resource, pk)] = etag
|
|
106
|
+
_save(self.path, data)
|
feincms3_api_cli/main.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The feincms3 content API from the command line (``f3api``)
|
|
3
|
+
|
|
4
|
+
Reads print JSON. Writes are dry runs unless ``--apply`` is given, and send
|
|
5
|
+
the ETag of the object as it was last read with this tool (``get``,
|
|
6
|
+
``list``, ``find``), so they fail instead of overwriting someone else's
|
|
7
|
+
change. Errors are printed with their paths.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import getpass
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from feincms3_api_cli.client import APIError, Client
|
|
16
|
+
from feincms3_api_cli.config import ETags, Sites
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# Exit codes
|
|
20
|
+
OK, FAILED, USAGE, INVALID, CONFLICT, NOT_FOUND, FORBIDDEN = range(7)
|
|
21
|
+
STATUS_EXIT = {
|
|
22
|
+
422: INVALID,
|
|
23
|
+
409: CONFLICT,
|
|
24
|
+
412: CONFLICT,
|
|
25
|
+
428: CONFLICT,
|
|
26
|
+
404: NOT_FOUND,
|
|
27
|
+
401: FORBIDDEN,
|
|
28
|
+
403: FORBIDDEN,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CommandError(Exception):
|
|
33
|
+
def __init__(self, message, code=FAILED):
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.code = code
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main(argv=None):
|
|
39
|
+
parser = build_parser()
|
|
40
|
+
args = parser.parse_args(argv)
|
|
41
|
+
if not getattr(args, "handler", None):
|
|
42
|
+
parser.print_help()
|
|
43
|
+
return USAGE
|
|
44
|
+
try:
|
|
45
|
+
return args.handler(args) or OK
|
|
46
|
+
except APIError as exc:
|
|
47
|
+
print_error(exc)
|
|
48
|
+
return STATUS_EXIT.get(exc.status, FAILED)
|
|
49
|
+
except CommandError as exc:
|
|
50
|
+
print(f"f3api: {exc}", file=sys.stderr)
|
|
51
|
+
return exc.code
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def print_error(exc):
|
|
55
|
+
data = exc.data if isinstance(exc.data, dict) else {"detail": exc.data}
|
|
56
|
+
prefix = f"operation {data['operation']}: " if "operation" in data else ""
|
|
57
|
+
print(f"f3api: {exc.status} {prefix}{data.get('detail', '')}", file=sys.stderr)
|
|
58
|
+
for error in data.get("errors") or ():
|
|
59
|
+
if isinstance(error, dict):
|
|
60
|
+
path = error.get("path") or error.get("loc") or ""
|
|
61
|
+
message = error.get("message") or error.get("msg") or ""
|
|
62
|
+
print(f" {path}: {message}", file=sys.stderr)
|
|
63
|
+
for key, value in data.items():
|
|
64
|
+
if key not in {"detail", "errors", "operation"}:
|
|
65
|
+
print(f" {key}: {json.dumps(value)}", file=sys.stderr)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def output(data):
|
|
69
|
+
json.dump(data, sys.stdout, indent=2, ensure_ascii=False)
|
|
70
|
+
sys.stdout.write("\n")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def read_json(path):
|
|
74
|
+
try:
|
|
75
|
+
if path in {None, "-"}:
|
|
76
|
+
return json.load(sys.stdin)
|
|
77
|
+
with open(path) as f:
|
|
78
|
+
return json.load(f)
|
|
79
|
+
except (OSError, ValueError) as exc:
|
|
80
|
+
raise CommandError(
|
|
81
|
+
f"Can't read JSON from {path or 'stdin'}: {exc}", USAGE
|
|
82
|
+
) from exc
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def connect(args):
|
|
86
|
+
try:
|
|
87
|
+
url, token = Sites().resolve(args.site)
|
|
88
|
+
except LookupError as exc:
|
|
89
|
+
raise CommandError(str(exc), USAGE) from exc
|
|
90
|
+
return Client(url, token), ETags(url)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _etag(wire):
|
|
94
|
+
return (wire or {}).get("meta", {}).get("etag")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# Sites ######################################################################
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def site_add(args):
|
|
101
|
+
token = (
|
|
102
|
+
sys.stdin.readline().strip() if args.token_stdin else getpass.getpass("Token: ")
|
|
103
|
+
)
|
|
104
|
+
Sites().add(args.name, args.url, token)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def site_list(args):
|
|
108
|
+
data = Sites().data
|
|
109
|
+
output(
|
|
110
|
+
{
|
|
111
|
+
name: {"url": site["url"], "default": name == data.get("default")}
|
|
112
|
+
for name, site in data["sites"].items()
|
|
113
|
+
}
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def site_remove(args):
|
|
118
|
+
try:
|
|
119
|
+
Sites().remove(args.name)
|
|
120
|
+
except KeyError as exc:
|
|
121
|
+
raise CommandError(f"No site {args.name!r}.", USAGE) from exc
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def site_default(args):
|
|
125
|
+
try:
|
|
126
|
+
Sites().set_default(args.name)
|
|
127
|
+
except KeyError as exc:
|
|
128
|
+
raise CommandError(f"No site {args.name!r}.", USAGE) from exc
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# Reading ####################################################################
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def resources(args):
|
|
135
|
+
client, _etags = connect(args)
|
|
136
|
+
_status, data = client.request("GET", "schema/")
|
|
137
|
+
output(
|
|
138
|
+
[
|
|
139
|
+
{"name": r["name"], "type": r["type"], "title": r["title"]}
|
|
140
|
+
for r in data["resources"]
|
|
141
|
+
]
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def schema(args):
|
|
146
|
+
client, _etags = connect(args)
|
|
147
|
+
path = f"schema/{args.type}/" if args.type else "schema/"
|
|
148
|
+
output(client.request("GET", path)[1])
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def list_objects(args):
|
|
152
|
+
client, etags = connect(args)
|
|
153
|
+
params = dict(_pair(f) for f in args.filter)
|
|
154
|
+
params |= {
|
|
155
|
+
"limit": args.limit,
|
|
156
|
+
"offset": args.offset,
|
|
157
|
+
"q": args.q,
|
|
158
|
+
"fields": args.fields,
|
|
159
|
+
"content": "true" if args.content else None,
|
|
160
|
+
"expand": "references" if args.expand else None,
|
|
161
|
+
}
|
|
162
|
+
_status, data = client.request("GET", f"{args.resource}/", params=params)
|
|
163
|
+
# Without content, an item's ETag isn't the object's.
|
|
164
|
+
if args.content:
|
|
165
|
+
etags.update(
|
|
166
|
+
{(args.resource, item["id"]): _etag(item) for item in data["items"]}
|
|
167
|
+
)
|
|
168
|
+
output(data)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _pair(value):
|
|
172
|
+
key, sep, rest = value.partition("=")
|
|
173
|
+
if not sep:
|
|
174
|
+
raise CommandError(f"Expected key=value, not {value!r}.", USAGE)
|
|
175
|
+
return key, rest
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def get(args):
|
|
179
|
+
client, etags = connect(args)
|
|
180
|
+
_status, data = client.request(
|
|
181
|
+
"GET",
|
|
182
|
+
f"{args.resource}/{args.id}/",
|
|
183
|
+
params={
|
|
184
|
+
"nested": "true" if args.nested else None,
|
|
185
|
+
"expand": "references" if args.expand else None,
|
|
186
|
+
},
|
|
187
|
+
)
|
|
188
|
+
etags.update({(args.resource, data["id"]): _etag(data)})
|
|
189
|
+
output(data)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def find(args):
|
|
193
|
+
client, etags = connect(args)
|
|
194
|
+
_status, data = client.request(
|
|
195
|
+
"GET",
|
|
196
|
+
f"{args.resource}/find/",
|
|
197
|
+
params={"path": args.path, "host": args.host},
|
|
198
|
+
)
|
|
199
|
+
etags.update({(args.resource, data["id"]): _etag(data)})
|
|
200
|
+
output(data)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def plugin(args):
|
|
204
|
+
client, _etags = connect(args)
|
|
205
|
+
path = f"{args.resource}/{args.id}/plugins/{args.type}/{args.plugin_id}/"
|
|
206
|
+
output(client.request("GET", path)[1])
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# Writing ####################################################################
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _written(args, data):
|
|
213
|
+
if not args.apply:
|
|
214
|
+
print(
|
|
215
|
+
"f3api: dry run, nothing saved; run again with --apply to save.",
|
|
216
|
+
file=sys.stderr,
|
|
217
|
+
)
|
|
218
|
+
output(data)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _if_match(args, etags, resource, pk):
|
|
222
|
+
if args.force:
|
|
223
|
+
return "*"
|
|
224
|
+
if args.etag:
|
|
225
|
+
return args.etag
|
|
226
|
+
if etag := etags.get(resource, pk):
|
|
227
|
+
return etag
|
|
228
|
+
raise CommandError(
|
|
229
|
+
f"No ETag for {resource}/{pk}: read it first (f3api get {resource} {pk}),"
|
|
230
|
+
" or pass --etag or --force.",
|
|
231
|
+
CONFLICT,
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _params(args):
|
|
236
|
+
return {"dry_run": None if args.apply else "true"}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def create(args):
|
|
240
|
+
client, etags = connect(args)
|
|
241
|
+
_status, data = client.request(
|
|
242
|
+
"POST", f"{args.resource}/", params=_params(args), body=read_json(args.file)
|
|
243
|
+
)
|
|
244
|
+
if args.apply:
|
|
245
|
+
etags.update({(args.resource, data["id"]): _etag(data)})
|
|
246
|
+
_written(args, data)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def update(args):
|
|
250
|
+
client, etags = connect(args)
|
|
251
|
+
_status, data = client.request(
|
|
252
|
+
"PATCH",
|
|
253
|
+
f"{args.resource}/{args.id}/",
|
|
254
|
+
params=_params(args),
|
|
255
|
+
body=read_json(args.file),
|
|
256
|
+
headers={"If-Match": _if_match(args, etags, args.resource, args.id)},
|
|
257
|
+
)
|
|
258
|
+
if args.apply:
|
|
259
|
+
etags.update({(args.resource, args.id): _etag(data)})
|
|
260
|
+
_written(args, data)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def content(args):
|
|
264
|
+
client, etags = connect(args)
|
|
265
|
+
body = read_json(args.file)
|
|
266
|
+
if not (isinstance(body, dict) and "content" in body):
|
|
267
|
+
body = {"content": body}
|
|
268
|
+
_status, data = client.request(
|
|
269
|
+
"PUT",
|
|
270
|
+
f"{args.resource}/{args.id}/content/",
|
|
271
|
+
params=_params(args),
|
|
272
|
+
body=body,
|
|
273
|
+
headers={"If-Match": _if_match(args, etags, args.resource, args.id)},
|
|
274
|
+
)
|
|
275
|
+
if args.apply:
|
|
276
|
+
etags.update({(args.resource, args.id): _etag(data)})
|
|
277
|
+
_written(args, data)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def update_plugin(args):
|
|
281
|
+
client, etags = connect(args)
|
|
282
|
+
body = read_json(args.file)
|
|
283
|
+
if not (isinstance(body, dict) and set(body) == {"fields"}):
|
|
284
|
+
body = {"fields": body}
|
|
285
|
+
_status, data = client.request(
|
|
286
|
+
"PATCH",
|
|
287
|
+
f"{args.resource}/{args.id}/plugins/{args.type}/{args.plugin_id}/",
|
|
288
|
+
params=_params(args),
|
|
289
|
+
body=body,
|
|
290
|
+
headers={"If-Match": _if_match(args, etags, args.resource, args.id)},
|
|
291
|
+
)
|
|
292
|
+
if args.apply:
|
|
293
|
+
etags.update({(args.resource, args.id): _etag(data)})
|
|
294
|
+
_written(args, data)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def delete(args):
|
|
298
|
+
client, etags = connect(args)
|
|
299
|
+
client.request(
|
|
300
|
+
"DELETE",
|
|
301
|
+
f"{args.resource}/{args.id}/",
|
|
302
|
+
params=_params(args),
|
|
303
|
+
headers={"If-Match": _if_match(args, etags, args.resource, args.id)},
|
|
304
|
+
)
|
|
305
|
+
if args.apply:
|
|
306
|
+
etags.update({(args.resource, args.id): None})
|
|
307
|
+
print(f"f3api: deleted {args.resource}/{args.id}.", file=sys.stderr)
|
|
308
|
+
else:
|
|
309
|
+
print(
|
|
310
|
+
f"f3api: dry run, {args.resource}/{args.id} can be deleted; run"
|
|
311
|
+
" again with --apply to delete it.",
|
|
312
|
+
file=sys.stderr,
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def cache_clear(args):
|
|
317
|
+
client, _etags = connect(args)
|
|
318
|
+
client.request("DELETE", f"{args.resource}/{args.id}/cache/")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def upload(args):
|
|
322
|
+
client, _etags = connect(args)
|
|
323
|
+
try:
|
|
324
|
+
output(client.upload(args.file)[1])
|
|
325
|
+
except OSError as exc:
|
|
326
|
+
raise CommandError(f"Can't read {args.file}: {exc}", USAGE) from exc
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def batch(args):
|
|
330
|
+
client, etags = connect(args)
|
|
331
|
+
body = read_json(args.file)
|
|
332
|
+
if isinstance(body, list):
|
|
333
|
+
body = {"operations": body}
|
|
334
|
+
operations = body.get("operations") if isinstance(body, dict) else None
|
|
335
|
+
for operation in operations if isinstance(operations, list) else ():
|
|
336
|
+
if (
|
|
337
|
+
isinstance(operation, dict)
|
|
338
|
+
and operation.get("op") != "create"
|
|
339
|
+
and "etag" not in operation
|
|
340
|
+
and not isinstance(operation.get("id"), dict)
|
|
341
|
+
and (etag := etags.get(operation.get("resource"), operation.get("id")))
|
|
342
|
+
):
|
|
343
|
+
operation["etag"] = etag
|
|
344
|
+
_status, data = client.request("POST", "batch/", params=_params(args), body=body)
|
|
345
|
+
if args.apply:
|
|
346
|
+
entries = {}
|
|
347
|
+
for operation, result in zip(operations, data["results"], strict=False):
|
|
348
|
+
resource = operation["resource"]
|
|
349
|
+
if operation["op"] == "delete":
|
|
350
|
+
entries[resource, operation["id"]] = None
|
|
351
|
+
elif operation["op"] == "create":
|
|
352
|
+
entries[resource, result["id"]] = _etag(result)
|
|
353
|
+
else:
|
|
354
|
+
pk = operation["id"]
|
|
355
|
+
if isinstance(pk, dict):
|
|
356
|
+
pk = data["refs"][pk["ref"]]
|
|
357
|
+
entries[resource, pk] = _etag(result)
|
|
358
|
+
etags.update(entries)
|
|
359
|
+
_written(args, data)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
# The parser #################################################################
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def build_parser():
|
|
366
|
+
parser = argparse.ArgumentParser(
|
|
367
|
+
prog="f3api",
|
|
368
|
+
description="The feincms3 content API from the command line.",
|
|
369
|
+
epilog="Exit codes: 0 done, 1 failed, 2 usage, 3 invalid data (with"
|
|
370
|
+
" paths), 4 conflict (ETag, references), 5 not found, 6 not allowed.",
|
|
371
|
+
)
|
|
372
|
+
parser.add_argument("--site", help="a site added with `site add`")
|
|
373
|
+
commands = parser.add_subparsers(title="commands")
|
|
374
|
+
|
|
375
|
+
def command(name, handler, help):
|
|
376
|
+
sub = commands.add_parser(name, help=help, description=help)
|
|
377
|
+
sub.set_defaults(handler=handler)
|
|
378
|
+
return sub
|
|
379
|
+
|
|
380
|
+
site = commands.add_parser("site", help="the sites and their tokens")
|
|
381
|
+
sites = site.add_subparsers(title="site commands")
|
|
382
|
+
add = sites.add_parser("add", help="add a site; asks for the token")
|
|
383
|
+
add.add_argument("name")
|
|
384
|
+
add.add_argument("url", help="where the API is, e.g. https://example.com/api/")
|
|
385
|
+
add.add_argument(
|
|
386
|
+
"--token-stdin", action="store_true", help="read the token from stdin"
|
|
387
|
+
)
|
|
388
|
+
add.set_defaults(handler=site_add)
|
|
389
|
+
sites.add_parser("list", help="the sites").set_defaults(handler=site_list)
|
|
390
|
+
remove = sites.add_parser("remove", help="remove a site")
|
|
391
|
+
remove.add_argument("name")
|
|
392
|
+
remove.set_defaults(handler=site_remove)
|
|
393
|
+
default = sites.add_parser("default", help="use a site by default")
|
|
394
|
+
default.add_argument("name")
|
|
395
|
+
default.set_defaults(handler=site_default)
|
|
396
|
+
|
|
397
|
+
command("resources", resources, "the resources")
|
|
398
|
+
sub = command("schema", schema, "the regions and plugins, or one type's fields")
|
|
399
|
+
sub.add_argument("type", nargs="?", help="e.g. pages.page")
|
|
400
|
+
|
|
401
|
+
sub = command("list", list_objects, "list objects")
|
|
402
|
+
sub.add_argument("resource")
|
|
403
|
+
sub.add_argument("-f", "--filter", action="append", default=[], metavar="KEY=VALUE")
|
|
404
|
+
sub.add_argument("-q", help="search")
|
|
405
|
+
sub.add_argument("--limit", type=int)
|
|
406
|
+
sub.add_argument("--offset", type=int)
|
|
407
|
+
sub.add_argument("--fields", help="only these fields, comma separated")
|
|
408
|
+
sub.add_argument("--content", action="store_true", help="with content")
|
|
409
|
+
sub.add_argument("--expand", action="store_true", help="describe references")
|
|
410
|
+
|
|
411
|
+
sub = command("get", get, "one object")
|
|
412
|
+
sub.add_argument("resource")
|
|
413
|
+
sub.add_argument("id")
|
|
414
|
+
sub.add_argument("--nested", action="store_true", help="containers with children")
|
|
415
|
+
sub.add_argument("--expand", action="store_true", help="describe references")
|
|
416
|
+
|
|
417
|
+
sub = command("find", find, "an object by its path")
|
|
418
|
+
sub.add_argument("path")
|
|
419
|
+
sub.add_argument("--resource", default="pages")
|
|
420
|
+
sub.add_argument("--host")
|
|
421
|
+
|
|
422
|
+
sub = command("plugin", plugin, "one plugin of an object")
|
|
423
|
+
sub.add_argument("resource")
|
|
424
|
+
sub.add_argument("id")
|
|
425
|
+
sub.add_argument("type")
|
|
426
|
+
sub.add_argument("plugin_id")
|
|
427
|
+
|
|
428
|
+
def writing(sub, *, etag=True):
|
|
429
|
+
sub.add_argument(
|
|
430
|
+
"--apply", action="store_true", help="save; without it, a dry run"
|
|
431
|
+
)
|
|
432
|
+
if etag:
|
|
433
|
+
sub.add_argument("--etag", help="instead of the one last read")
|
|
434
|
+
sub.add_argument(
|
|
435
|
+
"--force", action="store_true", help="overwrite whatever is there"
|
|
436
|
+
)
|
|
437
|
+
return sub
|
|
438
|
+
|
|
439
|
+
sub = writing(command("create", create, "create an object from JSON"), etag=False)
|
|
440
|
+
sub.add_argument("resource")
|
|
441
|
+
sub.add_argument("file", nargs="?", help="JSON; stdin if left out or -")
|
|
442
|
+
|
|
443
|
+
sub = writing(command("update", update, "change fields, replace regions"))
|
|
444
|
+
sub.add_argument("resource")
|
|
445
|
+
sub.add_argument("id")
|
|
446
|
+
sub.add_argument("file", nargs="?", help="JSON; stdin if left out or -")
|
|
447
|
+
|
|
448
|
+
sub = writing(command("content", content, "replace the regions given"))
|
|
449
|
+
sub.add_argument("resource")
|
|
450
|
+
sub.add_argument("id")
|
|
451
|
+
sub.add_argument("file", nargs="?", help="JSON; stdin if left out or -")
|
|
452
|
+
|
|
453
|
+
sub = writing(command("update-plugin", update_plugin, "change one plugin's fields"))
|
|
454
|
+
sub.add_argument("resource")
|
|
455
|
+
sub.add_argument("id")
|
|
456
|
+
sub.add_argument("type")
|
|
457
|
+
sub.add_argument("plugin_id")
|
|
458
|
+
sub.add_argument("file", nargs="?", help="JSON; stdin if left out or -")
|
|
459
|
+
|
|
460
|
+
sub = writing(command("delete", delete, "delete an object"))
|
|
461
|
+
sub.add_argument("resource")
|
|
462
|
+
sub.add_argument("id")
|
|
463
|
+
|
|
464
|
+
sub = command("cache-clear", cache_clear, "delete an object's cached rendering")
|
|
465
|
+
sub.add_argument("resource")
|
|
466
|
+
sub.add_argument("id")
|
|
467
|
+
|
|
468
|
+
sub = command("upload", upload, "stage a file; prints the reference to write")
|
|
469
|
+
sub.add_argument("file")
|
|
470
|
+
|
|
471
|
+
sub = writing(
|
|
472
|
+
command("batch", batch, "several writes in one transaction"), etag=False
|
|
473
|
+
)
|
|
474
|
+
sub.add_argument("file", nargs="?", help="JSON; stdin if left out or -")
|
|
475
|
+
return parser
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def main_exit():
|
|
479
|
+
sys.exit(main())
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: feincms3-api-cli
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: The feincms3 content API from the command line
|
|
5
|
+
Project-URL: Homepage, https://github.com/feincms/feincms3-api/
|
|
6
|
+
Author-email: Feinheit AG <dev@feinheit.ch>, Matthias Kestenholz <mk@feinheit.ch>
|
|
7
|
+
License-Expression: BSD-3-Clause
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# feincms3-api-cli
|
|
23
|
+
|
|
24
|
+
The [feincms3 content API](https://github.com/feincms/feincms3-api) from the
|
|
25
|
+
command line, for people and for agents with a shell. It talks HTTP with a
|
|
26
|
+
token, so it works against any site with the API, without the site's code.
|
|
27
|
+
Standard library only.
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
uvx feincms3-api-cli --help # or: pip install feincms3-api-cli
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Sites
|
|
34
|
+
|
|
35
|
+
A site is the API's URL and a token (create one in the admin, or with
|
|
36
|
+
`./manage.py f3api_token`):
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
f3api site add example https://example.com/api/ # asks for the token
|
|
40
|
+
f3api site list
|
|
41
|
+
f3api --site other list pages # the first site is the default
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`F3API_URL` and `F3API_TOKEN` override the configured site. Sites are kept
|
|
45
|
+
in `~/.config/f3api/sites.json` (readable by you only).
|
|
46
|
+
|
|
47
|
+
## Reading
|
|
48
|
+
|
|
49
|
+
Everything prints JSON:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
f3api resources
|
|
53
|
+
f3api schema # region sets and the plugins allowed per region
|
|
54
|
+
f3api schema pages.page # one type's fields
|
|
55
|
+
f3api list pages -f language_code=de -q angebot --fields title,path
|
|
56
|
+
f3api get pages 17 --expand # with meta.references
|
|
57
|
+
f3api find /de/angebot/
|
|
58
|
+
f3api plugin pages 17 pages.button 103
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Writing
|
|
62
|
+
|
|
63
|
+
Writes are **dry runs unless `--apply`** is given: run once, look at the
|
|
64
|
+
result and its `meta.warnings`, then run again with `--apply`.
|
|
65
|
+
|
|
66
|
+
Writes send the ETag of the object as it was last read with `f3api`
|
|
67
|
+
(`get`, `find`, `list --content`), so a write fails with exit code 4 if
|
|
68
|
+
someone changed the object since, instead of overwriting their change.
|
|
69
|
+
Read it again, or pass `--etag` or `--force`.
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
f3api get pages 17 > page.json
|
|
73
|
+
f3api update pages 17 <<'EOF'
|
|
74
|
+
{"fields": {"title": "Unser Angebot"}}
|
|
75
|
+
EOF
|
|
76
|
+
f3api update pages 17 changes.json --apply
|
|
77
|
+
f3api content pages 17 regions.json --apply # replace the regions given
|
|
78
|
+
f3api update-plugin pages 17 pages.button 103 --apply <<'EOF'
|
|
79
|
+
{"button_label": "Kontakt"}
|
|
80
|
+
EOF
|
|
81
|
+
f3api create pages new-page.json --apply
|
|
82
|
+
f3api delete articles 3 --apply
|
|
83
|
+
f3api cache-clear pages 17
|
|
84
|
+
f3api upload team.jpg # prints {"upload": "…"} to use in fields
|
|
85
|
+
f3api batch subtree.json --apply # several writes in one transaction
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
In a batch, operations without an `etag` get the one last read.
|
|
89
|
+
|
|
90
|
+
## Errors
|
|
91
|
+
|
|
92
|
+
Errors go to stderr with their paths:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
f3api: 422 The data isn't valid.
|
|
96
|
+
fields.slug: This field is required.
|
|
97
|
+
content.main[2].fields.text: …
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Exit codes: 0 done, 1 failed, 2 usage, 3 invalid data, 4 conflict (ETag,
|
|
101
|
+
references), 5 not found, 6 not allowed.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
feincms3_api_cli/__init__.py,sha256=G5l-x5XsSO-JgRZKtNHgDplnE9KY3FqvSpl8thbE0X0,76
|
|
2
|
+
feincms3_api_cli/__main__.py,sha256=QMsCMt4-6MN3PBOAzeTzWyiqckXoIo9yknbR2DmTtEk,58
|
|
3
|
+
feincms3_api_cli/client.py,sha256=eeekGkKpxFU8wwjJDDHYZ44J7c03BUAdOQrLUhItEOw,2670
|
|
4
|
+
feincms3_api_cli/config.py,sha256=lSiImjh0WfevyytQJrzvo1I4MeKir-OcdkzZWp6hAQU,3090
|
|
5
|
+
feincms3_api_cli/main.py,sha256=7E88M6TVTfR_fdwVIREy2G52SxRIjyAgwwGp5dtKAL8,15227
|
|
6
|
+
feincms3_api_cli-0.0.1.dist-info/METADATA,sha256=32IoADy_aqCun1s74e71b_2I5UdqzpoHjtQhXp6Lf8A,3390
|
|
7
|
+
feincms3_api_cli-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
feincms3_api_cli-0.0.1.dist-info/entry_points.txt,sha256=fxvGGE3pdN2UnnHHFZsDxCLvL_1UOAdoy-3Z7l8cgrk,58
|
|
9
|
+
feincms3_api_cli-0.0.1.dist-info/RECORD,,
|