mdformat icon indicating copy to clipboard operation
mdformat copied to clipboard

API ignores the "check" option

Open LordFckHelmchen opened this issue 8 months ago • 3 comments

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

LordFckHelmchen avatar Apr 30 '25 15:04 LordFckHelmchen

Related #233

LordFckHelmchen avatar Apr 30 '25 16:04 LordFckHelmchen

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.

KyleKing avatar May 20 '25 15:05 KyleKing

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.

LordFckHelmchen avatar May 21 '25 08:05 LordFckHelmchen