formist-cli 0.1.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,221 @@
1
+ """Small helpers shared by more than one ``fm`` subcommand module.
2
+
3
+ Kept deliberately tiny and dependency-free (no import of ``formist_cli.cli``, so any
4
+ subcommand module can import this without a cycle): this is where a helper goes
5
+ the moment a second subcommand module needs the identical body, so it never gets
6
+ a third independent copy.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import sys
13
+ from collections.abc import Callable
14
+ from typing import Any
15
+
16
+ from formist_cli.targets import Target
17
+
18
+ #: The ``/admin/*`` gate, said once. Every `fm` subcommand that reaches an
19
+ #: ``/admin`` route shows this in its ``--help`` epilog, and they must not
20
+ #: drift: two half-right descriptions of one authorisation rule is how an
21
+ #: operator concludes the wrong thing about a 403.
22
+ PLATFORM_ADMIN_GATE_NOTE = (
23
+ "GATE: site-wide platform admin (User.is_platform_admin), re-checked fresh on "
24
+ "every call. A project OWNER or ADMIN is NOT sufficient: membership in a space "
25
+ "grants nothing here, so a 403 means the flag is missing from YOUR user row, not "
26
+ "that the user or the space is missing. `fm spaces --admin --host evane` reads "
27
+ "/admin behind the identical flag, so a working `fm spaces --admin` is the "
28
+ "cheapest proof you have it."
29
+ )
30
+
31
+ #: Help text for every ``--admin`` flag this CLI adds. Deliberately generic:
32
+ #: naming, in ``--help`` output, exactly which commands ``--admin`` unlocks is
33
+ #: the same kind of list this project's README keeps out of its public-facing
34
+ #: half, for the same reason, so the flag's own help never grows one either.
35
+ ADMIN_FLAG_HELP = "platform administrators only"
36
+
37
+
38
+ def add_admin_flag(parser: argparse.ArgumentParser) -> None:
39
+ """Add ``--admin`` to a subcommand, the same way ``cli._add_env`` wires
40
+ ``--host``: ``default=argparse.SUPPRESS`` so that when this flag is not
41
+ given on the subcommand itself, a value already set at the root parser
42
+ (``fm --admin <command>``) is left alone instead of being overwritten
43
+ back to ``False``.
44
+ """
45
+ parser.add_argument(
46
+ "--admin", action="store_true", default=argparse.SUPPRESS, help=ADMIN_FLAG_HELP,
47
+ )
48
+
49
+
50
+ def as_dict(payload: object, *, what: str, error: type[Exception]) -> dict:
51
+ """``payload`` as a dict, or raise ``error``, never ``{}``.
52
+
53
+ Anything that is not a dict is a server contract change, not an empty result.
54
+ Returning ``{}`` would render an empty table, which reads as "no rows", a
55
+ wrong answer where an error is the right one, and the exact
56
+ true-about-what-it-fetched-and-false-about-what-exists shape ``fm users``'
57
+ docstring is about.
58
+
59
+ ``error`` is passed in rather than raising one shared exception type because
60
+ each subcommand's own error class is what ``cli.py``'s handler catches
61
+ to print operator prose instead of a traceback.
62
+ """
63
+ if not isinstance(payload, dict):
64
+ raise error(
65
+ f"expected a JSON object from {what}, got {type(payload).__name__}. "
66
+ "That is a server contract change, not an empty result."
67
+ )
68
+ return payload
69
+
70
+
71
+ def pagination_footer(*, shown: int, total: int | None, offset: int = 0) -> str:
72
+ """The shown-vs-total footer line every paginated ``fm`` listing ends with.
73
+
74
+ ``fm users list`` and ``fm spaces`` (and its ``conversations`` / ``skills`` /
75
+ ``invitations`` subjects) each need this: a page of 50 printed on its own
76
+ reads as a platform with 50 rows, the exact shape ``fm users``' module
77
+ docstring is about.
78
+
79
+ The three cases:
80
+
81
+ * the server sent no ``total`` at all: say UNKNOWN rather than a count with
82
+ no denominator, which would be the most confident-looking way to be wrong;
83
+ * more rows exist than were shown: name both flags that get the rest;
84
+ * this page is the whole set (including the empty set): no alarm, because
85
+ an alarm that fires when nothing is wrong is an alarm nobody reads.
86
+ """
87
+ if total is None:
88
+ return f"{shown} shown, total UNKNOWN (the server sent no `total`)"
89
+ if offset + shown < int(total):
90
+ return (
91
+ f"{shown} shown (rows {offset + 1}-{offset + shown} of {total}), "
92
+ f"MORE EXIST. Use --offset {offset + shown} for the next page, or a "
93
+ f"larger --limit."
94
+ )
95
+ return f"{shown} of {total}"
96
+
97
+
98
+ class SubcommandParser(argparse.ArgumentParser):
99
+ """Subcommand parser that accepts options between positionals on Python < 3.12.
100
+
101
+ ``fm settings set --host evane a=true`` puts an option between two
102
+ positionals; argparse only handles that natively from 3.12.
103
+ """
104
+
105
+ _intermixed = False
106
+
107
+ def parse_known_args(self, args=None, namespace=None):
108
+ if sys.version_info >= (3, 12) or self._intermixed:
109
+ return super().parse_known_args(args, namespace)
110
+ self._intermixed = True
111
+ try:
112
+ return super().parse_known_intermixed_args(args, namespace)
113
+ except TypeError:
114
+ return super().parse_known_args(args, namespace)
115
+ finally:
116
+ self._intermixed = False
117
+
118
+
119
+ def build_standalone_parser(
120
+ add_parser: Callable[[argparse._SubParsersAction], argparse.ArgumentParser],
121
+ ) -> argparse.ArgumentParser:
122
+ """The same parser one subcommand module builds, detached, so ``--help`` can
123
+ be rendered/asserted in a test without going through the full `fm` CLI.
124
+
125
+ Built by calling the module's own ``add_parser`` rather than repeating its
126
+ arguments here: two definitions of one parser is two things to keep in
127
+ step, and the copy that drifts is the one a test asserts on. Each caller
128
+ stays a one-line, no-argument ``build_standalone_parser()``, so this is
129
+ the shared body, not a new public entry point to remember.
130
+ """
131
+ holder = argparse.ArgumentParser(prog="fm")
132
+ return add_parser(holder.add_subparsers(dest="command", parser_class=SubcommandParser))
133
+
134
+
135
+ def render_grant_rows(items: list[dict]) -> str:
136
+ """A grants table: one renderer for both ``fm users grants`` and
137
+ ``fm connectors grants``.
138
+
139
+ Both commands read the same server-side view, so they get the same
140
+ renderer rather than one each. Two copies of this would drift on exactly the
141
+ columns that are easy to get wrong (see below), and nothing would compare them.
142
+
143
+ The columns that must not lie, and why each is rendered the way it is:
144
+
145
+ ``scopes`` ``-`` when the provider records none (``scopes_recorded`` false)
146
+ versus ``(none granted)`` when it records an EMPTY set. Printing
147
+ an empty column for both would say "this credential may do
148
+ nothing" about an API key that may do everything.
149
+ ``expiry`` never a bare timestamp. ``access_token`` expiries are refreshed
150
+ silently and are always minutes away, so they are labelled as
151
+ such; ``none_recorded`` prints ``(not recorded)``, which is not
152
+ the same claim as "never expires".
153
+ ``status`` ``-`` when the provider records no auth status at all. An ``ok``
154
+ there would be an assurance nothing measured.
155
+ """
156
+ if not items:
157
+ return "(no grants, this subject has connected nothing)"
158
+ lines = [
159
+ f"{'provider':<18} {'identity':<34} {'status':<14} {'scopes':<9} expiry",
160
+ f"{'-' * 18} {'-' * 34} {'-' * 14} {'-' * 9} {'-' * 24}",
161
+ ]
162
+ for row in items:
163
+ if row.get("scopes_recorded"):
164
+ scopes = str(len(row.get("scopes") or [])) if row.get("scopes") else "0"
165
+ else:
166
+ scopes = "-"
167
+ lines.append(
168
+ f"{str(row.get('provider') or '-'):<18.18} "
169
+ f"{str(row.get('identity') or row.get('account') or '-'):<34.34} "
170
+ f"{str(row.get('auth_status') or '-'):<14} "
171
+ f"{scopes:<9} "
172
+ f"{_expiry_cell(row)}"
173
+ )
174
+ return "\n".join(lines)
175
+
176
+
177
+ def _expiry_cell(row: dict) -> str:
178
+ """The expiry column, which is the one most able to mislead.
179
+
180
+ ``access_token`` is a ~1h token the server refreshes on its own; printing it
181
+ as a deadline would show every healthy connector as expiring within the hour.
182
+ """
183
+ kind = row.get("expiry_kind")
184
+ if kind == "access_token":
185
+ return f"{row.get('expires_at') or '?'} (access token, auto-renewed)"
186
+ if kind == "credential":
187
+ return f"{row.get('expires_at') or '?'} (credential)"
188
+ return "(not recorded)"
189
+
190
+
191
+ def require_object(body: object, *, what: str, error: type[Exception]) -> dict:
192
+ """The decoded body as a dict, or ``error`` explaining what came back instead.
193
+
194
+ Shared rather than re-written per command: several modules had grown
195
+ their own version of this, and the reason that matters is not tidiness.
196
+ Each copy decided on its own what "malformed" meant, so the same broken
197
+ response produced a different message depending on which subcommand you
198
+ happened to run.
199
+
200
+ ``what`` names the endpoint in the operator's words; ``error`` is the command's
201
+ own exception type, so a caller still catches what it always caught.
202
+ """
203
+ if not isinstance(body, dict):
204
+ raise error(
205
+ f"expected a JSON object from {what}, got "
206
+ f"{type(body).__name__}: {str(body)[:200]}"
207
+ )
208
+ return body
209
+
210
+
211
+ def default_fetch(target: Target, path: str, **kwargs: Any) -> Any:
212
+ """The plain ``api.get`` a ``fetch=`` parameter falls back to when a caller
213
+ does not inject one.
214
+
215
+ Imported lazily so a module that only needs this as a *default* stays
216
+ importable (and unit-testable with a fake fetcher) without pulling in the
217
+ HTTP layer.
218
+ """
219
+ from formist_cli import api
220
+
221
+ return api.get(target, path, **kwargs)
@@ -0,0 +1,358 @@
1
+ """``fm connectors`` - what a space's connectors are authorized to do.
2
+
3
+ The space-side half of the access panel, over ``GET /admin/spaces/{id}/connectors/
4
+ grants``. ``fm users grants <id>`` is the person-side half; both read the same
5
+ view and share one renderer in :mod:`formist_cli.cli_support`, so the two
6
+ commands cannot come to disagree about what a column means.
7
+
8
+ Two shapes of a familiar defect live here specifically: a report that is
9
+ true about what it fetched and false about what exists.
10
+
11
+ An empty scope column: several connector types record no scopes at all,
12
+ since an API-key connector has no scope concept. Printing an empty cell
13
+ for both "records none" and "granted none" would say a Fireflies key may
14
+ do nothing, when in fact it may do everything that API allows. The shared
15
+ renderer prints ``-`` for the first and a count for the second.
16
+
17
+ An expiry that is always about to lapse: ``expires_at`` on a Google or
18
+ Airtable connector is the roughly one-hour access token, which the server
19
+ refreshes silently. Rendered as a deadline it would show every healthy
20
+ connector as expiring within the hour, permanently. It is labelled, never
21
+ bare.
22
+
23
+ This is the space's own connectors only. A member's personal
24
+ (user-scoped) connector belongs to the person and has no ``project_id``;
25
+ it is reported by ``fm users grants``. An empty table here therefore does
26
+ not mean nobody in the space has connected anything.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import json
33
+ import sys
34
+ import time
35
+
36
+ from formist_cli import api, context
37
+ from formist_cli.cli_support import as_dict as _shared_as_dict
38
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
39
+ from formist_cli.cli_support import render_grant_rows
40
+
41
+ SUBJECTS = ("list", "grants")
42
+ DEFAULT_SUBJECT = "list"
43
+
44
+
45
+ class ConnectorsError(Exception):
46
+ """A refusal about the connector surface, written for an operator."""
47
+
48
+
49
+ #: The refusal an unknown subject gets. Prose, not a bare ValueError: the reader is
50
+ #: an operator at a terminal, and "unknown subcommand" without the valid list is a
51
+ #: dead end.
52
+ def subject_error(subject: object) -> ConnectorsError:
53
+ return ConnectorsError(
54
+ f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}.\n"
55
+ " list the space's connectors (id, kind, status), the default\n"
56
+ " grants every connector of a space: identity, scopes, status, expiry "
57
+ "(always needs --admin)"
58
+ )
59
+
60
+
61
+ # ===========================================================================
62
+ # Rendering
63
+ # ===========================================================================
64
+ def render_grants(payload: dict) -> str:
65
+ """One space's connectors, named so the reader knows which space they read.
66
+
67
+ The heading is not decoration: this command takes a UUID, and a table with no
68
+ space name on it is impossible to check against the space you meant.
69
+ """
70
+ space = payload.get("space") or {}
71
+ items = payload.get("items") or []
72
+ heading = (
73
+ f"{space.get('name') or '(unnamed space)'} "
74
+ f"[{space.get('region') or '?'}] {space.get('id') or ''}"
75
+ ).strip()
76
+ return f"{heading}\n\n{render_grant_rows(items)}"
77
+
78
+
79
+ # ===========================================================================
80
+ # CLI - the parser lives in cli.py
81
+ # ===========================================================================
82
+ # Deliberately not an `add_parser` module like users.py. `fm connectors`
83
+ # already existed as an inline command, and registering a second parser
84
+ # under the same name raises a conflicting-subparser error at import. So
85
+ # this module supplies the subject vocabulary and the grants behaviour,
86
+ # and cli.py keeps owning the one `connectors` parser. One command, two
87
+ # subjects.
88
+
89
+ COMMAND_DESCRIPTION = """A space's connectors, and what they are authorized to do.
90
+
91
+ fm connectors [--space X] the connector list (id, kind, status); a
92
+ member of the space, no flag needed
93
+ fm connectors --admin [--space X] the same list, for a space you are not
94
+ a member of (platform administrators only)
95
+ fm connectors grants [<space-id>] identity, scopes, auth status, expiry;
96
+ always needs --admin
97
+
98
+ SPACE-OWNED CONNECTORS ONLY. A member's PERSONAL connector is user-scoped, has no
99
+ project, and is not listed here, use `fm users grants <user-id>` for those. An empty
100
+ table means the space owns no connectors, NOT that nobody has connected anything.
101
+
102
+ THE EXPIRY COLUMN IS LABELLED, AND THE LABEL IS THE POINT. `access token,
103
+ auto-renewed` is the roughly one-hour token the server refreshes on its own,
104
+ it is always minutes from expiring and that is normal, not a problem to chase.
105
+ `(not recorded)` means no expiry is stored for that credential, which is NOT
106
+ the same as "it never expires".
107
+
108
+ A `-` IN THE SCOPES COLUMN MEANS THE PROVIDER RECORDS NO SCOPES (an API-key
109
+ connector), not that the credential was granted nothing.
110
+
111
+ This command never writes. There is no flag that makes it write.
112
+ """
113
+
114
+
115
+ def run_grants(args, eff) -> int:
116
+ """`fm connectors grants`, the space's connector grants.
117
+
118
+ Takes the already-resolved context from cli.py rather than resolving
119
+ again: the resolver prints a provenance banner, and resolving twice
120
+ would print it twice and invite the reader to believe two different
121
+ targets were consulted.
122
+ """
123
+ space = getattr(eff, "space", None)
124
+ if not space:
125
+ raise ConnectorsError(
126
+ "`fm connectors grants` needs a space id.\n"
127
+ "-> pass it positionally, with --space, or set one with `fm use`."
128
+ )
129
+ payload = api.admin_get(
130
+ eff.target, f"/admin/spaces/{space}/connectors/grants", token=eff.token
131
+ )
132
+ if getattr(args, "json", False):
133
+ print(json.dumps(payload, indent=2))
134
+ else:
135
+ # The shared helper is called inline rather than wrapped in a local
136
+ # `_as_dict`, to avoid re-wrapping a helper that was already shared
137
+ # into cli_support once, which is how it would drift back apart.
138
+ print(
139
+ render_grants(
140
+ _shared_as_dict(
141
+ payload,
142
+ what="/admin/spaces/{id}/connectors/grants",
143
+ error=ConnectorsError,
144
+ )
145
+ )
146
+ )
147
+ return 0
148
+
149
+
150
+ # ===========================================================================
151
+ # ``fm connector`` (singular) - per-connector operator actions
152
+ # ===========================================================================
153
+ # A deliberately separate top-level command from ``fm connectors`` (plural)
154
+ # above. That one is the admin surface (Global-only, platform-admin-gated).
155
+ # These two hit ordinary project routes (member-gated, never ``/admin``),
156
+ # which is the same reason ``fm entity-fields`` is its own top-level
157
+ # command rather than a subject of ``fm connectors``. Folding a
158
+ # project-scoped write into the admin listing command would blur a
159
+ # distinction this codebase treats as load-bearing: the server is the
160
+ # trust boundary.
161
+ #
162
+ # `reauth` and `sync` each give the CLI a stable entry point onto an
163
+ # existing project route, replacing a one-off script with the same effect.
164
+ #
165
+ # Both subjects are writes with real external side effects (a live Microsoft
166
+ # OAuth flow; a real Graph/Attendee crawl) and follow `fm`'s write
167
+ # convention: dry run by default, ``--apply`` to actually do it.
168
+
169
+ CONNECTOR_SUBJECTS = ("reauth", "sync")
170
+
171
+ #: How often to poll `.../reauth/poll` while waiting for the operator to enter
172
+ #: the device code, and for how long before giving up. The server's own flow
173
+ #: response carries an `interval`/`expires_in` (Microsoft's own device-code
174
+ #: timing); these are only the CLI's fallback when the server sends neither.
175
+ DEFAULT_POLL_INTERVAL = 5
176
+ DEFAULT_POLL_TIMEOUT = 900
177
+
178
+
179
+ def _connector_subject_error(subject: object) -> ConnectorsError:
180
+ return ConnectorsError(
181
+ f"unknown subcommand {subject!r}. Valid: {', '.join(CONNECTOR_SUBJECTS)}.\n"
182
+ " reauth <cid> re-authorize an existing OUTLOOK connection (device-code, WRITE)\n"
183
+ " sync <cid> trigger a real sync for one connector NOW (WRITE)"
184
+ )
185
+
186
+
187
+ CONNECTOR_COMMAND_DESCRIPTION = """Per-connector operator actions (project-scoped WRITEs).
188
+
189
+ fm connector reauth <cid> --space <id> [--apply]
190
+ Re-authorize an existing OUTLOOK connection whose delegated token has
191
+ died (the same flow the product's "Reconnect" banner drives). Prints the
192
+ user_code + verification_uri, then polls until Microsoft answers.
193
+
194
+ fm connector sync <cid> --space <id> [--kind ...] [--apply]
195
+ Trigger a real sync for ONE connector now (the scheduler's per-connection
196
+ unit of work, on demand). --kind is accepted for your own bookkeeping;
197
+ the server dispatches by the connector's OWN type, so it is never sent.
198
+
199
+ Both are WRITEs with real external side effects. DRY RUN by default; --apply
200
+ performs the action.
201
+ """
202
+
203
+
204
+ def add_connector_parser(subparsers) -> argparse.ArgumentParser:
205
+ parser = subparsers.add_parser(
206
+ "connector",
207
+ help="per-connector operator actions: reauth, sync (both WRITE)",
208
+ description=CONNECTOR_COMMAND_DESCRIPTION,
209
+ formatter_class=argparse.RawDescriptionHelpFormatter,
210
+ )
211
+ _add_connector_arguments(parser)
212
+ return parser
213
+
214
+
215
+ def _add_connector_arguments(parser: argparse.ArgumentParser) -> None:
216
+ from formist_cli.cli import _add_env, _add_space
217
+
218
+ _add_env(parser, for_write=True)
219
+ _add_space(parser)
220
+ parser.add_argument("subject", help=f"one of: {', '.join(CONNECTOR_SUBJECTS)}")
221
+ parser.add_argument("arg", nargs="?", default=None, help="the connection/connector id (UUID)")
222
+ parser.add_argument(
223
+ "--provider", default="outlook",
224
+ help="reauth: informational only, today only OUTLOOK supports device-code reauth",
225
+ )
226
+ parser.add_argument(
227
+ "--kind", default=None, choices=("calendar", "messages", "sharepoint", "drive"),
228
+ help="sync: informational only, never sent to the server",
229
+ )
230
+ parser.add_argument("--apply", action="store_true", help="perform the action (default: dry run)")
231
+ parser.add_argument(
232
+ "--poll-interval", dest="poll_interval", type=int, default=DEFAULT_POLL_INTERVAL,
233
+ help="reauth: seconds between polls when the server sends none",
234
+ )
235
+ parser.add_argument(
236
+ "--poll-timeout", dest="poll_timeout", type=int, default=DEFAULT_POLL_TIMEOUT,
237
+ help="reauth: give up after this many seconds",
238
+ )
239
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a report")
240
+
241
+
242
+ def build_connector_standalone_parser() -> argparse.ArgumentParser:
243
+ return _build_standalone_parser(add_connector_parser)
244
+
245
+
246
+ def _require_connection_id(arg: str | None) -> str:
247
+ if not arg:
248
+ raise ConnectorsError(
249
+ "needs a connection id.\n-> fm connector reauth|sync <cid> --space <id>"
250
+ )
251
+ return arg
252
+
253
+
254
+ # ---------------------------------------------------------------------------
255
+ # reauth
256
+ # ---------------------------------------------------------------------------
257
+ def _run_reauth(ctx, args) -> int:
258
+ cid = _require_connection_id(args.arg)
259
+ if not args.apply:
260
+ print(
261
+ f"DRY RUN: nothing was changed.\n"
262
+ f"Would initiate a device-code re-authorization for connection {cid} "
263
+ f"in space {ctx.space} ({ctx.target.name}).\n"
264
+ f"To apply: re-run with --apply.",
265
+ file=sys.stderr,
266
+ )
267
+ return 0
268
+
269
+ initiated = api.post(
270
+ ctx.target, f"/projects/{ctx.space}/connections/{cid}/reauth", {}, token=ctx.token
271
+ )
272
+ if not isinstance(initiated, dict):
273
+ raise ConnectorsError(
274
+ f"expected a JSON object from .../reauth, got {type(initiated).__name__}."
275
+ )
276
+ flow = initiated.get("device_code_flow") or {}
277
+ print("=" * 60)
278
+ print(f"DEVICE CODE: authorize the connection at {ctx.space}")
279
+ print(f" URL : {flow.get('verification_uri')}")
280
+ print(f" CODE: {flow.get('user_code')}")
281
+ print(f" (expires in {flow.get('expires_in', DEFAULT_POLL_TIMEOUT)}s)")
282
+ print("=" * 60)
283
+
284
+ interval = flow.get("interval") or args.poll_interval
285
+ deadline = time.monotonic() + int(flow.get("expires_in") or args.poll_timeout)
286
+ poll_path = f"/projects/{ctx.space}/connections/{cid}/reauth/poll"
287
+ result: dict = {"status": "pending"}
288
+ first = True
289
+ while time.monotonic() < deadline:
290
+ if not first:
291
+ time.sleep(max(0, interval))
292
+ first = False
293
+ result = api.post(ctx.target, poll_path, {}, token=ctx.token)
294
+ if not isinstance(result, dict):
295
+ raise ConnectorsError(
296
+ f"expected a JSON object from .../reauth/poll, got {type(result).__name__}."
297
+ )
298
+ if result.get("status") != "pending":
299
+ break
300
+
301
+ if args.json:
302
+ print(json.dumps(result, indent=2, ensure_ascii=False))
303
+ else:
304
+ print(f"status={result.get('status')} auth_status={result.get('auth_status')}")
305
+ if result.get("status") not in ("connected",):
306
+ if result.get("error"):
307
+ print(f"FAILED: {result['error']}")
308
+ else:
309
+ print("did not complete (still pending, the operator ran out of time to authorize)")
310
+ return 2
311
+ return 0
312
+
313
+
314
+ # ---------------------------------------------------------------------------
315
+ # sync
316
+ # ---------------------------------------------------------------------------
317
+ def _run_sync(ctx, args) -> int:
318
+ cid = _require_connection_id(args.arg)
319
+ kind_note = f" (kind={args.kind})" if args.kind else ""
320
+ if not args.apply:
321
+ print(
322
+ f"DRY RUN: nothing was changed.\n"
323
+ f"Would trigger a sync now for connector {cid}{kind_note} "
324
+ f"in space {ctx.space} ({ctx.target.name}).\n"
325
+ f"To apply: re-run with --apply.",
326
+ file=sys.stderr,
327
+ )
328
+ return 0
329
+
330
+ # `--kind` is never sent: one endpoint dispatches by the connector's own
331
+ # type, so there is no server-side parameter to send it to; it exists
332
+ # purely so an operator can invoke this the way per-purpose scripts were
333
+ # once named.
334
+ result = api.post(ctx.target, f"/projects/{ctx.space}/connectors/{cid}/sync", {}, token=ctx.token)
335
+ if not isinstance(result, dict):
336
+ raise ConnectorsError(
337
+ f"expected a JSON object from .../connectors/{{cid}}/sync, got {type(result).__name__}."
338
+ )
339
+ if args.json:
340
+ print(json.dumps(result, indent=2, ensure_ascii=False))
341
+ else:
342
+ for key, value in result.items():
343
+ if isinstance(value, (str, int, float, bool)) or value is None:
344
+ print(f"{key:<20} {value}")
345
+ for key, value in result.items():
346
+ if isinstance(value, list):
347
+ print(f"{key:<20} {len(value)} item(s)")
348
+ return 0
349
+
350
+
351
+ def run_connector(args) -> int:
352
+ subject = (getattr(args, "subject", None) or "").strip().lower()
353
+ if subject not in CONNECTOR_SUBJECTS:
354
+ raise _connector_subject_error(getattr(args, "subject", None))
355
+ ctx = context.resolve(args, for_write=True, need_space=True, need_token=True)
356
+ if subject == "reauth":
357
+ return _run_reauth(ctx, args)
358
+ return _run_sync(ctx, args)