atli 0.5.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.
@@ -0,0 +1,1129 @@
1
+ """`atli conf ...` click commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import click
8
+
9
+ from atli.client import AtlassianAPIError
10
+ from atli.config import Config, ConfigError
11
+ from atli.confluence.client import ConfluenceClient
12
+ from atli.confluence.markdown import (
13
+ MarkdownError,
14
+ _picked_engine,
15
+ to_markdown_macro,
16
+ to_storage,
17
+ )
18
+ from atli.output import emit_json, emit_kv, emit_table, fail
19
+
20
+
21
+ def _client(ctx: click.Context) -> ConfluenceClient:
22
+ # Import here to avoid circular dependency
23
+ from atli.cli import _ensure_config
24
+ cfg = _ensure_config(ctx)
25
+ try:
26
+ cfg.require_confluence()
27
+ except ConfigError as e:
28
+ fail(str(e))
29
+ return ConfluenceClient(cfg.confluence_url, cfg.confluence_token)
30
+
31
+
32
+ def _page_url(base_url: str, page: dict) -> str:
33
+ web = page.get("_links", {}).get("webui") or page.get("_links", {}).get("tinyui") or ""
34
+ if web.startswith("http"):
35
+ return web
36
+ return f"{base_url.rstrip('/')}{web}" if web else ""
37
+
38
+
39
+ def _read_content(file: Path | None, content: str | None) -> str:
40
+ if file is not None:
41
+ return file.read_text(encoding="utf-8")
42
+ if content is not None:
43
+ return content
44
+ fail("provide --file or --content")
45
+ return "" # unreachable
46
+
47
+
48
+ def _convert_if_markdown(
49
+ body: str,
50
+ representation: str,
51
+ file_path: Path | None,
52
+ quiet: bool,
53
+ ) -> tuple[str, str]:
54
+ """Apply markdown→storage conversion when requested.
55
+
56
+ Returns ``(body, representation)`` to send. When the user passes
57
+ ``--format markdown``, this performs the conversion and returns
58
+ representation ``"storage"`` (the wire format). When they pass a
59
+ ``.md`` filename without ``--format markdown`` and representation is
60
+ the default ``"storage"``, emits a stderr warning but does not block.
61
+ """
62
+ import sys
63
+
64
+ if representation == "markdown-macro":
65
+ if not quiet:
66
+ print(
67
+ "info: wrapping markdown in 'markdown' macro "
68
+ "(server-side plugin renders)",
69
+ file=sys.stderr,
70
+ )
71
+ return to_markdown_macro(body), "storage"
72
+
73
+ if representation == "markdown":
74
+ engine = _picked_engine("auto")
75
+ if not quiet:
76
+ note = (
77
+ "via pandoc"
78
+ if engine == "pandoc"
79
+ else "via markdown-it-py (pandoc not on PATH)"
80
+ )
81
+ print(f"info: converting markdown {note}", file=sys.stderr)
82
+ try:
83
+ return to_storage(body, engine="auto"), "storage"
84
+ except MarkdownError as e:
85
+ fail(str(e))
86
+ return "", "storage" # unreachable
87
+
88
+ if (
89
+ file_path is not None
90
+ and file_path.suffix == ".md"
91
+ and representation == "storage"
92
+ ):
93
+ print(
94
+ f"warn: {file_path.name} looks like markdown but --format is "
95
+ f"'storage'. Pass --format markdown to convert, or rename the "
96
+ f"file to suppress this warning.",
97
+ file=sys.stderr,
98
+ )
99
+ return body, representation
100
+
101
+
102
+ @click.group()
103
+ def conf() -> None:
104
+ """Manage Confluence pages."""
105
+
106
+
107
+ @conf.command("create")
108
+ @click.option("--space", required=True, help="Space key, e.g. TEAM")
109
+ @click.option("--title", required=True, help="Page title")
110
+ @click.option("--file", "file", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Read content from file")
111
+ @click.option("--content", default=None, help="Inline content (alternative to --file)")
112
+ @click.option("--parent-id", default=None, help="Parent page ID (optional)")
113
+ @click.option(
114
+ "--format",
115
+ "representation",
116
+ default="storage",
117
+ show_default=True,
118
+ type=click.Choice(["storage", "wiki", "markdown", "markdown-macro"]),
119
+ help="Body format Confluence will interpret",
120
+ )
121
+ @click.pass_context
122
+ def create(
123
+ ctx: click.Context,
124
+ space: str,
125
+ title: str,
126
+ file: Path | None,
127
+ content: str | None,
128
+ parent_id: str | None,
129
+ representation: str,
130
+ ) -> None:
131
+ """Create a new page."""
132
+ client = _client(ctx)
133
+ body = _read_content(file, content)
134
+ body, representation = _convert_if_markdown(
135
+ body, representation, file, ctx.obj.get("quiet", False)
136
+ )
137
+ try:
138
+ page = client.create_page(
139
+ space=space,
140
+ title=title,
141
+ content=body,
142
+ parent_id=parent_id,
143
+ representation=representation,
144
+ )
145
+ except AtlassianAPIError as e:
146
+ fail(str(e))
147
+
148
+ cfg: Config = ctx.obj["config"]
149
+ if ctx.obj["json"]:
150
+ emit_json(page)
151
+ return
152
+ emit_kv(
153
+ [
154
+ ("Page", page.get("id", "")),
155
+ ("Title", title),
156
+ ("Space", space),
157
+ ("URL", _page_url(cfg.confluence_url, page)),
158
+ ],
159
+ json_mode=False,
160
+ )
161
+
162
+
163
+ @conf.command("view")
164
+ @click.option("--space", required=True, help="Space key")
165
+ @click.option("--title", required=True, help="Page title")
166
+ @click.option("--body", "show_body", is_flag=True, help="Print page body content")
167
+ @click.pass_context
168
+ def view(ctx: click.Context, space: str, title: str, show_body: bool) -> None:
169
+ """Show a page by space + title."""
170
+ client = _client(ctx)
171
+ try:
172
+ page = client.require_page(space, title)
173
+ except AtlassianAPIError as e:
174
+ fail(str(e))
175
+
176
+ cfg: Config = ctx.obj["config"]
177
+ if ctx.obj["json"]:
178
+ emit_json(page)
179
+ return
180
+
181
+ rows = [
182
+ ("Page", page.get("id", "")),
183
+ ("Title", page.get("title", "")),
184
+ ("Space", page.get("space", {}).get("key", space)),
185
+ ("Version", page.get("version", {}).get("number", "")),
186
+ ("URL", _page_url(cfg.confluence_url, page)),
187
+ ]
188
+ emit_kv(rows, json_mode=False)
189
+
190
+ if show_body:
191
+ storage = page.get("body", {}).get("storage", {}).get("value", "")
192
+ click.echo("")
193
+ click.echo(storage)
194
+
195
+
196
+ @conf.command("update")
197
+ @click.option("--space", required=True, help="Space key")
198
+ @click.option("--title", required=True, help="Page title")
199
+ @click.option("--file", "file", type=click.Path(exists=True, dir_okay=False, path_type=Path), help="Read new content from file")
200
+ @click.option("--content", default=None, help="Inline content (alternative to --file)")
201
+ @click.option(
202
+ "--format",
203
+ "representation",
204
+ default="storage",
205
+ show_default=True,
206
+ type=click.Choice(["storage", "wiki", "markdown", "markdown-macro"]),
207
+ help="Body format",
208
+ )
209
+ @click.option("--create-if-missing", is_flag=True, help="Create the page if it does not exist")
210
+ @click.pass_context
211
+ def update(
212
+ ctx: click.Context,
213
+ space: str,
214
+ title: str,
215
+ file: Path | None,
216
+ content: str | None,
217
+ representation: str,
218
+ create_if_missing: bool,
219
+ ) -> None:
220
+ """Update an existing page (or create it with --create-if-missing)."""
221
+ client = _client(ctx)
222
+ body = _read_content(file, content)
223
+ body, representation = _convert_if_markdown(
224
+ body, representation, file, ctx.obj.get("quiet", False)
225
+ )
226
+ try:
227
+ if create_if_missing:
228
+ action, page = client.upsert_page(space, title, body, representation=representation)
229
+ else:
230
+ existing = client.require_page(space, title)
231
+ page = client.update_page(
232
+ page_id=existing["id"],
233
+ title=title,
234
+ content=body,
235
+ version=existing.get("version", {}).get("number", 1),
236
+ representation=representation,
237
+ )
238
+ action = "updated"
239
+ except AtlassianAPIError as e:
240
+ fail(str(e))
241
+
242
+ cfg: Config = ctx.obj["config"]
243
+ if ctx.obj["json"]:
244
+ emit_json({"action": action, "page": page})
245
+ return
246
+ emit_kv(
247
+ [
248
+ ("Page", page.get("id", "")),
249
+ ("Title", title),
250
+ ("Space", space),
251
+ ("Action", action),
252
+ ("URL", _page_url(cfg.confluence_url, page)),
253
+ ],
254
+ json_mode=False,
255
+ )
256
+
257
+
258
+ @conf.command("list")
259
+ @click.option("--space", required=True, help="Space key")
260
+ @click.option("--limit", default=25, show_default=True, help="Max pages")
261
+ @click.pass_context
262
+ def list_cmd(ctx: click.Context, space: str, limit: int) -> None:
263
+ """List pages in a space."""
264
+ client = _client(ctx)
265
+ try:
266
+ result = client.list_pages(space, limit=limit)
267
+ except AtlassianAPIError as e:
268
+ fail(str(e))
269
+
270
+ pages = result.get("results", [])
271
+ if ctx.obj["json"]:
272
+ emit_json(result)
273
+ return
274
+ rows = [[p.get("id", ""), p.get("title", "")] for p in pages]
275
+ emit_table(["ID", "Title"], rows, json_mode=False)
276
+
277
+
278
+ @conf.command("search")
279
+ @click.argument("query", required=False, default=None)
280
+ @click.option("--cql", is_flag=True, help="Treat query as raw CQL")
281
+ @click.option("--space", default=None, help="Filter by space key")
282
+ @click.option("--title", "title_match", default=None, help="Filter by title substring")
283
+ @click.option("--label", default=None, help="Filter by label")
284
+ @click.option("--text", "text_match", default=None, help="Filter by text content")
285
+ @click.option("--limit", default=10, show_default=True, help="Max results")
286
+ @click.pass_context
287
+ def search(
288
+ ctx: click.Context,
289
+ query: str | None,
290
+ cql: bool,
291
+ space: str | None,
292
+ title_match: str | None,
293
+ label: str | None,
294
+ text_match: str | None,
295
+ limit: int,
296
+ ) -> None:
297
+ """Search pages with filters or raw CQL.
298
+
299
+ Pass QUERY as raw CQL with --cql, or use convenience filters like --space, --label, --text.
300
+ If no filters are given and no QUERY, searches all pages.
301
+ """
302
+ client = _client(ctx)
303
+ if cql and query:
304
+ cql_query = query
305
+ elif space or title_match or label or text_match:
306
+ # Merge QUERY into text_match if provided
307
+ final_text = text_match
308
+ if query and not text_match:
309
+ final_text = query
310
+ elif query and text_match:
311
+ fail("Cannot specify both QUERY and --text; use one or the other")
312
+ try:
313
+ result = client.search_pages(
314
+ space=space, title=title_match, label=label, text=final_text, limit=limit
315
+ )
316
+ except AtlassianAPIError as e:
317
+ fail(str(e))
318
+ if ctx.obj["json"]:
319
+ emit_json(result)
320
+ return
321
+ rows = [
322
+ [p.get("id", ""), p.get("space", {}).get("key", ""), p.get("title", "")]
323
+ for p in result.get("results", [])
324
+ ]
325
+ emit_table(["ID", "Space", "Title"], rows, json_mode=False)
326
+ return
327
+ elif query:
328
+ # Escape query for safe CQL text search
329
+ escaped_query = query.replace("\\", "\\\\").replace('"', '\\"')
330
+ cql_query = f'type = page AND text ~ "{escaped_query}"'
331
+ else:
332
+ cql_query = "type = page"
333
+
334
+ try:
335
+ result = client.search(cql_query, limit=limit)
336
+ except AtlassianAPIError as e:
337
+ fail(str(e))
338
+
339
+ if ctx.obj["json"]:
340
+ emit_json(result)
341
+ return
342
+ rows = [
343
+ [p.get("id", ""), p.get("space", {}).get("key", ""), p.get("title", "")]
344
+ for p in result.get("results", [])
345
+ ]
346
+ emit_table(["ID", "Space", "Title"], rows, json_mode=False)
347
+
348
+
349
+ @conf.command("attach")
350
+ @click.option("--space", required=True, help="Space key")
351
+ @click.option("--title", required=True, help="Page title")
352
+ @click.option("--file", "file_path", type=click.Path(exists=True, dir_okay=False, path_type=Path), required=True, help="File to upload")
353
+ @click.pass_context
354
+ def attach(ctx: click.Context, space: str, title: str, file_path: Path) -> None:
355
+ """Upload a file attachment to a Confluence page."""
356
+ client = _client(ctx)
357
+ try:
358
+ page = client.require_page(space, title, expand="version")
359
+ except AtlassianAPIError as e:
360
+ fail(str(e))
361
+
362
+ page_id = page["id"]
363
+ try:
364
+ result = client.upload_attachment(page_id, str(file_path))
365
+ except AtlassianAPIError as e:
366
+ fail(str(e))
367
+
368
+ attachments = result.get("results", [])
369
+ if not attachments:
370
+ fail("upload succeeded but no attachment returned")
371
+
372
+ att = attachments[0]
373
+ cfg: Config = ctx.obj["config"]
374
+ if ctx.obj["json"]:
375
+ emit_json(att)
376
+ return
377
+ emit_kv(
378
+ [
379
+ ("Attachment", att.get("id", "")),
380
+ ("Title", att.get("title", "")),
381
+ ("Page", page_id),
382
+ ("Space", space),
383
+ ],
384
+ json_mode=False,
385
+ )
386
+
387
+
388
+ @conf.command("delete")
389
+ @click.option("--id", "page_id", default=None, help="Page ID (mutually exclusive with --space/--title)")
390
+ @click.option("--space", default=None, help="Space key (use with --title)")
391
+ @click.option("--title", default=None, help="Page title (use with --space)")
392
+ @click.option("--yes", is_flag=True, help="Skip the confirmation prompt")
393
+ @click.pass_context
394
+ def delete(ctx: click.Context, page_id: str | None, space: str | None, title: str | None, yes: bool) -> None:
395
+ """Delete (move to trash) a Confluence page."""
396
+ has_id = page_id is not None
397
+ has_space_title = space is not None and title is not None
398
+ if has_id == has_space_title:
399
+ fail("provide either --id or --space + --title")
400
+
401
+ client = _client(ctx)
402
+
403
+ if has_id:
404
+ try:
405
+ page = client.get_page(page_id)
406
+ except AtlassianAPIError as e:
407
+ fail(str(e))
408
+ else:
409
+ try:
410
+ page = client.require_page(space, title)
411
+ except AtlassianAPIError as e:
412
+ fail(str(e))
413
+
414
+ resolved_id = page["id"]
415
+ resolved_title = page.get("title", "")
416
+
417
+ if not yes:
418
+ if ctx.obj["json"]:
419
+ fail("--yes is required when --json is set (no stdin prompt)")
420
+ click.echo(f"Page {resolved_id}")
421
+ click.echo(f"Title {resolved_title}")
422
+ if not click.confirm("Continue with delete?", default=False):
423
+ fail("aborted")
424
+
425
+ try:
426
+ client.delete_page(resolved_id)
427
+ except AtlassianAPIError as e:
428
+ fail(str(e))
429
+
430
+ if ctx.obj["json"]:
431
+ emit_json({"id": resolved_id, "deleted": True})
432
+ return
433
+ emit_kv(
434
+ [("Page", resolved_id), ("Title", resolved_title), ("Action", "deleted")],
435
+ json_mode=False,
436
+ )
437
+
438
+
439
+ # ----------------------------- label commands -----------------------------
440
+
441
+
442
+ def _resolve_page_id(client: ConfluenceClient, space: str | None, title: str | None, page_id: str | None) -> str:
443
+ """Resolve page id from either --id or --space+--title."""
444
+ if page_id:
445
+ return page_id
446
+ if space and title:
447
+ try:
448
+ page = client.require_page(space, title, expand="version")
449
+ except Exception as e:
450
+ fail(str(e))
451
+ return page["id"]
452
+ fail("provide --id or both --space and --title")
453
+ return "" # unreachable
454
+
455
+
456
+ @conf.group("label")
457
+ def label() -> None:
458
+ """Manage page labels."""
459
+
460
+
461
+ @label.command("list")
462
+ @click.option("--space", default=None, help="Space key")
463
+ @click.option("--title", default=None, help="Page title")
464
+ @click.option("--id", "page_id", default=None, help="Page ID")
465
+ @click.pass_context
466
+ def label_list(ctx: click.Context, space: str | None, title: str | None, page_id: str | None) -> None:
467
+ """List labels on a page."""
468
+ client = _client(ctx)
469
+ resolved_id = _resolve_page_id(client, space, title, page_id)
470
+ try:
471
+ result = client.list_labels(resolved_id)
472
+ except AtlassianAPIError as e:
473
+ fail(str(e))
474
+ if ctx.obj["json"]:
475
+ emit_json(result)
476
+ return
477
+ labels = result.get("results", [])
478
+ rows = [[lbl.get("name", ""), lbl.get("prefix", "")] for lbl in labels]
479
+ emit_table(["Label", "Prefix"], rows, json_mode=False)
480
+
481
+
482
+ @label.command("add")
483
+ @click.argument("labels", nargs=-1, required=True)
484
+ @click.option("--space", default=None, help="Space key")
485
+ @click.option("--title", default=None, help="Page title")
486
+ @click.option("--id", "page_id", default=None, help="Page ID")
487
+ @click.pass_context
488
+ def label_add(
489
+ ctx: click.Context,
490
+ labels: tuple[str, ...],
491
+ space: str | None,
492
+ title: str | None,
493
+ page_id: str | None,
494
+ ) -> None:
495
+ """Add one or more labels to a page.
496
+
497
+ Example: atli conf label add --space TEAM --title "My Page" reviewed v2.0
498
+ """
499
+ client = _client(ctx)
500
+ resolved_id = _resolve_page_id(client, space, title, page_id)
501
+ try:
502
+ result = client.add_labels(resolved_id, list(labels))
503
+ except AtlassianAPIError as e:
504
+ fail(str(e))
505
+ if ctx.obj["json"]:
506
+ emit_json(result)
507
+ return
508
+ emit_kv(
509
+ [("Page", resolved_id), ("Labels added", ", ".join(labels))],
510
+ json_mode=False,
511
+ )
512
+
513
+
514
+ @label.command("delete")
515
+ @click.argument("label_name")
516
+ @click.option("--space", default=None, help="Space key")
517
+ @click.option("--title", default=None, help="Page title")
518
+ @click.option("--id", "page_id", default=None, help="Page ID")
519
+ @click.pass_context
520
+ def label_delete(
521
+ ctx: click.Context,
522
+ label_name: str,
523
+ space: str | None,
524
+ title: str | None,
525
+ page_id: str | None,
526
+ ) -> None:
527
+ """Remove a label from a page."""
528
+ client = _client(ctx)
529
+ resolved_id = _resolve_page_id(client, space, title, page_id)
530
+ try:
531
+ client.remove_label(resolved_id, label_name)
532
+ except AtlassianAPIError as e:
533
+ fail(str(e))
534
+ if ctx.obj["json"]:
535
+ emit_json({"page_id": resolved_id, "label": label_name, "deleted": True})
536
+ return
537
+ emit_kv(
538
+ [("Page", resolved_id), ("Label", label_name), ("Deleted", "yes")],
539
+ json_mode=False,
540
+ )
541
+
542
+
543
+ # ----------------------------- attachment download ---------------------------
544
+
545
+
546
+ @conf.group("attachment")
547
+ def attachment() -> None:
548
+ """Manage page attachments."""
549
+
550
+
551
+ @attachment.command("list")
552
+ @click.option("--space", default=None, help="Space key")
553
+ @click.option("--title", default=None, help="Page title")
554
+ @click.option("--id", "page_id", default=None, help="Page ID")
555
+ @click.option("--limit", default=50, show_default=True, help="Max attachments")
556
+ @click.pass_context
557
+ def attachment_list(
558
+ ctx: click.Context,
559
+ space: str | None,
560
+ title: str | None,
561
+ page_id: str | None,
562
+ limit: int,
563
+ ) -> None:
564
+ """List attachments on a page."""
565
+ client = _client(ctx)
566
+ resolved_id = _resolve_page_id(client, space, title, page_id)
567
+ try:
568
+ result = client.list_attachments(resolved_id, limit=limit)
569
+ except AtlassianAPIError as e:
570
+ fail(str(e))
571
+ if ctx.obj["json"]:
572
+ emit_json(result)
573
+ return
574
+ atts = result.get("results", [])
575
+ rows = [
576
+ [
577
+ a.get("id", ""),
578
+ a.get("title", ""),
579
+ str(a.get("extensions", {}).get("fileSize", "")),
580
+ a.get("extensions", {}).get("mediaType", ""),
581
+ ]
582
+ for a in atts
583
+ ]
584
+ emit_table(["ID", "Filename", "Size (bytes)", "Media type"], rows, json_mode=False)
585
+
586
+
587
+ @attachment.command("download")
588
+ @click.argument("attachment_id")
589
+ @click.option("--output", "-o", default=None, help="Output file path (default: filename from API)")
590
+ @click.pass_context
591
+ def attachment_download(ctx: click.Context, attachment_id: str, output: str | None) -> None:
592
+ """Download an attachment by its content ID.
593
+
594
+ Use `atli conf attachment list` to find attachment IDs.
595
+ """
596
+ client = _client(ctx)
597
+ # Fetch metadata to get filename
598
+ try:
599
+ meta = client.get_page(attachment_id, expand="")
600
+ except AtlassianAPIError:
601
+ meta = {}
602
+ filename = meta.get("title") or attachment_id
603
+ dest = output or filename
604
+
605
+ try:
606
+ data = client.download_attachment(attachment_id)
607
+ except AtlassianAPIError as e:
608
+ fail(str(e))
609
+
610
+ Path(dest).write_bytes(data)
611
+ if ctx.obj["json"]:
612
+ emit_json({"attachment_id": attachment_id, "saved_to": dest, "size": len(data)})
613
+ return
614
+ emit_kv(
615
+ [("Attachment", attachment_id), ("Saved to", dest), ("Size", f"{len(data)} bytes")],
616
+ json_mode=False,
617
+ )
618
+
619
+
620
+ # ----------------------------- property commands -----------------------------
621
+
622
+
623
+ @conf.group("property")
624
+ def property_group() -> None:
625
+ """Manage content properties (structured metadata) on pages."""
626
+
627
+
628
+ @property_group.command("list")
629
+ @click.option("--space", default=None, help="Space key")
630
+ @click.option("--title", default=None, help="Page title")
631
+ @click.option("--id", "page_id", default=None, help="Page ID")
632
+ @click.pass_context
633
+ def property_list(
634
+ ctx: click.Context,
635
+ space: str | None,
636
+ title: str | None,
637
+ page_id: str | None,
638
+ ) -> None:
639
+ """List all content properties on a page."""
640
+ client = _client(ctx)
641
+ resolved_id = _resolve_page_id(client, space, title, page_id)
642
+ try:
643
+ result = client.list_properties(resolved_id)
644
+ except AtlassianAPIError as e:
645
+ fail(str(e))
646
+ if ctx.obj["json"]:
647
+ emit_json(result)
648
+ return
649
+ props = result.get("results", [])
650
+ rows = [[p.get("key", ""), str(p.get("value", ""))] for p in props]
651
+ emit_table(["Key", "Value"], rows, json_mode=False)
652
+
653
+
654
+ @property_group.command("get")
655
+ @click.argument("key")
656
+ @click.option("--space", default=None, help="Space key")
657
+ @click.option("--title", default=None, help="Page title")
658
+ @click.option("--id", "page_id", default=None, help="Page ID")
659
+ @click.pass_context
660
+ def property_get(
661
+ ctx: click.Context,
662
+ key: str,
663
+ space: str | None,
664
+ title: str | None,
665
+ page_id: str | None,
666
+ ) -> None:
667
+ """Get a single content property by key."""
668
+ client = _client(ctx)
669
+ resolved_id = _resolve_page_id(client, space, title, page_id)
670
+ try:
671
+ result = client.get_property(resolved_id, key)
672
+ except AtlassianAPIError as e:
673
+ fail(str(e))
674
+ if ctx.obj["json"]:
675
+ emit_json(result)
676
+ return
677
+ emit_kv(
678
+ [("Page", resolved_id), ("Key", key), ("Value", str(result.get("value", "")))],
679
+ json_mode=False,
680
+ )
681
+
682
+
683
+ @property_group.command("set")
684
+ @click.argument("key")
685
+ @click.argument("value")
686
+ @click.option("--space", default=None, help="Space key")
687
+ @click.option("--title", default=None, help="Page title")
688
+ @click.option("--id", "page_id", default=None, help="Page ID")
689
+ @click.pass_context
690
+ def property_set(
691
+ ctx: click.Context,
692
+ key: str,
693
+ value: str,
694
+ space: str | None,
695
+ title: str | None,
696
+ page_id: str | None,
697
+ ) -> None:
698
+ """Set (create or update) a content property.
699
+
700
+ VALUE is interpreted as JSON when it looks like JSON, otherwise stored as a string.
701
+
702
+ Example: atli conf property set approval.status approved --id 12345
703
+ """
704
+ import json as _json
705
+
706
+ try:
707
+ parsed_value = _json.loads(value)
708
+ except ValueError:
709
+ parsed_value = value
710
+
711
+ client = _client(ctx)
712
+ resolved_id = _resolve_page_id(client, space, title, page_id)
713
+ try:
714
+ result = client.set_property(resolved_id, key, parsed_value)
715
+ except AtlassianAPIError as e:
716
+ fail(str(e))
717
+ if ctx.obj["json"]:
718
+ emit_json(result)
719
+ return
720
+ emit_kv(
721
+ [("Page", resolved_id), ("Key", key), ("Value", str(parsed_value)), ("Action", "set")],
722
+ json_mode=False,
723
+ )
724
+
725
+
726
+ @property_group.command("delete")
727
+ @click.argument("key")
728
+ @click.option("--space", default=None, help="Space key")
729
+ @click.option("--title", default=None, help="Page title")
730
+ @click.option("--id", "page_id", default=None, help="Page ID")
731
+ @click.pass_context
732
+ def property_delete(
733
+ ctx: click.Context,
734
+ key: str,
735
+ space: str | None,
736
+ title: str | None,
737
+ page_id: str | None,
738
+ ) -> None:
739
+ """Delete a content property."""
740
+ client = _client(ctx)
741
+ resolved_id = _resolve_page_id(client, space, title, page_id)
742
+ try:
743
+ client.delete_property(resolved_id, key)
744
+ except AtlassianAPIError as e:
745
+ fail(str(e))
746
+ if ctx.obj["json"]:
747
+ emit_json({"page_id": resolved_id, "key": key, "deleted": True})
748
+ return
749
+ emit_kv(
750
+ [("Page", resolved_id), ("Key", key), ("Deleted", "yes")],
751
+ json_mode=False,
752
+ )
753
+
754
+
755
+ # ----------------------------- space commands -----------------------------
756
+
757
+
758
+ @conf.group("space")
759
+ def space_group() -> None:
760
+ """Manage Confluence spaces."""
761
+
762
+
763
+ @space_group.command("list")
764
+ @click.option("--limit", default=100, show_default=True, help="Max spaces")
765
+ @click.option("--type", "space_type", default=None, type=click.Choice(["global", "personal"]), help="Filter by type")
766
+ @click.pass_context
767
+ def space_list(ctx: click.Context, limit: int, space_type: str | None) -> None:
768
+ """List accessible spaces."""
769
+ client = _client(ctx)
770
+ try:
771
+ result = client.list_spaces(limit=limit, typ=space_type)
772
+ except AtlassianAPIError as e:
773
+ fail(str(e))
774
+ if ctx.obj["json"]:
775
+ emit_json(result)
776
+ return
777
+ spaces = result.get("results", [])
778
+ rows = [
779
+ [s.get("key", ""), s.get("name", ""), s.get("type", "")]
780
+ for s in spaces
781
+ ]
782
+ emit_table(["Key", "Name", "Type"], rows, json_mode=False)
783
+
784
+
785
+ @space_group.command("view")
786
+ @click.argument("space_key")
787
+ @click.pass_context
788
+ def space_view(ctx: click.Context, space_key: str) -> None:
789
+ """Show details of a space."""
790
+ client = _client(ctx)
791
+ try:
792
+ result = client.get_space(space_key)
793
+ except AtlassianAPIError as e:
794
+ fail(str(e))
795
+ if ctx.obj["json"]:
796
+ emit_json(result)
797
+ return
798
+ emit_kv(
799
+ [
800
+ ("Key", result.get("key", "")),
801
+ ("Name", result.get("name", "")),
802
+ ("Type", result.get("type", "")),
803
+ ("Status", result.get("status", "")),
804
+ ],
805
+ json_mode=False,
806
+ )
807
+
808
+
809
+ @space_group.command("create")
810
+ @click.option("--key", "space_key", required=True, help="Short space key (e.g. TEAM)")
811
+ @click.option("--name", required=True, help="Human-readable space name")
812
+ @click.option("--description", default=None, help="Space description")
813
+ @click.pass_context
814
+ def space_create(ctx: click.Context, space_key: str, name: str, description: str | None) -> None:
815
+ """Create a new space."""
816
+ client = _client(ctx)
817
+ try:
818
+ result = client.create_space(space_key, name, description)
819
+ except AtlassianAPIError as e:
820
+ fail(str(e))
821
+ if ctx.obj["json"]:
822
+ emit_json(result)
823
+ return
824
+ emit_kv(
825
+ [("Key", result.get("key", space_key)), ("Name", name), ("Action", "created")],
826
+ json_mode=False,
827
+ )
828
+
829
+
830
+ @space_group.command("update")
831
+ @click.argument("space_key")
832
+ @click.option("--name", default=None, help="New space name")
833
+ @click.option("--description", default=None, help="New description")
834
+ @click.pass_context
835
+ def space_update(ctx: click.Context, space_key: str, name: str | None, description: str | None) -> None:
836
+ """Update a space's name or description."""
837
+ client = _client(ctx)
838
+ try:
839
+ result = client.update_space(space_key, name=name, description=description)
840
+ except AtlassianAPIError as e:
841
+ fail(str(e))
842
+ if ctx.obj["json"]:
843
+ emit_json(result)
844
+ return
845
+ emit_kv(
846
+ [("Key", space_key), ("Action", "updated")],
847
+ json_mode=False,
848
+ )
849
+
850
+
851
+ @space_group.command("delete")
852
+ @click.argument("space_key")
853
+ @click.option("--yes", is_flag=True, help="Skip confirmation (required: deletes all content)")
854
+ @click.pass_context
855
+ def space_delete(ctx: click.Context, space_key: str, yes: bool) -> None:
856
+ """Delete a space and ALL its content (irreversible)."""
857
+ if not yes:
858
+ if ctx.obj["json"]:
859
+ fail("--yes is required when --json is set")
860
+ click.echo(f"WARNING: This will permanently delete space '{space_key}' and all its content.")
861
+ if not click.confirm("Continue?", default=False):
862
+ fail("aborted")
863
+ client = _client(ctx)
864
+ try:
865
+ client.delete_space(space_key)
866
+ except AtlassianAPIError as e:
867
+ fail(str(e))
868
+ if ctx.obj["json"]:
869
+ emit_json({"key": space_key, "deleted": True})
870
+ return
871
+ emit_kv([("Space", space_key), ("Deleted", "yes")], json_mode=False)
872
+
873
+
874
+ # ----------------------------- page hierarchy commands -----------------------
875
+
876
+
877
+ @conf.command("children")
878
+ @click.option("--space", default=None, help="Space key")
879
+ @click.option("--title", default=None, help="Page title")
880
+ @click.option("--id", "page_id", default=None, help="Page ID")
881
+ @click.option("--limit", default=100, show_default=True, help="Max children")
882
+ @click.pass_context
883
+ def children(
884
+ ctx: click.Context,
885
+ space: str | None,
886
+ title: str | None,
887
+ page_id: str | None,
888
+ limit: int,
889
+ ) -> None:
890
+ """List direct child pages of a page."""
891
+ client = _client(ctx)
892
+ resolved_id = _resolve_page_id(client, space, title, page_id)
893
+ try:
894
+ result = client.get_child_pages(resolved_id, limit=limit)
895
+ except AtlassianAPIError as e:
896
+ fail(str(e))
897
+ if ctx.obj["json"]:
898
+ emit_json(result)
899
+ return
900
+ pages = result.get("results", [])
901
+ rows = [[p.get("id", ""), p.get("title", "")] for p in pages]
902
+ emit_table(["ID", "Title"], rows, json_mode=False)
903
+
904
+
905
+ @conf.command("move")
906
+ @click.option("--id", "page_id", required=True, help="Page ID to move")
907
+ @click.option("--parent", "new_parent_id", required=True, help="New parent page ID")
908
+ @click.pass_context
909
+ def move(ctx: click.Context, page_id: str, new_parent_id: str) -> None:
910
+ """Move a page by changing its parent.
911
+
912
+ The page will become a child of the new parent. Use `atli conf children`
913
+ to find page IDs.
914
+ """
915
+ client = _client(ctx)
916
+ try:
917
+ result = client.move_page(page_id, new_parent_id)
918
+ except AtlassianAPIError as e:
919
+ fail(str(e))
920
+ if ctx.obj["json"]:
921
+ emit_json(result)
922
+ return
923
+ emit_kv(
924
+ [
925
+ ("Page", page_id),
926
+ ("Title", result.get("title", "")),
927
+ ("New parent", new_parent_id),
928
+ ("Action", "moved"),
929
+ ],
930
+ json_mode=False,
931
+ )
932
+
933
+
934
+ # ----------------------------- version commands -----------------------------
935
+
936
+
937
+ @conf.group("version")
938
+ def version_group() -> None:
939
+ """Manage page version history."""
940
+
941
+
942
+ @version_group.command("list")
943
+ @click.option("--id", "page_id", required=True, help="Page ID")
944
+ @click.option("--limit", default=25, help="Max versions to show")
945
+ @click.pass_context
946
+ def version_list(ctx: click.Context, page_id: str, limit: int) -> None:
947
+ """List version history for a page."""
948
+ client = _client(ctx)
949
+ try:
950
+ result = client.get_page_versions(page_id, limit=limit)
951
+ except AtlassianAPIError as e:
952
+ fail(str(e))
953
+
954
+ if ctx.obj["json"]:
955
+ emit_json(result)
956
+ return
957
+
958
+ versions = result.get("results", [])
959
+ rows = [
960
+ [
961
+ str(v.get("number", "")),
962
+ v.get("when", "")[:19],
963
+ (v.get("by") or {}).get("displayName", ""),
964
+ v.get("message", "")[:50],
965
+ ]
966
+ for v in versions
967
+ ]
968
+ emit_table(["Version", "When", "By", "Message (truncated)"], rows, json_mode=False)
969
+ click.echo(f"\nTotal: {len(versions)} version(s)")
970
+
971
+
972
+ @version_group.command("view")
973
+ @click.option("--id", "page_id", required=True, help="Page ID")
974
+ @click.option("--version", "version_number", required=True, type=int, help="Version number")
975
+ @click.pass_context
976
+ def version_view(ctx: click.Context, page_id: str, version_number: int) -> None:
977
+ """View a specific version of a page."""
978
+ client = _client(ctx)
979
+ try:
980
+ version = client.get_page_version(page_id, version_number)
981
+ except AtlassianAPIError as e:
982
+ fail(str(e))
983
+
984
+ if ctx.obj["json"]:
985
+ emit_json(version)
986
+ return
987
+
988
+ emit_kv([
989
+ ("Page ID", page_id),
990
+ ("Version", str(version.get("number", ""))),
991
+ ("When", version.get("when", "")),
992
+ ("By", (version.get("by") or {}).get("displayName", "")),
993
+ ("Message", version.get("message", "")),
994
+ ], json_mode=False)
995
+
996
+ # Show content if available
997
+ content = version.get("content", {}).get("storage", {}).get("value")
998
+ if content:
999
+ click.echo("\n--- Content (storage format) ---")
1000
+ click.echo(content[:500])
1001
+ if len(content) > 500:
1002
+ click.echo("... (truncated)")
1003
+
1004
+
1005
+ @version_group.command("restore")
1006
+ @click.option("--id", "page_id", required=True, help="Page ID")
1007
+ @click.option("--version", "version_number", required=True, type=int, help="Version to restore")
1008
+ @click.option("--yes", is_flag=True, help="Skip confirmation")
1009
+ @click.pass_context
1010
+ def version_restore(
1011
+ ctx: click.Context, page_id: str, version_number: int, yes: bool
1012
+ ) -> None:
1013
+ """Restore a page to a previous version."""
1014
+ if not yes:
1015
+ if ctx.obj["json"]:
1016
+ fail("--yes is required when --json is set")
1017
+ click.confirm(
1018
+ f"Restore page {page_id} to version {version_number}? "
1019
+ "This creates a new version with the old content.",
1020
+ abort=True,
1021
+ )
1022
+
1023
+ client = _client(ctx)
1024
+ try:
1025
+ result = client.restore_page_version(page_id, version_number)
1026
+ except AtlassianAPIError as e:
1027
+ fail(str(e))
1028
+
1029
+ if ctx.obj["json"]:
1030
+ emit_json(result)
1031
+ return
1032
+
1033
+ new_version = result.get("version", {}).get("number", "")
1034
+ click.echo(f"Restored page {page_id} to version {version_number} (new version: {new_version})")
1035
+
1036
+
1037
+ # ----------------------------- permissions commands -----------------------------
1038
+
1039
+
1040
+ @conf.command("permissions")
1041
+ @click.option("--id", "page_id", help="Page ID (for page-level permissions)")
1042
+ @click.option("--space", help="Space key (for space-level permissions)")
1043
+ @click.pass_context
1044
+ def permissions_cmd(ctx: click.Context, page_id: str | None, space: str | None) -> None:
1045
+ """View page or space permissions."""
1046
+ if not page_id and not space:
1047
+ fail("provide --id for page permissions or --space for space permissions")
1048
+ if page_id and space:
1049
+ fail("provide either --id or --space, not both")
1050
+
1051
+ client = _client(ctx)
1052
+ try:
1053
+ if page_id:
1054
+ result = client.get_page_restrictions(page_id)
1055
+ else:
1056
+ result = client.get_space_permissions(space) # type: ignore
1057
+ except AtlassianAPIError as e:
1058
+ fail(str(e))
1059
+
1060
+ if ctx.obj["json"]:
1061
+ emit_json(result)
1062
+ return
1063
+
1064
+ if page_id:
1065
+ # Page restrictions
1066
+ click.echo(f"Permissions for page {page_id}:\n")
1067
+ for operation in ["read", "update"]:
1068
+ restrictions = result.get("restrictions", {}).get(operation, {})
1069
+ users = restrictions.get("restrictions", {}).get("user", {}).get("results", [])
1070
+ groups = restrictions.get("restrictions", {}).get("group", {}).get("results", [])
1071
+
1072
+ click.echo(f"{operation.upper()}:")
1073
+ if users:
1074
+ click.echo(" Users:")
1075
+ for u in users:
1076
+ click.echo(f" - {u.get('displayName', '')} ({u.get('username', '')})")
1077
+ if groups:
1078
+ click.echo(" Groups:")
1079
+ for g in groups:
1080
+ click.echo(f" - {g.get('name', '')}")
1081
+ if not users and not groups:
1082
+ click.echo(" (unrestricted)")
1083
+ click.echo()
1084
+ else:
1085
+ # Space permissions
1086
+ click.echo(f"Permissions for space {space}:\n")
1087
+ perms = result.get("permissions", [])
1088
+ if perms:
1089
+ for perm in perms[:10]: # Show first 10
1090
+ click.echo(f"- {perm}")
1091
+ else:
1092
+ click.echo("(no permission data available)")
1093
+
1094
+
1095
+ # ----------------------------- export commands -----------------------------
1096
+
1097
+
1098
+ @conf.command("export")
1099
+ @click.option("--space", required=True, help="Space key to export")
1100
+ @click.option("--limit", default=1000, help="Max pages to export")
1101
+ @click.option("--output", type=click.Path(), help="Output file (JSON)")
1102
+ @click.pass_context
1103
+ def export_cmd(
1104
+ ctx: click.Context, space: str, limit: int, output: str | None
1105
+ ) -> None:
1106
+ """Export all pages from a space to JSON."""
1107
+ client = _client(ctx)
1108
+ try:
1109
+ pages = client.export_space_pages(space, limit=limit)
1110
+ except AtlassianAPIError as e:
1111
+ fail(str(e))
1112
+
1113
+ export_data = {
1114
+ "space": space,
1115
+ "exported_at": __import__("datetime").datetime.now().isoformat(),
1116
+ "page_count": len(pages),
1117
+ "pages": pages,
1118
+ }
1119
+
1120
+ if output:
1121
+ import json
1122
+ from pathlib import Path
1123
+ Path(output).write_text(json.dumps(export_data, indent=2), encoding="utf-8")
1124
+ if not ctx.obj["json"]:
1125
+ click.echo(f"Exported {len(pages)} page(s) from {space} to {output}")
1126
+ else:
1127
+ emit_json(export_data)
1128
+
1129
+