diff --git a/README.md b/README.md index 4682e1a0..12c7076b 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,8 @@ positional arguments: options: -h, --help show this help message and exit --check do not apply changes to files + --exit-non-zero-on-format + return non-zero if files are modified --no-validate do not validate that the rendered HTML is consistent --version show program's version number and exit --number apply consecutive numbering to ordered lists diff --git a/src/mdformat/_cli.py b/src/mdformat/_cli.py index 74a6e28b..28977090 100644 --- a/src/mdformat/_cli.py +++ b/src/mdformat/_cli.py @@ -178,6 +178,8 @@ def run(cli_args: Sequence[str], cache_toml: bool = True) -> int: # noqa: C901 return 1 if path: if formatted_str != original_str: + if opts["exit_non_zero_on_format"]: + format_errors_found = True path.write_bytes(formatted_str.encode()) else: sys.stdout.buffer.write(formatted_str.encode()) @@ -210,6 +212,11 @@ def make_arg_parser( parser.add_argument( "--check", action="store_true", help="do not apply changes to files" ) + parser.add_argument( + "--exit-non-zero-on-format", + action="store_true", + help="return non-zero if files are modified", + ) parser.add_argument( "--no-validate", action="store_const", diff --git a/tests/test_cli.py b/tests/test_cli.py index 28c36223..337b734a 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -26,6 +26,13 @@ def test_format(tmp_path): assert file_path.read_text() == FORMATTED_MARKDOWN +def test_format__exit_non_zero(tmp_path): + file_path = tmp_path / "test_markdown.md" + file_path.write_text(UNFORMATTED_MARKDOWN) + assert run((str(file_path),), "--exit-non-zero-on-format") == 1 + assert file_path.read_text() == FORMATTED_MARKDOWN + + def test_format__folder(tmp_path): file_path_1 = tmp_path / "test_markdown1.md" file_path_2 = tmp_path / "test_markdown2.md" @@ -39,6 +46,19 @@ def test_format__folder(tmp_path): assert file_path_3.read_text() == UNFORMATTED_MARKDOWN +def test_format__folder_exit_non_zero(tmp_path): + file_path_1 = tmp_path / "test_markdown1.md" + file_path_2 = tmp_path / "test_markdown2.md" + file_path_3 = tmp_path / "not_markdown3" + file_path_1.write_text(UNFORMATTED_MARKDOWN) + file_path_2.write_text(UNFORMATTED_MARKDOWN) + file_path_3.write_text(UNFORMATTED_MARKDOWN) + assert run((str(tmp_path),), "--exit-non-zero-on-format") == 1 + assert file_path_1.read_text() == FORMATTED_MARKDOWN + assert file_path_2.read_text() == FORMATTED_MARKDOWN + assert file_path_3.read_text() == UNFORMATTED_MARKDOWN + + def test_format__folder_leads_to_invalid(tmp_path): file_path_1 = tmp_path / "test_markdown1.md" file_path_1.mkdir()