Skip to content

Commit

Permalink
fix: only greet once when setting the same mode (#301)
Browse files Browse the repository at this point in the history
With this fix, ``Emitter.set_mode(mode)`` becomes a no-op if the emitter is
already at that ``mode``. This scenario can happen, for example, if the Emitter
is initialized with a mode and then the Dispatcher sets the same mode during
command-line handling.
  • Loading branch information
tigarmo authored Nov 8, 2024
1 parent 41a4f28 commit 6fa01e1
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions craft_cli/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,9 @@ def get_mode(self) -> EmitterMode:
@_active_guard()
def set_mode(self, mode: EmitterMode) -> None:
"""Set the mode of the emitter."""
if mode == self._mode:
return

self._mode = mode
self._log_handler.mode = mode

Expand Down
6 changes: 6 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ Changelog
See the `Releases page`_ on GitHub for a complete list of commits that are
included in each version.

2.10.1 (2024-Nov-11)
--------------------

- Fix an issue where setting an ``Emitter`` to the same mode multiple times
resulted in multiple greetings.

2.10.0 (2024-Oct-31)
--------------------
- Support adding a link to documentation in help messages.
Expand Down
27 changes: 27 additions & 0 deletions tests/unit/test_messages_emitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import logging
import sys
from unittest import mock
from unittest.mock import call, patch

import pytest
Expand Down Expand Up @@ -298,6 +299,32 @@ def test_set_mode_developer_modes(get_initiated_emitter, mode):
assert handler.mode == mode


@pytest.mark.parametrize(
"mode",
[
EmitterMode.VERBOSE,
EmitterMode.DEBUG,
EmitterMode.TRACE,
],
)
def test_set_mode_repeated(get_initiated_emitter, mode):
"""Repeatedly setting the same mode should not emit multiple greetings."""
greeting = "greeting"
emitter = get_initiated_emitter(EmitterMode.QUIET, greeting=greeting)

emitter.set_mode(mode)
emitter.set_mode(mode)

log_locat = f"Logging execution to {emitter._log_filepath!r}"
extra_print_args = {"use_timestamp": mock.ANY, "avoid_logging": True, "end_line": True}

# Only a single printing of the greeting and the logpath
assert emitter.printer_calls == [
call().show(sys.stderr, greeting, **extra_print_args),
call().show(sys.stderr, log_locat, **extra_print_args),
]


# -- tests for emitting messages of all kind


Expand Down

0 comments on commit 6fa01e1

Please sign in to comment.