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
4 changes: 3 additions & 1 deletion confluence/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import confluence.content.subcommand
import confluence.local.subcommand
import confluence.page.subcommand
from confluence.common.cli import PrettyHelpFormatter
from confluence.common.cli import COMMAND_LINE_ERROR_STATUS_CODE, CommandLineError, PrettyHelpFormatter
from confluence.common.utils import set_logger

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -40,6 +40,8 @@ def main(arguments: Sequence[str] | None = None): # noqa: ANN201
try:
set_logger(args.debug)
args.subcommand_func(args)
except CommandLineError as e:
parser.exit(COMMAND_LINE_ERROR_STATUS_CODE, f"error: {e}\n")
except Exception as e:
logger.exception(e)
raise e
Expand Down
4 changes: 4 additions & 0 deletions confluence/attachment/delete_attachment.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ def get_attachments(api: Api, content_id: str, *, filename: None | str, media_ty


def main(args: argparse.Namespace) -> None:
if args.non_interactive:
msg = "attachment delete は確認入力が必要なため、--non_interactive では実行できません。"
raise cli.CommandLineError(msg)

api = create_api_instance(args)
content_id = args.page_id

Expand Down
22 changes: 22 additions & 0 deletions confluence/common/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
COMMAND_LINE_ERROR_STATUS_CODE = 2


class CommandLineError(Exception):
"""コマンドライン引数や環境変数を修正すると解消できるエラー。"""


class PrettyHelpFormatter(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
def _format_action(self, action: argparse.Action) -> str:
return super()._format_action(action) + "\n"
Expand Down Expand Up @@ -82,6 +86,7 @@ def create_parent_parser() -> argparse.ArgumentParser:
"""
parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
group = parent_parser.add_argument_group(GLOBAL_OPTIONAL_ARGUMENTS_TITLE)
group.add_argument("--non_interactive", action="store_true", help="対話入力を要求せず、必要な認証情報や操作の確認がなければエラーにします。")
group.add_argument("--debug", action="store_true", help="指定するとデバッグ用のログが出力されます。")
group.add_argument(
"--confluence_base_url",
Expand Down Expand Up @@ -217,6 +222,23 @@ def format_url(url: str) -> str:
url = url.removesuffix("/")
return url

if args.non_interactive:
credentials = {}
for name in ("confluence_base_url", "confluence_user_name", "confluence_user_password"):
env_name = name.upper()
value = getattr(args, name)
if value is None:
value = os.environ.get(env_name)
if not value or (name != "confluence_user_password" and not value.strip()):
msg = f"--non_interactive では --{name} または環境変数 {env_name} を指定してください。"
raise CommandLineError(msg)
credentials[name] = value
return Api(
credentials["confluence_user_name"],
credentials["confluence_user_password"],
format_url(credentials["confluence_base_url"]),
)

confluence_base_url = args.confluence_base_url
if confluence_base_url is None:
if "CONFLUENCE_BASE_URL" in os.environ:
Expand Down
3 changes: 3 additions & 0 deletions confluence/page/update_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ def main(args: argparse.Namespace) -> None:
logger.info(f"次のページを更新します。 :: page_id='{page_id}', title='{page_title}', space.key='{space_key}'")

if not args.yes:
if args.non_interactive:
msg = "--non_interactive でページを更新するには --yes を指定してください。"
raise cli.CommandLineError(msg)
if not prompt_yesno("ページを更新しますか?"):
logger.info("ページの更新をキャンセルしました。")
return
Expand Down
11 changes: 11 additions & 0 deletions docs/user_guide/getting_started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,14 @@ ConfluenceのURLの指定

``content_id`` の調べ方
--------------------------------------------------


非対話での実行
==============================

スクリプトなどで実行する場合は、サブコマンドに ``--non_interactive`` を指定します。
認証情報はコマンドライン引数または環境変数で設定します。両方に設定した項目は引数を優先します。
認証情報が不足すると、入力を求めず、エラーメッセージを標準エラー出力に出して終了コード 2 で終了します。

``page update`` で実際にページを更新する場合は、あわせて ``--yes`` を指定します。
確認入力が必要な ``attachment delete`` は非対話モードでは実行できません。
71 changes: 71 additions & 0 deletions tests/test_non_interactive.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
from unittest.mock import Mock

import pytest

from confluence.__main__ import main

CREDENTIALS = {
"CONFLUENCE_BASE_URL": "https://example.test/confluence/",
"CONFLUENCE_USER_NAME": "agent",
"CONFLUENCE_USER_PASSWORD": "test-password",
}


@pytest.fixture(autouse=True)
def configure_environment(monkeypatch):
for name, value in CREDENTIALS.items():
monkeypatch.setenv(name, value)
monkeypatch.setattr("builtins.input", Mock(side_effect=AssertionError("unexpected prompt")))
monkeypatch.setattr("confluence.common.cli.getpass.getpass", Mock(side_effect=AssertionError("unexpected password prompt")))


@pytest.mark.parametrize("missing", CREDENTIALS)
def test_non_interactive_reports_missing_credentials(monkeypatch, capsys, missing):
monkeypatch.delenv(missing)

with pytest.raises(SystemExit) as exc_info:
main(["page", "get_body", "--page_id", "42", "--non_interactive"])

assert exc_info.value.code == 2
stderr = capsys.readouterr().err
assert missing in stderr
assert CREDENTIALS["CONFLUENCE_USER_PASSWORD"] not in stderr


def test_non_interactive_combines_options_and_environment(monkeypatch):
api_factory = Mock()
api_factory.return_value.get_content_by_id.return_value = {
"id": "42",
"type": "page",
"title": "Page",
"body": {"storage": {"value": "<p>Body</p>"}},
}
monkeypatch.setattr("confluence.common.cli.Api", api_factory)

main(["page", "get_body", "--page_id", "42", "--non_interactive", "--confluence_user_name", "override"])

api_factory.assert_called_once_with("override", "test-password", "https://example.test/confluence")


def test_non_interactive_update_requires_yes(monkeypatch, tmp_path, capsys):
api = Mock()
api.get_content_by_id.return_value = {"title": "Page", "space": {"key": "DOC"}, "version": {"number": 7}}
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")
with pytest.raises(SystemExit) as exc_info:
main(["page", "update", "--page_id", "42", "--xml_file", str(xml_file), "--non_interactive"])

assert exc_info.value.code == 2
assert "--yes" in capsys.readouterr().err
api.update_content.assert_not_called()


def test_non_interactive_attachment_delete_exits_without_request(monkeypatch):
api_factory = Mock()
monkeypatch.setattr("confluence.attachment.delete_attachment.create_api_instance", api_factory)
with pytest.raises(SystemExit) as exc_info:
main(["attachment", "delete", "--page_id", "42", "--non_interactive"])

assert exc_info.value.code == 2
api_factory.assert_not_called()