Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions confluence/common/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import getpass
import logging
import os
import sys

from more_itertools import first_true

Expand Down Expand Up @@ -129,6 +130,11 @@ def create_parent_parser() -> argparse.ArgumentParser:
return parser


def _prompt_input(message: str) -> str:
print(message, end="", file=sys.stderr, flush=True)
return input()


def prompt_yesno(msg: str) -> bool:
"""
標準入力で yes, noを選択できるようにする。
Expand All @@ -140,7 +146,7 @@ def prompt_yesno(msg: str) -> bool:

"""
while True:
choice = input(f"{msg} [y/n] : ")
choice = _prompt_input(f"{msg} [y/n] : ")
if choice == "y":
return True

Expand Down Expand Up @@ -203,13 +209,13 @@ def get_confluence_user_password() -> str:
def get_confluence_user_name() -> str:
value = ""
while value == "":
value = input("Confluenceのユーザー名を入力してください。 : ")
value = _prompt_input("Confluenceのユーザー名を入力してください。 : ")
return value

def get_confluence_base_url_from_stdin() -> str:
value = ""
while value == "":
value = input("ConfluenceのURLを入力してください。(例) https://kurusugawa.jp/confluence : ")
value = _prompt_input("ConfluenceのURLを入力してください。(例) https://kurusugawa.jp/confluence : ")
return value

def format_url(url: str) -> str:
Expand Down
31 changes: 30 additions & 1 deletion confluence/page/update_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@

import argparse
import logging
from difflib import unified_diff
from pathlib import Path
from urllib.parse import urlencode

from confluence.common import cli
from confluence.common.cli import create_api_instance, prompt_yesno
from confluence.common.utils import output_string, print_json

logger = logging.getLogger(__name__)


def storage_diff(current_body: str, edited_body: str) -> str:
lines = unified_diff(current_body.splitlines(keepends=True), edited_body.splitlines(keepends=True), fromfile="current", tofile="edited")
return "".join(line if line.endswith("\n") else f"{line}\n\\ No newline at end of file\n" for line in lines)


def main(args: argparse.Namespace) -> None:
api = create_api_instance(args)
page_id = args.page_id
Expand All @@ -20,12 +28,28 @@ def main(args: argparse.Namespace) -> None:
old_content = api.get_content_by_id(page_id, query_params={"expand": "version,ancestors,space,body.storage"})

page_title = old_content["title"]
page_info = {
"page_id": page_id,
"title": page_title,
"url": f"{api.base_url}/pages/viewpage.action?{urlencode({'pageId': page_id})}",
}
if args.dry_run:
version = old_content["version"]["number"]
diff = storage_diff(old_content["body"]["storage"]["value"], xml_text)
if args.json:
print_json({**page_info, "status": "preview", "version": version, "diff": diff})
else:
output_string(f"{page_title} (ID: {page_id}, 版: {version})\n{page_info['url']}\n{diff or '本文に変更はありません。'}".rstrip("\n"))
return

space_key = old_content["space"]["key"]
logger.info(f"次のページを更新します。 :: page_id='{page_id}', title='{page_title}', space.key='{space_key}'")

if not args.yes:
if not prompt_yesno("ページを更新しますか?"):
logger.info("ページの更新をキャンセルしました。")
if args.json:
print_json({**page_info, "status": "cancelled", "version": old_content["version"]["number"]})
return

request_body = {
Expand All @@ -35,7 +59,9 @@ def main(args: argparse.Namespace) -> None:
"space": {"key": space_key},
"body": {"storage": {"value": xml_text, "representation": "storage"}},
}
_ = api.update_content(page_id, request_body=request_body)
updated = api.update_content(page_id, request_body=request_body)
if args.json:
print_json({**page_info, "status": "updated", "version": updated["version"]["number"]})
logger.info(f"次のページを'{xml_file}'の内容で更新しました。 :: page_id='{page_id}', title='{page_title}', space.key='{space_key}'")


Expand All @@ -50,6 +76,9 @@ def add_arguments_to_parser(parser: argparse.ArgumentParser): # noqa: ANN201
parser.add_argument("--comment", help="ページを更新したときに残すコメント。")
parser.add_argument("--yes", action="store_true", help="すべてのプロンプトに自動的に'yes'と答え、非対話的に実行します。")

parser.add_argument("--dry_run", action="store_true", help="ページを更新せず、対象ページと本文の差分を出力します。")
parser.add_argument("--json", action="store_true", help="プレビューまたは更新結果をJSONで出力します。")

parser.set_defaults(subcommand_func=main)


Expand Down
9 changes: 9 additions & 0 deletions docs/command_reference/page/update.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,18 @@ Examples
$ confluence page update --page_id ${PAGE_ID} --xml_file page.xml --comment "ページを更新しました"


更新前に対象ページと差分を確認するには、``--dry_run`` を指定します。
``--json`` を組み合わせると、標準出力にJSONを出力します。

.. code-block::

$ confluence page update --page_id ${PAGE_ID} --xml_file page.xml --dry_run --json

JSONには ``page_id``、``title``、``url``、``version``、``status`` が含まれます。
プレビュー時の ``status`` は ``preview`` で、本文の差分は ``diff`` に入ります。
差分が空の場合は本文に変更がありません。
実行時の ``status`` は更新成功なら ``updated``、確認で取り消した場合は ``cancelled`` です。
``version`` は更新成功時には更新後の版番号、それ以外では取得した時点の版番号です。


Usage Details
Expand Down
81 changes: 81 additions & 0 deletions tests/test_page_update_output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import json
from unittest.mock import Mock

import pytest

from confluence.__main__ import main
from confluence.common.cli import create_api_instance


@pytest.fixture
def page_update(monkeypatch, tmp_path):
api = Mock(base_url="https://example.test/confluence")
api.get_content_by_id.return_value = {
"version": {"number": 7},
"title": "Page",
"space": {"key": "DOC"},
"type": "page",
"body": {"storage": {"value": "<p>Old</p>"}},
}
api.update_content.return_value = {"version": {"number": 8}}
monkeypatch.setattr("confluence.page.update_page.create_api_instance", lambda _args: api)
xml_file = tmp_path / "page.xml"
xml_file.write_text("<p>Edited</p>", encoding="utf-8")
return api, ["page", "update", "--page_id", "42", "--xml_file", str(xml_file)]


@pytest.mark.parametrize("as_json", [False, True])
def test_dry_run_has_diff_and_does_not_update(page_update, capsys, monkeypatch, as_json):
api, args = page_update
monkeypatch.setattr("builtins.input", Mock(side_effect=AssertionError("unexpected prompt")))

main([*args, "--dry_run", *(["--json"] if as_json else [])])

api.update_content.assert_not_called()
output = capsys.readouterr().out
if as_json:
preview = json.loads(output)
assert preview["status"] == "preview"
assert preview["version"] == 7
assert preview["page_id"] == "42"
assert preview["url"] == "https://example.test/confluence/pages/viewpage.action?pageId=42"
output = preview["diff"]
assert "-<p>Old</p>\n" in output
assert "+<p>Edited</p>\n" in output


@pytest.mark.parametrize(("answer", "status", "version"), [("y", "updated", 8), ("n", "cancelled", 7)])
def test_update_json_keeps_confirmation_out_of_stdout(page_update, capsys, monkeypatch, answer, status, version):
api, args = page_update
monkeypatch.setattr("builtins.input", lambda: answer)

main([*args, "--json"])

output = capsys.readouterr()
assert json.loads(output.out) == {
"page_id": "42",
"title": "Page",
"url": "https://example.test/confluence/pages/viewpage.action?pageId=42",
"version": version,
"status": status,
}
assert "[y/n]" in output.err
assert api.update_content.call_count == (1 if answer == "y" else 0)


def test_json_keeps_credential_prompts_out_of_stdout(page_update, capsys, monkeypatch):
api, args = page_update
monkeypatch.setattr("confluence.page.update_page.create_api_instance", create_api_instance)
monkeypatch.setattr("confluence.common.cli.Api", Mock(return_value=api))
monkeypatch.delenv("CONFLUENCE_BASE_URL", raising=False)
monkeypatch.delenv("CONFLUENCE_USER_NAME", raising=False)
replies = iter(["https://example.test/confluence", "agent"])
monkeypatch.setattr("builtins.input", lambda: next(replies))
monkeypatch.setattr("confluence.common.cli.getpass.getpass", Mock(return_value="test-password"))

main([*args, "--dry_run", "--json"])

output = capsys.readouterr()
assert json.loads(output.out)["status"] == "preview"
assert "ConfluenceのURL" in output.err
assert "Confluenceのユーザー名" in output.err