def test_gfm_spec(entry): """Test mdformat-gfm against the GFM spec. Test that: 1. Markdown AST is the same before and after 1 pass of formatting 2. Markdown after 1st pass and 2nd pass of formatting are equal """ md_original = entry["md"] md_new = mdformat.text(md_original, extensions={"gfm"}) md_2nd_pass = mdformat.text(md_new, extensions={"gfm"}) assert is_md_equal(md_original, md_new, extensions={"gfm"}) assert md_new == md_2nd_pass
def test_commonmark_spec(wrap, number, entry): """mdformat.text() against the Commonmark spec. Test that: 1. Markdown AST is the same before and after 1 pass of formatting 2. Markdown after 1st pass and 2nd pass of formatting are equal """ options = {"wrap": wrap, "number": number} md_original = entry["md"] md_new = mdformat.text(md_original, options=options) md_2nd_pass = mdformat.text(md_new, options=options) assert is_md_equal(md_original, md_new, options=options) assert md_new == md_2nd_pass
def _render_container(self, source: Path, destination: Path, data: dict): for filename in os.listdir(f"{source}"): filename = Path(filename) src = source / filename dst = destination / filename if src.is_file(): basename = filename if basename.suffix == '.j2': log.info("Rendering template: %s", dst) basename = Path(f"{basename}"[:-3]) result = self.render(src, data=data) if basename.suffix == ".md": result = mdformat.text( result, extensions={"tables", "gfm", "toc"} ) if result and not result.isspace(): with open(destination / basename, "w") as f: f.write(result) elif basename.suffix == '.1': basename = Path(f"{basename}"[:-2]) target = destination / basename if not target.exists(): log.info("Copying %s to %s", src, target) shutil.copy(src, target) else: log.info( "Skipping %s since target alreaady exists", target) else: log.info("Copying %s to %s", src, dst) shutil.copy(src, dst) else: dst.mkdir(parents=True, exist_ok=True) self._render_container(src, dst, data)
def test_default_style__api(line, title, text, expected): """Test fixtures in tests/data/default_style.md.""" md_new = mdformat.text(text, extensions={"gfm"}) if md_new != expected: print("Formatted (unexpected) Markdown below:") print(md_new) assert md_new == expected
def runtest(self): with open(str(self.fspath)) as file: md = file.read() formatted = mdformat.text(md) assert md == formatted mtimes = getattr(self.config, "_mdformat_mtimes", {}) mtimes[str(self.fspath)] = self._mdformat_mtime
def test_css(): unformatted_md = """~~~css body {background-color: powderblue; } h1 { color: blue; } p{ \t\tcolor: red;} ~~~ """ formatted_md = """```css body { background-color: powderblue; } h1 { color: blue; } p { color: red; } ``` """ assert mdformat.text(unformatted_md, codeformatters={"css"}) == formatted_md
def test_xml(): unformatted_md = """~~~xml <?xml version="1.0" encoding="UTF-8"?> <note> <to>Tove</to><from>Jani</from> <heading>Reminder</heading><body>Don't forget me this weekend!</body> </note> ~~~ """ formatted_md = """```xml <?xml version="1.0" encoding="utf-8"?> <note> <to> Tove </to> <from> Jani </from> <heading> Reminder </heading> <body> Don\'t forget me this weekend! </body> </note> ``` """ assert mdformat.text(unformatted_md, codeformatters={"xml"}) == formatted_md
def test_fixtures(line, title, text, expected): """Test fixtures in tests/data/fixtures.md.""" md_new = mdformat.text(text, extensions={"toc"}) if md_new != expected: print("Formatted (unexpected) Markdown below:") print(md_new) assert md_new == expected
def test_html(): unformatted_md = """~~~html <ul> <li>foo</li> </ul> <hr /> <ul> <li>bar</li> </ul> ~~~ """ formatted_md = """```html <html> <body> <ul> <li> foo </li> </ul> <hr/> <ul> <li> bar </li> </ul> </body> </html> ``` """ assert mdformat.text(unformatted_md, codeformatters={"html"}) == formatted_md
def convert_to_markdown(resume: Resume, destination: str): content = get_markdown_content(resume) markdown = os.linesep.join( [item_line for category in content for item_line in category]) markdown = mdformat.text(markdown, options={'wrap': 120}) with open(destination, 'w+') as f: f.write(markdown)
def test_fixtures__api(line, title, text, expected): """Test fixtures in tests/data/fixtures.md.""" md_new = mdformat.text(text, extensions={"myst"}) try: assert md_new == expected except Exception: print(md_new) raise
def test_fixtures(line, title, text, expected): """Test fixtures in tests/data/fixtures.md.""" if "NIGHTLY" in title: pytest.skip("nightly test not supported on stable") md_new = mdformat.text(text, codeformatters={"rust"}) if md_new != expected: print("Formatted (unexpected) Markdown below:") print(md_new) assert md_new == expected
def test_style(fixture_file, options): """Test Markdown renderer renders expected style.""" cases = read_fixture_file(Path(__file__).parent / "data" / fixture_file) for case in cases: line, title, text, expected = case md_new = mdformat.text(text, options=options) if md_new != expected: print(md_new) assert md_new == expected
def format_md(text: str) -> str: """ Format MarkDown with mdformat. """ return mdformat.text( text, options={ "wrap": 79, }, )
def test_api_options(): non_numbered = """\ 0. a 0. b 0. c """ numbered = """\ 0. a 1. b 2. c """ assert mdformat.text(non_numbered, options={"number": True}) == numbered
def test_format_json__integration(): unformatted_md = """~~~json {"a": 1, "b": 2} ~~~ """ formatted_md = """```json { "a": 1, "b": 2 } ``` """ assert mdformat.text(unformatted_md, codeformatters={"json"}) == formatted_md
def lint(md: str) -> str: """Lint the `Markdown`. Parameters ---------- md : str The `Markdown` as outputted by `astdocs`. Returns ------- : str Linted `Markdown`. """ return mdformat.text(md)
def test_rustfmt_error(capfd): """Test that any prints by rustfmt go to devnull.""" unformatted_md = """~~~rust blaalbal.ablaa ~~~ """ formatted_md = """```rust blaalbal.ablaa ``` """ result = mdformat.text(unformatted_md, codeformatters={"rust"}) captured = capfd.readouterr() assert not captured.err assert not captured.out assert result == formatted_md
def test_code_formatter(monkeypatch): monkeypatch.setitem(CODEFORMATTERS, "lang", example_formatter) text = mdformat.text( dedent("""\ ```lang a ``` """), codeformatters={"lang"}, ) assert text == dedent("""\ ```lang dummy ``` """)
def test_mdformat_integration(): unformatted_md = """~~~python def hello(): print( 'Hello world!' ) ~~~ """ formatted_md = """```python def hello(): print("Hello world!") ``` """ assert mdformat.text(unformatted_md, codeformatters={"python"}) == formatted_md
def test_gofmt_error(capfd): """Test that any prints by gofmt go to devnull.""" unformatted_md = """~~~go func { ~~~ """ formatted_md = """```go func { ``` """ result = mdformat.text(unformatted_md, codeformatters={"go"}) captured = capfd.readouterr() assert not captured.err assert not captured.out assert result == formatted_md
def test_single_token_extension(monkeypatch): """Test the front matter plugin, as a single token extension example.""" plugin_name = "text_editor" monkeypatch.setitem(PARSER_EXTENSIONS, plugin_name, TextEditorPlugin) text = mdformat.text( dedent("""\ # Example Heading Example paragraph. """), extensions=[plugin_name], ) assert text == dedent("""\ # All text is like this now! All text is like this now! """)
def test_table(monkeypatch): """Test the table plugin, as a multi-token extension example.""" monkeypatch.setitem(PARSER_EXTENSIONS, "table", ExampleTablePlugin) text = mdformat.text( dedent("""\ |a|b| |-|-| |c|d| other text """), extensions=["table"], ) assert text == dedent("""\ dummy 21 other text """)
def test_format_toml__integration(): unformatted_md = """~~~toml [animals] color = "white" [cars] color = "blue" ~~~ """ formatted_md = """```toml [animals] color = "white" [cars] color = "blue" ``` """ assert mdformat.text(unformatted_md, codeformatters={"toml"}) == formatted_md
def test_mdformat_integration(): unformatted_md = """~~~go package main import "fmt" func main() { fmt.Println("hello world") } ~~~ """ formatted_md = """```go package main import "fmt" func main() { \tfmt.Println("hello world") } ``` """ assert mdformat.text(unformatted_md, codeformatters={"go"}) == formatted_md
def test_js(): unformatted_md = """~~~js function myFunction() { // Declare a function document.getElementById("demo").innerHTML = "Hello World!";} myFunction(); // Call the function ~~~ """ formatted_md = """```js function myFunction() { // Declare a function document.getElementById("demo").innerHTML = "Hello World!"; } myFunction(); // Call the function ``` """ assert mdformat.text(unformatted_md, codeformatters={"js"}) == formatted_md
def test_postprocess_plugins(monkeypatch): """Test that postprocessors work collaboratively.""" suffix_plugin_name = "suffixer" prefix_plugin_name = "prefixer" monkeypatch.setitem(PARSER_EXTENSIONS, suffix_plugin_name, SuffixPostprocessPlugin) monkeypatch.setitem(PARSER_EXTENSIONS, prefix_plugin_name, PrefixPostprocessPlugin) text = mdformat.text( dedent( """\ # Example Heading. Example paragraph. """ ), extensions=[suffix_plugin_name, prefix_plugin_name], ) assert text == dedent( """\ # Prefixed!Example Heading.Suffixed! Prefixed!Example paragraph.Suffixed! """ )
def test_word_wrap(): input_text = """\ [^a] [^a]: Ooh no, the first line of this first paragraph is still wrapped too wide unfortunately. Should fix this. But this second paragraph is wrapped exactly as expected. Woohooo, awesome! """ expected_output = """\ [^a] [^a]: Ooh no, the first line of this first paragraph is still wrapped too wide unfortunately. Should fix this. But this second paragraph is wrapped exactly as expected. Woohooo, awesome! """ output = mdformat.text(input_text, options={"wrap": 40}, extensions={"footnote"}) assert output == expected_output
def run(cli_args: Sequence[str]) -> int: # noqa: C901 parser = argparse.ArgumentParser( description="CommonMark compliant Markdown formatter") parser.add_argument("paths", nargs="*", help="Files to format") parser.add_argument("--check", action="store_true") args = parser.parse_args(cli_args) if not args.paths: sys.stderr.write("No files have been passed in. Doing nothing.\n") return 0 # Convert paths given as args to pathlib.Path objects. # Check that all paths are either files, directories or stdin. # Resolve directory paths to a list of file paths (ending with ".md"). file_paths: List[Optional[Path]] = [ ] # Path to file or None for stdin/stdout for path_str in args.paths: if path_str == "-": file_paths.append(None) continue path_obj = Path(path_str) try: path_exists = path_obj.exists() except OSError: # Catch "OSError: [WinError 123]" on Windows path_exists = False if not path_exists: sys.stderr.write(f'Error: File "{path_str}" does not exist.\n') return 1 if path_obj.is_dir(): for p in path_obj.glob("**/*.md"): file_paths.append(p) else: file_paths.append(path_obj) format_errors_found = False for path in file_paths: if path: path_str = str(path) original_str = path.read_text(encoding="utf-8") else: path_str = "-" original_str = sys.stdin.read() formatted_str = mdformat.text(original_str) if args.check: if formatted_str != original_str: format_errors_found = True sys.stderr.write( f'Error: File "{path_str}" is not formatted.\n') else: if not is_md_equal(original_str, formatted_str): sys.stderr.write( f'Error: Could not format "{path_str}"\n' "\n" "The formatted Markdown renders to different HTML than the input Markdown.\n" # noqa: E501 "This is likely a bug in mdformat. Please create an issue report here:\n" # noqa: E501 "https://github.com/executablebooks/mdformat/issues\n") return 1 if path: path.write_text(formatted_str, encoding="utf-8") else: sys.stdout.write(formatted_str) if format_errors_found: return 1 return 0
def test_fixtures(line, title, text, expected): output = mdformat.text(text, extensions={"pelican"}) print(output) assert output.rstrip() == expected.rstrip(), output