API ignores the "check" option
Describe the bug
context When I format a file via mdformat.file and pass the check option.
expectation I expect the call to error-out if the file is not formatted similar to what the CLI does.
bug Instead the file is always reformatted.
It would be great to have the API behave the same as the CLI to work in Python-based tooling w/o having to subprocess-call mdformat.
On a side-note, one can also specify arbitrary options that get silently ignored.
Reproduce the bug
from pathlib import Path
import mdformat
file = Path("ill_formatted.md")
file.write_text(" # TITLE WITH LEADING SPACES")
print(f"Before\n{file.read_text()}")
mdformat.file(file, options={"check": True})
print(f"After\n{file.read_text()}")
file.unlink()
Output:
Before
# TITLE WITH LEADING SPACES
After
# TITLE WITH LEADING SPACES
List your environment
Python 3.13.2 & mdformat 0.7.22
Related #233
For the CLI, --check is a separate step before writing the file and not a native option to the shared API. See:
https://github.com/hukkin/mdformat/blob/499b47aeb430f6e09f841ed4f70a992dbb06c96f/src/mdformat/_cli.py#L146C33-L148
You can implement check today with something like:
import sys
from pathlib import Path
import mdformat
for pth in Path.cwd().glob("**/*.md"):
original = pth.read_text()
formatted = mdformat.text(original)
if formatted != original:
print(f"File '{pth}' is not formatted.")
print(f"Expected\n{formatted}", file=sys.stderr)
Having validation of the options and integrating check into the API might be nice PRs to consider.
Hey Kyle!
Thanks for the reply. I'm currently just using the protected _cli API (since we are all grown ups ;-) ):
mdformat._cli.run([md_file_name, "--end-of-line=keep", "--number", "--wrap=120", "--check"]))
This way my devs have the exact same experience when calling mdformat from the CLI or when the linting script is run in CI. If I find some time, I'll have a look at an PR.