diff --git a/CHANGELOG.md b/CHANGELOG.md index 291dc0ecc..30902cf85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ - On Windows, shell command completion now recognizes paths typed with forward slashes, such as `./my` and `C:/tools/my`. Path completion preserves the typed separators so the first Tab extends the shared prefix when several names match. + - `history --output-file` and `history --edit` now write UTF-8 files, so `run_script` can run + them again. On a locale whose encoding is not UTF-8, such as Korean or Japanese Windows, a + history with non-ASCII text was written in the locale's encoding, which `run_script` rejects + as not being an ASCII or UTF-8 encoded text file. `run_pyscript` now reads scripts as UTF-8, + the default encoding of Python source files, with or without a byte order mark, instead of in + the locale's encoding. ## 4.4.3 (2026-11-16) diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 942bcd2cd..7519c1ec2 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -5315,7 +5315,7 @@ def py_quit() -> None: expanded_filename = os.path.expanduser(pyscript) try: - with open(expanded_filename) as f: + with open(expanded_filename, encoding="utf-8-sig") as f: py_code_to_run = f.read() except OSError as ex: self.perror(f"Error reading script file '{expanded_filename}': {ex}") @@ -5628,7 +5628,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None: if args.edit: fd, fname = tempfile.mkstemp(suffix=".txt", text=True) fobj: TextIO - with os.fdopen(fd, "w") as fobj: + with os.fdopen(fd, "w", encoding="utf-8") as fobj: for command in history.values(): if command.statement.multiline_command: fobj.write(f"{command.expanded}\n") @@ -5644,7 +5644,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None: elif args.output_file: full_path = os.path.abspath(os.path.expanduser(args.output_file)) try: - with open(full_path, "w") as fobj: + with open(full_path, "w", encoding="utf-8") as fobj: for item in history.values(): if item.statement.multiline_command: fobj.write(f"{item.expanded}\n") diff --git a/tests/test_history.py b/tests/test_history.py index ac89620a7..700895d97 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -1473,6 +1473,59 @@ def test_history_edit(monkeypatch) -> None: run_script_mock.assert_called_once() +@pytest.fixture +def non_utf8_locale(monkeypatch): + """Make cmd2's open() and os.fdopen() default to cp1252, as they do on a non-UTF-8 Windows locale.""" + real_open = open + real_fdopen = os.fdopen + + def open_cp1252(file, mode="r", *args, **kwargs): + if "b" not in mode and not args: + kwargs.setdefault("encoding", "cp1252") + return real_open(file, mode, *args, **kwargs) + + def fdopen_cp1252(fd, mode="r", *args, **kwargs): + if "b" not in mode and not args: + kwargs.setdefault("encoding", "cp1252") + return real_fdopen(fd, mode, *args, **kwargs) + + monkeypatch.setattr(cmd2.cmd2, "open", open_cp1252, raising=False) + monkeypatch.setattr(cmd2.cmd2.os, "fdopen", fdopen_cp1252) + + +class SayApp(cmd2.Cmd): + def do_say(self, args) -> None: + self.poutput(args) + + +def test_history_output_file_is_utf8(non_utf8_locale, tmp_path) -> None: + app = SayApp() + run_cmd(app, "say Łukasz ✨") + fname = tmp_path / "history.txt" + + run_cmd(app, f'history -o "{fname}"') + + assert app.last_result is True + assert fname.read_bytes().decode("utf-8").splitlines() == ["say Łukasz ✨"] + + # run_script reads only ASCII or UTF-8 files, so the saved history can be run again + out, err = run_cmd(app, f'run_script "{fname}"') + assert err == [] + assert out == ["Łukasz ✨"] + + +def test_history_edit_runs_non_ascii_commands(non_utf8_locale, monkeypatch) -> None: + app = SayApp() + # Leave the file as history wrote it + monkeypatch.setattr("cmd2.Cmd.run_editor", lambda _self, _fname: None) + run_cmd(app, "say Łukasz ✨") + + out, err = run_cmd(app, "history -e 1") + + assert err == [] + assert out == ["Łukasz ✨"] + + def test_history_run_all_commands(base_app) -> None: # make sure we refuse to run all commands as a default run_cmd(base_app, "shortcuts") diff --git a/tests/test_run_pyscript.py b/tests/test_run_pyscript.py index e4030ebde..4ebbea914 100644 --- a/tests/test_run_pyscript.py +++ b/tests/test_run_pyscript.py @@ -262,3 +262,26 @@ def test_run_pyscript_print_redirection(base_app, request, tmp_path, capsys) -> # Verify the remaining output when to the correct stream assert "this goes to sys.stdout" in out assert "this goes to sys.stderr" in err + + +@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"]) +def test_run_pyscript_reads_utf8(base_app, tmp_path, monkeypatch, encoding) -> None: + import cmd2.cmd2 + + real_open = open + + def open_cp1252(file, mode="r", *args, **kwargs): + # Without an explicit encoding, open() uses cp1252, as it does on a non-UTF-8 Windows locale + if "b" not in mode and not args: + kwargs.setdefault("encoding", "cp1252") + return real_open(file, mode, *args, **kwargs) + + monkeypatch.setattr(cmd2.cmd2, "open", open_cp1252, raising=False) + python_script = tmp_path / "script.py" + python_script.write_text('print("Łukasz ✨")\n', encoding=encoding) + + out, err = run_cmd(base_app, f'run_pyscript "{python_script}"') + + assert err == [] + assert out == ["Łukasz ✨"] + assert base_app.last_result is True