API 使用例
- 全ての例はGitHubで確認できます。
- このページで使用されるMMG APIのリファレンスはPython APIで確認できます。
api_example_convert_file.py
ファイルを読み込んで変換する例です。
See on GitHub
from typing import Dict
import os
import mmg.api as mmg
def main():
# Read a markdown file as a string
base_file = os.path.join(os.path.dirname(__file__), "./sample.base.md")
base_file = os.path.abspath(base_file)
print(f"Reading file: {base_file}")
with open(base_file, "r", encoding="utf-8") as f:
base_md: str = f.read()
# Convert markdown string
converted_mds: Dict[str, str] = mmg.convert(base_md)
for tag, txt in converted_mds.items():
print(f"\n>> Tag: {tag}")
print(txt)
if __name__ == "__main__":
main()
Output Text
>> Tag: A
# Heading A
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in ultrices metus, in semper mi.
Footer here.
>> Tag: B
# Heading B
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in ultrices metus, in semper mi.
Footer here.
>> Tag: C
# Heading C
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean in ultrices metus, in semper mi.
Footer here.
api_example_convert_string.py
Python stringを変換する例です。
See on GitHub
from typing import Dict
import mmg.api as mmg
base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A
Hello, A!
<!-- [B] -->
# Sample Document B
Hello, B!
<!-- [C] -->
# Sample Document C
Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""
def main():
converted_mds: Dict[str, str] = mmg.convert(base_md)
for tag, txt in converted_mds.items():
print(f"\n>> Tag: {tag}")
print(txt)
if __name__ == "__main__":
main()
Output Text
>> Tag: A
# Sample Document A
Hello, A!
Thank you for using mmg!
>> Tag: B
# Sample Document B
Hello, B!
Thank you for using mmg!
>> Tag: C
# Sample Document C
Hello, C!
Thank you for using mmg!
api_example_convert_with_cfg.py
ヘッダーのないPython stringを変換する例です。
ヘッダーの代わりに、Config
オブジェクトを直接使用します。
See on GitHub
from typing import Dict
import mmg.api as mmg
base_md: str = """
<!-- [A] -->
# Sample Document A
Hello, A!
<!-- [B] -->
# Sample Document B
Hello, B!
<!-- [C] -->
# Sample Document C
Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""
def main():
cfg = mmg.Config(lang_tags=["A", "B", "C"])
print(f"Config: {cfg}")
converted_mds: Dict[str, str] = mmg.convert(base_md, cfg=cfg)
for tag, txt in converted_mds.items():
print(f"\n>> Tag: {tag}")
print(txt)
if __name__ == "__main__":
main()
Output Text
>> Tag: A
# Sample Document A
Hello, A!
Thank you for using mmg!
>> Tag: B
# Sample Document B
Hello, B!
Thank you for using mmg!
>> Tag: C
# Sample Document C
Hello, C!
Thank you for using mmg!
api_example_create_toc.py
目次を生成する例です。
See on GitHub
from typing import List
from mmg.utils import REGEX_PATTERN
from mmg.toc import create_toc, parse_toc_options
base_md: str = """
# 🔎 Header 1
Here are some examples of the table of contents.
**Table of Contents with Emoji**
<!-- [[ multilingual toc: level=2~3 ]] -->
**Table of Contents without Emoji**
<!-- [[ multilingual toc: level=2~3 no-emoji ]] -->
## 📝 Header 2
Foo
### 🌈 Header 3
Bar
"""
def main():
doc = base_md.splitlines()
for line in doc:
if REGEX_PATTERN["auto_toc"].match(line):
toc_options = parse_toc_options(line)
toc: List[str] = create_toc(toc_options, doc)
toc: str = "\n".join(toc)
print(f">> Toc (no-emoji: {toc_options[2]}):\n{toc}\n")
if __name__ == "__main__":
main()
Output Text
>> Toc (no-emoji: False):
1. [📝 Header 2](#-header-2)
1. [🌈 Header 3](#-header-3)
>> Toc (no-emoji: True):
1. [Header 2](#-header-2)
1. [Header 3](#-header-3)
api_example_health_check.py
バリデーションを実行する例です。
See on GitHub
from mmg.health import HealthChecker, HealthStatus
base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A
Hello, A!
<!-- [B] -->
# Sample Document B
Hello, B!
<!-- [C] -->
# Sample Document C
Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""
def main():
hc = HealthChecker()
status: HealthStatus = hc.health_check(base_md.splitlines())
print(f" - Health check: {status.name}")
print(" - Health messages:")
for msg in hc.warning_messages:
print(f"\t[WARN] {msg}")
for msg in hc.error_messages:
print(f"\t[ERR ] {msg}")
print(f" - Tag list: {hc.tag_count}")
if __name__ == "__main__":
main()
Output Text
- Health check: HEALTHY
- Health messages:
- Tag list: {'A': 1, 'B': 1, 'C': 1}
api_example_reserved_tags.py
予約されたタグのリストを確認する例です。予約されたタグは、ユーザー定義のタグとして使用できません。
See on GitHub
# import mmg.api as mmg
from mmg.config import RESERVED_KEYWORDS
def main():
print(RESERVED_KEYWORDS)
if __name__ == "__main__":
main()
Output Text
['common', 'ignore', '<Unknown>']
api_example_save_file.py
変換した結果をファイルに保存する例です。
この例は、実際にA.md
、B.md
、C.md
ファイルを現在のディレクトリに作成します。
See on GitHub
import os
from typing import Dict
import mmg.api as mmg
base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A
Hello, A!
<!-- [B] -->
# Sample Document B
Hello, B!
<!-- [C] -->
# Sample Document C
Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""
def main(fake: bool = True):
converted_mds: Dict[str, str] = mmg.convert(base_md)
if fake:
print(f"Fake mode: skip saving file. Detected tags: {converted_mds.keys()}")
return
for tag, txt in converted_mds.items():
file_name = os.path.join(os.path.dirname(__file__), f"./{tag}.md")
file_name = os.path.abspath(file_name)
with open(file_name, "w", encoding="utf-8") as f:
f.write(txt)
if __name__ == "__main__":
main(fake=False)
No output text.
api_example_save_file_no_suffix_option.py
変換した結果をファイルに保存するとき、no suffix
オプションを使用する例です。
この例は、実際にREADME.A
、README.B
、README
ファイルを現在のディレクトリに作成します。
See on GitHub
import os
from typing import Dict, List
from mmg.config import Config, extract_config_from_md
import mmg.api as mmg
base_md: str = """
<!---------------------------->
<!-- multilingual suffix: A, B, C -->
<!-- no suffix: C -->
<!---------------------------->
<!-- [A] -->
# Sample Document A
Hello, A!
<!-- [B] -->
# Sample Document B
Hello, B!
<!-- [C] -->
# Sample Document C
Hello, C!
<!-- [common] -->
Thank you for using mmg!
"""
def main(fake: bool = True):
converted_mds: Dict[str, str] = mmg.convert(base_md)
base_doc: List[str] = base_md.splitlines()
cfg: Config = extract_config_from_md(base_doc)
if fake:
print(f"Fake mode: skip saving file. Detected tags: {converted_mds.keys()}")
return
for tag, txt in converted_mds.items():
file_name = f"./README.{tag}.md" if tag != cfg.no_suffix else "./README.md"
file_name = os.path.join(os.path.dirname(__file__), file_name)
file_name = os.path.abspath(file_name)
with open(file_name, "w", encoding="utf-8") as f:
f.write(txt)
if __name__ == "__main__":
main(fake=False)
No output text.
api_example_set_cfg.py
Config
オブジェクトを扱う例です。
See on GitHub
from mmg.api import Config
def main():
cfg1 = Config()
cfg1.lang_tags = ["en", "fr", "kr", "jp"] # Language tags are also used as suffixes.
cfg1.no_suffix = "en" # Used only when saving files.
print(f"cfg1: {cfg1}")
cfg2 = Config(
lang_tags=["en", "fr", "kr", "jp"],
no_suffix="en",
)
print(f"cfg2: {cfg2}")
if __name__ == "__main__":
main()
Output Text
cfg1: Config(lang_tags=['en', 'fr', 'kr', 'jp'], no_suffix='en')
cfg2: Config(lang_tags=['en', 'fr', 'kr', 'jp'], no_suffix='en')