diff --git a/codespell_lib/_codespell.py b/codespell_lib/_codespell.py index b98cdd81f2..7be5e7fa13 100644 --- a/codespell_lib/_codespell.py +++ b/codespell_lib/_codespell.py @@ -535,6 +535,11 @@ def parse_options( metavar="LINES", help="print LINES of surrounding context", ) + parser.add_argument( + "--stdin-single-line", + action="store_true", + help="output just a single line for each misspelling in stdin mode", + ) parser.add_argument("--config", type=str, help="path to config file.") parser.add_argument("--toml", type=str, help="path to a pyproject.toml file.") parser.add_argument("files", nargs="*", help="files or directories to check") @@ -993,6 +998,8 @@ def parse_file( f"{cfilename}:{cline}: {cwrongword} " f"==> {crightword}{creason}" ) + elif options.stdin_single_line: + print(f"{cline}: {cwrongword} ==> {crightword}{creason}") else: print( f"{cline}: {line.strip()}\n\t{cwrongword} " diff --git a/codespell_lib/tests/test_basic.py b/codespell_lib/tests/test_basic.py index 8a20f0a7e1..8888c22288 100644 --- a/codespell_lib/tests/test_basic.py +++ b/codespell_lib/tests/test_basic.py @@ -1163,3 +1163,40 @@ def FakeStdin(text: str) -> Generator[None, None, None]: yield finally: sys.stdin = oldin + + +def run_codespell_stdin( + text: str, + args: Tuple[Any, ...], + cwd: Optional[Path] = None, +) -> int: + """Run codespell in stdin mode and return number of lines in output.""" + proc = subprocess.run( + ["codespell", *args, "-"], # noqa: S603, S607 + cwd=cwd, + input=text, + capture_output=True, + encoding="utf-8", + check=False, + ) + output = proc.stdout + # get number of lines + count = output.count("\n") + return count + + +def test_stdin(tmp_path: Path) -> None: + """Test running the codespell executable.""" + input_file_lines = 4 + text = "" + for _ in range(input_file_lines): + text += "abandonned\n" + for single_line_per_error in [True, False]: + args: Tuple[str, ...] = () + if single_line_per_error: + args = ("--stdin-single-line",) + # we expect 'input_file_lines' number of lines with + # --stdin-single-line and input_file_lines * 2 lines without it + assert run_codespell_stdin( + text, args=args, cwd=tmp_path + ) == input_file_lines * (2 - int(single_line_per_error))