diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index ee2d16eff..6d870a5b7 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -5759,7 +5759,7 @@ def _get_history(self, args: argparse.Namespace) -> dict[int, HistoryItem]: Index and range errors propagate to the caller. Empty selections return an empty dictionary. """ if args.arg: - if args.arg.startswith(r"/") and args.arg.endswith(r"/"): + if len(args.arg) > 1 and args.arg.startswith(r"/") and args.arg.endswith(r"/"): return self.history.regex_search(args.arg, args.all) if re.fullmatch(r"-?[0-9]+", args.arg): try: diff --git a/cmd2/history.py b/cmd2/history.py index 08a178485..bd5146cf7 100644 --- a/cmd2/history.py +++ b/cmd2/history.py @@ -355,7 +355,8 @@ def regex_search(self, regex: str, include_persisted: bool = False) -> dict[int, or an empty dictionary if the regex was not matched """ regex = regex.strip() - if regex.startswith(r"/") and regex.endswith(r"/"): + # A lone "/" is a search for a slash, not an empty pattern wrapped in delimiters + if len(regex) > 1 and regex.startswith(r"/") and regex.endswith(r"/"): regex = regex[1:-1] finder = re.compile(regex, re.DOTALL | re.MULTILINE) diff --git a/tests/test_history.py b/tests/test_history.py index 6dbbd2381..405f162d4 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -383,6 +383,15 @@ def test_history_regex_search(hist) -> None: assert items[2].statement.raw == "second" +def test_history_regex_search_single_slash_is_literal(hist) -> None: + from cmd2.cmd2 import HistoryItem + from cmd2.parsing import Statement + + hist.append(HistoryItem(Statement("", raw="ls /tmp"))) + items = hist.regex_search("/") + assert [item.statement.raw for item in items.values()] == ["ls /tmp"] + + def test_history_max_length_zero(hist) -> None: hist.truncate(0) assert len(hist) == 0 @@ -1144,6 +1153,15 @@ def test_history_literal_search_containing_colon(base_app) -> None: assert list(base_app.last_result) == [3] +def test_history_literal_search_for_single_slash(base_app) -> None: + run_cmd(base_app, "help") + run_cmd(base_app, "set prompt /") + out, err = run_cmd(base_app, "history /") + assert err == [] + assert out == [" 2 set prompt /"] + assert list(base_app.last_result) == [2] + + @pytest.mark.parametrize("separator", [":", ".."]) @pytest.mark.parametrize("session_start", [0, 2, 4]) @pytest.mark.parametrize("include_persisted", [False, True])