7rikazhexde’s tech log

技術的な興味関心、備忘録、アウトプットなどを書いています。

DynamoDB localをWindowsで使用する方法

はじめに

  • WindowsでDynamoDB localを使用する方法を調べたので備忘録として記事にしました。
  • WindowsWindows(WSL2)の例を紹介します。
  • テーブル操作はWindows(DynamoDB)← Windows(WSL2:Python)の例を紹介します。
  • dockerによる利用は記載しません。

DynamoDB local v2.x のダウンロード

  • .zipをDLして展開する
  • DynamoDBLocal.jarの保存先に移動してpowershellで以下のコマンドを実行する
java -D"java.library.path=./DynamoDBLocal_lib" -jar DynamoDBLocal.jar
Initializing DynamoDB Local with the following configuration:
Port:   8000
InMemory:       false
DbPath: null
SharedDb:       false
shouldDelayTransientStatuses:   false
CorsParams:     null

AWS CLIインストール

https://aws.amazon.com/jp/cli/ にアクセスし、右側のDLリンクをクリックする。

Windows
64 ビットWindows インストーラをダウンロードし、実行します。

dynamodb-adminを使用するためには認証情報の設定が必要です。詳細は以下を確認してください。

7rikazhexde.github.io

テーブルの作成、書き込み

以下を確認してください。 Windows(DynamoDB)← Windows(WSL2:Python)の場合はendpoint_urlWindows側のIPアドレスを設定する必要があるので注意してください。

7rikazhexde.github.io

Node.js(npm)をインストールする

npmでdynamodb-localをインストールするため、未インストールの場合はNode.jsの公式ページからDL、または、nodenv等でインストールしてください。

https://nodejs.org/ja/downloadnodejs.org

github.com

Windows(WSL2)向け

dynamodb-adminをインストールして起動する

npm install -g dynamodb-admin
DYNAMO_ENDPOINT=http://[dynamodb-localを起動しているPCのアドレス]:8000 dynamodb-admin

  database endpoint:    http://[dynamodb-localを起動しているPCのアドレス]:8000
  region:               [aws configureで設定したregion]
  accessKey:            [aws configureで設定したaccessKey]

  dynamodb-admin listening on http://:::8001 (alternatively http://0.0.0.0:8001)
(node:44479) NOTE: We are formalizing our plans to enter AWS SDK for JavaScript (v2) into maintenance mode in 2023.

Please migrate your code to use AWS SDK for JavaScript (v3).
For more information, check the migration guide at https://a.co/7PzMCcy
(Use `node --trace-warnings ...` to show where the warning was created)

http://localhost:8001にアクセスすることでテーブルを確認することができます。

Windows向け

dynamodb-adminをインストールして起動する

powershellで以下を実行します。

npm install -g dynamodb-admin

npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.

added 125 packages in 21s

21 packages are looking for funding
  run `npm fund` for details
npm notice
npm notice New major version of npm available! 9.8.1 -> 10.1.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.1.0
npm notice Run npm install -g npm@10.1.0 to update!
npm notice
set DYNAMO_ENDPOINT=http://localhost:8000
dynamodb-admin

  DYNAMO_ENDPOINT is not defined (using default of http://localhost:8000)
  database endpoint:    http://localhost:8000
  region:               [aws configureで設定したregion]
  accessKey:            [aws configureで設定したaccessKey]

  dynamodb-admin listening on http://:::8001 (alternatively http://0.0.0.0:8001)
(node:26076) NOTE: We are formalizing our plans to enter AWS SDK for JavaScript (v2) into maintenance mode in 2023.

Please migrate your code to use AWS SDK for JavaScript (v3).
For more information, check the migration guide at https://a.co/7PzMCcy
(Use `node --trace-warnings ...` to show where the warning was created)

http://localhost:8001にアクセスすることでテーブルを確認することができます。

以上です。

Markdownリンターのmarkdownlint-cli/markdownlint-cli2の情報とpre-commitフックの設定方法について

概要

qiitaの記事でvscode拡張機能markdownlintを使用していることに触れました。

qiita.com

GitHubのプロジェクトでは基本的にpre-commit hooksを使用してコミット前に文法や体裁をチェックしています。pre-commitスクリプトの作成とフックはpre-commitで管理しています。

また、マークダウン用のpre-commitフックとして、mdformatを使用しているのですが、markdownlintのフックとして、markdownlint-climarkdownlint-cli2というpre-commitフックがあることを知り試してみることにしました。

本記事はCLIツールの紹介と使い方についてまとめた記事になります。

注意事項

2023/09/22時点の情報です。
最新の情報はプロジェクトのGitHubページを確認してください。

個人的な見解

記事ではmarkdownlint-climarkdownlint-cli2を紹介しますが、 個人的にはvscode拡張(markdownlint)+pre-commitフック(markdownlint-cli)--fixオプションは指定しない(=修正まではしない)指定が良いと思います。

理由はvscode拡張のmardkdownlintの警告に対してフォーマットした場合とmarkdownlint-climarkdownlint-cli2でそれぞれフォーマットとした場合とで異なる結果になるためです。

警告を解消しても意図した変換(修正)にならないのであれば意味がありません。 そのため、文法や体裁のチェックまで実行することが良いと個人的には思います。

pre-commitフックでmarkdownlint-cli/cli2を使用する意味

markdownlint-clivscode機能拡張であり、タブ表示したファイルのフォーマットチェックとファイル保存時に自動でフォーマットすることができます。

一方でpre-commitフックでは、設定上は全マークダウンファイルをチェック対象にすることができます。 基本的にファイル保存すると思うのでpre-commitフックの設定はしなくても良いですが、個人的にはタブ表示以外のファイルも文法や体裁をチェックしたほうが良いと思います。

markdownlintについて

以下記事でまとめていますので参照ください。

7rikazhexde.github.io

簡単にまとめると以下です。

  • フォーマットルール が存在する
  • vscode機能拡張をインストール、設定するとファイル保存時にフォーマット処理を実行できる
  • configファイルを設定すればルール適用有無を変更できる

markdownlint-cliについて

MarkdownLintのコマンドラインインターフェイス(CLI)です。 使い方はUsageを確認してください。

markdownlint-cli2について

markdownlint-cli2はmarkdownlint-cliと基本的に同じ機能をサポートしており、並行処理により高速化を実現していると記載されています。

参考情報

pre-commitフック設定(.pre-commit-config.yaml)

設定はmkdocsで作成した静的サイトのコンテンツの元になるMarkdownファイルに適用した例で説明します。

github.com

まずconfigファイル(.markdownlint.jsonc)について説明します。configファイルはmarkdownファイルに対して、フォーマットのルール適用を有無を指定できます。コマンド実行では--config`で指定することでconfigファイルを指定することができます。

以下の設定ではREADME.mddocs`ディレクトリ以下のすべてのMarkdownファイルに対してconfigファイル指定でフォーマットチェックを実行する方法です。

markdownlint-cli

  - repo: https://github.com/igorshubovych/markdownlint-cli
    rev: v0.36.0
    hooks:
      - id: markdownlint
        args:
          [
            #"--fix", # フォーマット指定は無効にする。
            "--config",
            ".markdownlint.jsonc",
            "README.md",
            "docs/**/*.md",
          ]

markdownlint-cli2

  - repo: https://github.com/DavidAnson/markdownlint-cli2
    rev: v0.10.0
    hooks:
      - id: markdownlint-cli2
        args:
          [
            #"--fix", # フォーマット指定は無効にする。
            "--config",
            ".markdownlint.jsonc",
            "README.md",
            "docs/**/*.md",
          ]

補足

markdownlint-cli2にはmarkdownlint-cli2-fixというコマンドも可能ですが非推奨のようです。markdownlint-cli2-fixはmarkdownlint-cli2の--fixオプション指定と同じとのことです。

Deprecated

The following command behaves similarly, defaulting the fix property to true:

markdownlint-cli2-fix "*/.md" "#node_modules" Otherwise, markdownlint-cli2-fix behaves the same as markdownlint-cli2.

構成ファイル(.markdownlint.jsonc)

いくつか除外するルールを設定しています。 その他の例はGitHub記載の .markdownlint.jsonc, .markdownlint.yamlを確認してください。 markdownlint-cliではコンフィグファイルにjson,yamlをサポートし、markdownlint-cli2ではその他のファイルもサポートしています。(詳細)

{
  // Reference : https://github.com/markdownlint/markdownlint/blob/main/docs/creating_rules.md

  // Unordered list indentation / 番号なしリストのインデント
  //"MD007": false,

  // Trailing spaces / 末尾のスペース
  //"MD009": false,

  // Hard tabs / インデントのタブ
  //"MD010": false,

  // Line length / 行の長さ
  "MD013": false,

  // Dollar signs used before commands without showing output / コマンドの前にドル記号を使用して出力を表示しない
  // コードブロックでコマンドライン(bash/zsh)を書く場合、コピー&ペーストを考慮すると、
  // "$"や"%"は表示しない方が良いので警告を有効にする。(見た目重視であれば無効にする。)
  //"MD014": false,

  // Multiple headings with the same content / 同じ内容の複数の見出し
  "MD024": false,

  // Multiple top-level headings in the same document / 同じドキュメント内の複数のトップレベルの見出し
  "MD025": false,

  // Trailing punctuation in heading / 見出しの末尾の句読点
  "MD026": false,

  // Inline HTML / raw HTMLの記入
  // MD009を無効にする変わりに改行に<br/>を使用するため無効にする。
  "MD033": false

  // Fenced code blocks should have a language specified / フェンスされたコードブロックには言語を指定する必要があります
  // 言語に問わずハイライトした方が良いので有効にする。
  //"MD040": false
}

実行結果例

MD012の警告の例で実行します。

MD012警告例

エラーが複数表示されていますが、正しくエラーが指摘されています。

markdownlint-cli

% poetry run pre-commit run --all-files

markdownlint.............................................................Failed
- hook id: markdownlint
- exit code: 1

docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]

markdownlint-cli2

% poetry run pre-commit run --all-files

markdownlint-cli2........................................................Failed
- hook id: markdownlint-cli2
- exit code: 1

markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/markdown/index.md docs/application/vscode/index.en.md docs/application/vscode/index.md docs/application/workflowy/workflowy-tips.md docs/programming-language/index.en.md docs/sample/sample-tips.md docs/application/vscode/setting-tips.md docs/programming-language/python/pymysql-tips.en.md docs/markdown/markdown-tips.en.md docs/command-line-tool/vi/vi-tips.en.md docs/application/inkscape/inkscape-tips.en.md docs/sample/sample-tips.en.md docs/programming-language/applescript/index.en.md docs/raspberrypi/index.md docs/application/index.md
Linting: 59 file(s)
Summary: 2 error(s)
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]
markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/programming-language/python/pymysql-tips.md docs/command-line-tool/index.md docs/sample/index.md docs/application/obsidian/obsidian-tips.md docs/database/mariadb-tips.md README.md docs/command-line-tool/index.en.md docs/database/index.md docs/programming-language/python/pre-commit-tips.md docs/programming-language/python/post-commit-tips.md docs/programming-language/python/mdformat-tips.md docs/application/index.en.md docs/application/vscode/setting-tips.en.md docs/application/vscode/extention-tips.en.md docs/programming-language/python/dash-plotly-tips.en.md
Linting: 59 file(s)
Summary: 2 error(s)
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]
markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/programming-language/applescript/example.md docs/raspberrypi/index.en.md docs/programming-language/python/dash-plotly-tips.md docs/raspberrypi/raspberrypi-ubuntu-tips.md docs/programming-language/python/pre-commit-tips.en.md docs/database/mariadb-tips.en.md docs/application/inkscape/inkscape-tips.md docs/raspberrypi/raspberrypi-ubuntu-tips.en.md docs/index.en.md docs/command-line-tool/git/git-tips.md docs/programming-language/python/mkdocs-tips.en.md docs/sample/index.en.md docs/markdown/index.en.md docs/programming-language/python/mkdocs-tips.md docs/application/obsidian/obsidian-tips.en.md
Linting: 59 file(s)
Summary: 2 error(s)
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]
markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/programming-language/python/post-commit-tips.en.md docs/index.md docs/programming-language/python/index.md docs/application/vscode/extention-tips.md docs/programming-language/applescript/index.md docs/command-line-tool/git/git-tips.en.md docs/programming-language/applescript/example.en.md docs/programming-language/python/mdformat-tips.en.md docs/database/index.en.md docs/command-line-tool/vi/vi-tips.md docs/application/workflowy/workflowy-tips.en.md docs/programming-language/python/index.en.md docs/markdown/markdown-tips.md docs/programming-language/index.md
Linting: 59 file(s)
Summary: 2 error(s)
docs/application/inkscape/inkscape-tips.en.md:14 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2]
docs/application/inkscape/inkscape-tips.en.md:15 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 3]

実行結果(--fix指定)

「個人的な見解」で説明しましたが、vscode拡張(markdownlint)では14,15行目が削除されるような修正がされるのですが、markdownlint-cli/cli2では変換結果が異なります。(cli/cli2でも変換結果が異なります。)

vscode拡張(markdownlint)と同じ修正結果もあるのですが、他にも異なる結果が見受けられました。これでは修正作業にも時間がかかってしまいます。そのため、エラーチェックまでに--fix指定はせずに実行すべきという意見です。

markdownlint-cli

MD012_markdown-cli_fix

markdownlint.............................................................Failed
- hook id: markdownlint
- files were modified by this hook

markdownlint-cli2

MD012_markdown-cli2_fix

markdownlint-cli2........................................................Failed
- hook id: markdownlint-cli2
- files were modified by this hook

markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/markdown/index.md docs/application/vscode/index.en.md docs/application/vscode/index.md docs/application/workflowy/workflowy-tips.md docs/programming-language/index.en.md docs/sample/sample-tips.md docs/application/vscode/setting-tips.md docs/programming-language/python/pymysql-tips.en.md docs/markdown/markdown-tips.en.md docs/command-line-tool/vi/vi-tips.en.md docs/application/inkscape/inkscape-tips.en.md docs/sample/sample-tips.en.md docs/programming-language/applescript/index.en.md docs/raspberrypi/index.md docs/application/index.md
Linting: 59 file(s)
Summary: 0 error(s)
markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/programming-language/python/pymysql-tips.md docs/command-line-tool/index.md docs/sample/index.md docs/application/obsidian/obsidian-tips.md docs/database/mariadb-tips.md README.md docs/command-line-tool/index.en.md docs/database/index.md docs/programming-language/python/pre-commit-tips.md docs/programming-language/python/post-commit-tips.md docs/programming-language/python/mdformat-tips.md docs/application/index.en.md docs/application/vscode/setting-tips.en.md docs/application/vscode/extention-tips.en.md docs/programming-language/python/dash-plotly-tips.en.md
Linting: 59 file(s)
Summary: 0 error(s)
markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/programming-language/applescript/example.md docs/raspberrypi/index.en.md docs/programming-language/python/dash-plotly-tips.md docs/raspberrypi/raspberrypi-ubuntu-tips.md docs/programming-language/python/pre-commit-tips.en.md docs/database/mariadb-tips.en.md docs/application/inkscape/inkscape-tips.md docs/raspberrypi/raspberrypi-ubuntu-tips.en.md docs/index.en.md docs/command-line-tool/git/git-tips.md docs/programming-language/python/mkdocs-tips.en.md docs/sample/index.en.md docs/markdown/index.en.md docs/programming-language/python/mkdocs-tips.md docs/application/obsidian/obsidian-tips.en.md
Linting: 59 file(s)
Summary: 0 error(s)
markdownlint-cli2 v0.10.0 (markdownlint v0.31.1)
Finding: README.md docs/**/*.md docs/programming-language/python/post-commit-tips.en.md docs/index.md docs/programming-language/python/index.md docs/application/vscode/extention-tips.md docs/programming-language/applescript/index.md docs/command-line-tool/git/git-tips.en.md docs/programming-language/applescript/example.en.md docs/programming-language/python/mdformat-tips.en.md docs/database/index.en.md docs/command-line-tool/vi/vi-tips.md docs/application/workflowy/workflowy-tips.en.md docs/programming-language/python/index.en.md docs/markdown/markdown-tips.md docs/programming-language/index.md
Linting: 59 file(s)
Summary: 0 error(s)

補足: mdformatでチェックまで実行する方法

上記変換差異はmdformatにも言えることです。 mdformatではチェックまで実行する場合は引数に--checkを指定することで有効にできます。

まとめ

Markdownリンターのmarkdownlint-cli/markdownlint-cli2の情報とpre-commitフックの設定方法について紹介しました。

mdformatを使用していますが、処理の速度的にはmarkdownlint-cli2 < mdformat < markdownlint-cliという印象です。

それぞれフォーマットまで使用できた方が良いですが、意図した変換にならないこともあるため注意は必要です。 ただ、便利なツールではあるので、コミット時の差分チェックと合わせて利用することでファイル管理がしやすくなると思います。

以上です。

【Twitter Cards / OGP】mdformatでYAML Frontmatterが変換される現象と回避方法について

経緯

以前、以下の記事でmkdocsで作成したドキュメントページをpre-commitmdformatを使用した際にmkdocs(Admonitions)が意図した表示にならない問題と解決方法について投稿しました。

7rikazhexde-techlog.hatenablog.com

今回はtwitter cardに対応するためにコジオン・チェスさんの記事を参考に、descriptionimageのメタ情報を <meta> タグとして出力されるように設定したのですが、mdformatfrontmatter部分が変換されてしまい、<meta> タグとして機能しない現象になりました。

kojion.github.io

<meta>タグをHTMLに反映するためにはmetaプラグインYAML Frontmatterで作成されたmarkdownファイルが必要1なのですが、
調べるとYAML Frontmatter用のプラグインを使用することで回避することができました。

本記事ではmdformatでYAML Frontmatterが変換される現象と回避方法を備忘録としてまとめた内容になります。

問題の現象について

変換前

---
description: Inkscape tips
image: application/inkscape/images/inkscape.png
---

# Inkscape tips

変換後(意図しない変換)

______________________________________________________________________

## description: Inkscape tips image: application/inkscape/images/inkscape.png

# Inkscape tips

解決方法

poetryまたは、pipmdformat-frontmatterをインストールし、.pre-commit-config.yamlに設定します。2,3

これでpre-commitmdformat実行時に変換されなくなります。4

  - repo: https://github.com/executablebooks/mdformat
    rev: 0.7.16
    hooks:
      - id: mdformat
        additional_dependencies:
          - mdformat-admon
          - mdformat-footnote
          - mdformat-frontmatter # 追加

pypi.org

まとめ

twitter card用にYAML Frontmatterで作成されたmarkdownファイルが変換される現象と回避方法を紹介しました。 これは、はてなブログ等のブログで表示する際に必要なOGPを設定するケースでも同様であり、他のSSGプロジェクトでも同様の現象は起きると思います。

madformatを使用する際は合わせてmdformat-frontmatterをインストールすることをお勧めします。

以上です。


  1. metaプラグインYAML Frontmatterでメタ情報をmarkdownファイルに記入することで、nav毎に作成されるhtmlに反映されるようになります。YAML Frontmatterについては下記を参照してください。squidfunk.github.iojekyllrb-ja.github.io
  2. mdformat-frontmatterはmdformatプラグインですが、プラグインはpre-commit hookで使用する前提のため.pre-commit-config.yamlに追加します。
  3. pre-commitでの使用方法https://mdformat.readthedocs.io/en/stable/users/installation_and_usage.html#usage-as-a-pre-commit-hook
  4. poetry run mdformat [ファイル名]では変換されるので注意してください。pre-commitのみサポートしています。

Material for Mkdocsでgitリポジトリの追加で最新のリリース情報(タグ)を表示する方法

経緯

Material for Mkdocsではヘッダーにgitリポジトリの情報を表示することができます。

squidfunk.github.io

公式ドキュメントを見るとわかりますが、latest releasestars,forksの情報が表示されていますが、私の環境ではリポジトリの設定をしてもlatest releaseの情報は表示されませんでした。

調べると公式ドキュメントの脚注に以下の記載がありました。つまり、GitHubでリリースの作成を実行しなければ取得、表示はできないとのことでした。(9.2.8時点)

Unfortunately, GitHub only provides an API endpoint to obtain the latest release - not the latest tag. Thus, make sure to create a release (not pre-release) for the latest tag you want to display next to the number of stars and forks.

リポジトリではタグは作成していましたが、リリースの作成はしていませんでした。

本記事では確認した内容を備忘録としてまとめた内容になります。

表示内容

対象のURLは下記です。
7rikazhexde.github.io

リリース作成前後の表示は下記の通りです。
リリースの作成後はリリース情報(タグ)が表示されていることを確認できました。

リリース作成前

repo_url_no_release

リリース作成後

repo_url_released

補足: REST APIによる確認

脚注ではAPI Endpointで取得するとありますが、GitHub API V3(REST)で確認したところ確かに取得はできませんでした。(/releasesでも同様です。)
mkdocs-materialでどういう仕様でリリース情報を取得しているかは未確認ですが、下記の通りリリースの作成後は取得できました。

リリース作成前

% curl -s -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/7rikazhexde/dev-insights-tips/releases/latest
{
  "message": "Not Found",
  "documentation_url": "https://docs.github.com/rest/releases/releases#get-the-latest-release"
}

リリース作成後

% curl -s -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/7rikazhexde/dev-insights-tips/releases/latest
{
  "url": "https://api.github.com/repos/7rikazhexde/dev-insights-tips/releases/120650944",
  "assets_url": "https://api.github.com/repos/7rikazhexde/dev-insights-tips/releases/120650944/assets",
  "upload_url": "https://uploads.github.com/repos/7rikazhexde/dev-insights-tips/releases/120650944/assets{?name,label}",
  "html_url": "https://github.com/7rikazhexde/dev-insights-tips/releases/tag/v0.1.42",
  "id": 120650944,
  "author": {
    "login": "7rikazhexde",
    "id": 33836132,
    "node_id": "MDQ6VXNlcjMzODM2MTMy",
    "avatar_url": "https://avatars.githubusercontent.com/u/33836132?v=4",
    "gravatar_id": "",
    "url": "https://api.github.com/users/7rikazhexde",
    "html_url": "https://github.com/7rikazhexde",
    "followers_url": "https://api.github.com/users/7rikazhexde/followers",
    "following_url": "https://api.github.com/users/7rikazhexde/following{/other_user}",
    "gists_url": "https://api.github.com/users/7rikazhexde/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/7rikazhexde/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/7rikazhexde/subscriptions",
    "organizations_url": "https://api.github.com/users/7rikazhexde/orgs",
    "repos_url": "https://api.github.com/users/7rikazhexde/repos",
    "events_url": "https://api.github.com/users/7rikazhexde/events{/privacy}",
    "received_events_url": "https://api.github.com/users/7rikazhexde/received_events",
    "type": "User",
    "site_admin": false
  },
  "node_id": "RE_kwDOJwRtyc4HMPzA",
  "tag_name": "v0.1.42",
  "target_commitish": "main",
  "name": "dev-insights-tips-v0.1.42",
  "draft": false,
  "prerelease": false,
  "created_at": "2023-09-09T16:09:49Z",
  "published_at": "2023-09-11T14:12:39Z",
  "assets": [

  ],
  "tarball_url": "https://api.github.com/repos/7rikazhexde/dev-insights-tips/tarball/v0.1.42",
  "zipball_url": "https://api.github.com/repos/7rikazhexde/dev-insights-tips/zipball/v0.1.42",
  "body": ""
}

手順

リリースの作成(GitHub)

Create a new release > Tags > タグ選択 / Create release > Release title入力 > Publish release

または、

Create a new release > Release > Chosen a tag / タグ選択 > Release title入力 > Publish release

リポジトリ設定

mkdocs.ymlの設定内容と合わせて記載します。(v1.42.0現在)

repo_name: 7rikazhexde/dev-insights-tips
repo_url: https://github.com/7rikazhexde/dev-insights-tips

theme:
  icon:
    repo: fontawesome/brands/github

まとめ

Material for Mkdocsでgitリポジトリの追加で最新のリリース情報(タグ)を表示する方法について紹介しました。 正直言われなければ気づかない部分ですが、タグ管理している場合はせっかくなので表示しましょう。

以上です。

【エラー解決方法】MkDocsで「mkdocs gh-deploy --force」を実行すると、「ERROR - Config value 'plugins': Plugin 'i18n' option 'languages': Expected a list of items, but a <class 'dict'> was given.」が発生し、GitHub Pagesへのデプロイに失敗する。

更新情報

20230902

下記手順を確認したところ、プロジェクト直下のindex.en.mdを取得できず(デフォルトは日本語)に
404エラーになる現象を確認しています。
直下以下のフォルダ内のファイルの言語変更は問題なく動作します。 同様の現象が発生している場合は、バージョン固定(ver0.56)で対応するのが良いと思います。

20230923

mkdocs-material 9.1.16に更新したところ以下のWARNINGが表示されました。

WARNING - Language en is not supported by mkdocs-material==None, not setting the 'theme.language' option
WARNING - Language ja is not supported by mkdocs-material==None, not setting the 'theme.language' option

mkdocs.ymltheme.languageで設定していましたが、pluginsi18nを設定しても言語セレクタが表示されなくなりました。

theme:
  language: ja

具体的には、option-docs_structure記載の通り、docs_structure: folderにしてドキュメント記載のフォルダ構成にする必要があります。

plugins:
  - i18n:
    docs_structure: folder

結論から言えば、mkdocs-static-i18n 1.0.6で後述する1.0.0以降のi18nプラグイン記述に変更すれば機能します。

the-folder-docs-structureでフォルダ構成にすれば機能しました。GitHub Pagesへのデプロイも問題ありませんでした。

the-suffix-structureでもlocalでのビルドでは問題ありませんでした。ただし、デプロイは未確認です。

概要

私は以下の仕様で、Material for MkDocsで作成したドキュメントをGitHub Actionsを使用してGitHub Pagesへデプロイ、および、Webサイト(Dev Insights Tips)として公開しています。

しかし、2023/09/01にデプロイしたところ、mkdocs gh-deploy --forceで表題のエラーになりました。調べるとmkdocs-static-i18nの仕様とのことで、解決方法が公開されていました。

本記事ではエラーと解決方法について紹介します。

GitHub Actionの実行結果とエラー内容

使用中のYAMLファイル

# GitHub Actions to automate deployment of project documentation
# Reference: https://squidfunk.github.io/mkdocs-material/publishing-your-site/?h=git+hub#github-pages

name: ci
on:
  push:
    branches:
      - main

env:
  cache_id: ""
permissions:
  contents: write

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: 3.x
      - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
      - uses: actions/cache@v3
        with:
          key: mkdocs-material-${{ env.cache_id }}
          path: .cache
          restore-keys: |
            mkdocs-material-
      - run: pip install mkdocs-material mkdocs-static-i18n pygments plantuml-markdown
      - run: mkdocs gh-deploy --force

Runアクション(pip install)

mkdocs-static-i18nは2023/09/01時点で最新のver1.0.2がインストールされていました。

# 省略
Successfully built paginate readtime
Installing collected packages: paginate, watchdog, urllib3, soupsieve, six, regex, pyyaml, pygments, platformdirs, pathspec, packaging, mkdocs-material-extensions, mergedeep, MarkupSafe, markdown2, markdown, lxml, idna, cssselect, colorama, click, charset-normalizer, certifi, babel, requests, pyyaml-env-tag, python-dateutil, pyquery, pymdown-extensions, jinja2, beautifulsoup4, readtime, plantuml-markdown, ghp-import, mkdocs, mkdocs-static-i18n, mkdocs-material
Successfully installed MarkupSafe-2.1.3 babel-2.12.1 beautifulsoup4-4.12.2 certifi-2023.7.22 charset-normalizer-3.2.0 click-8.1.7 colorama-0.4.6 cssselect-1.2.0 ghp-import-2.1.0 idna-3.4 jinja2-3.1.2 lxml-4.9.3 markdown-3.4.4 markdown2-2.4.10 mergedeep-1.3.4 mkdocs-1.5.2 mkdocs-material-9.2.6 mkdocs-material-extensions-1.1.1 mkdocs-static-i18n-1.0.2 packaging-23.1 paginate-0.5.6 pathspec-0.11.2 plantuml-markdown-3.9.2 platformdirs-3.10.0 pygments-2.16.1 pymdown-extensions-10.2.1 pyquery-2.0.0 python-dateutil-2.8.2 pyyaml-6.0.1 pyyaml-env-tag-0.1 readtime-3.0.0 regex-2023.8.8 requests-2.31.0 six-1.16.0 soupsieve-2.4.1 urllib3-2.0.4 watchdog-3.0.0

Notice:  A new release of pip is available: 23.1.2 -> 23.2.1
Notice:  To update, run: pip install --upgrade pip

Runアクション(mkdocs gh-deploy --force)

以下ログの通り、「ERROR - Config value 'plugins': Plugin 'i18n' option 'languages': Expected a list of items, but a was given.」が発生しました。

Run mkdocs gh-deploy --force
  mkdocs gh-deploy --force
  shell: /usr/bin/bash -e {0}
  env:
    cache_id: 35
    pythonLocation: /opt/hostedtoolcache/Python/3.11.4/x64
    PKG_CONFIG_PATH: /opt/hostedtoolcache/Python/3.11.4/x64/lib/pkgconfig
    Python_ROOT_DIR: /opt/hostedtoolcache/Python/3.11.4/x64
    Python2_ROOT_DIR: /opt/hostedtoolcache/Python/3.11.4/x64
    Python3_ROOT_DIR: /opt/hostedtoolcache/Python/3.11.4/x64
    LD_LIBRARY_PATH: /opt/hostedtoolcache/Python/3.11.4/x64/lib
ERROR   -  Config value 'plugins': Plugin 'i18n' option 'languages': Expected a list of items, but a <class 'dict'> was given.

Aborted with 1 configuration errors!
Error: Process completed with exit code 1.

エラー内容

エラーとして、ERROR - Config value 'plugins': Plugin 'i18n' option 'languages': Expected a list of items, but a <class 'dict'> was given.が出力されています。 調べると同様のエラーは発生しており、下記issueが登録されていました。

github.com

エラー解決方法

Contributerからの回答は以下の通りです。

The new version 1.0.0 of the plugin requires a different configuration setup. There is a migration tool provided:

https://ultrabug.github.io/mkdocs-static-i18n/setup/upgrading-to-1/

You can also modify your ci.yml to stick to the older version for now if you don't require new features:

Change mkdocs-static-i18n \ to mkdocs-static-i18n==0.56 \ as per the version history:

https://pypi.org/project/mkdocs-static-i18n/#history

つまり、ver1.0.0から機能追加により異なる設定が必要になる。ただし、新機能を必要としない場合はver0.56を明示的に指定すれば良いとのことでした。

具体的な機能追加の詳細は確認できなかったのですが、個人的にはver0.56を使用し続けるのは、バグや機能の観点で避けたいので下記記載のスクリプトを使用することにしました。

ultrabug.github.io

まず、私の環境ではバージョン管理にPoetryを使用していますが、mkdocs-static-i18nのバージョンはver0.56だったので更新しました。

変更前のpyproject.toml
[tool.poetry.dependencies]
mdformat = "^0.7.16"
mkdocs-material = "^9.1.16"
mkdocs-static-i18n = "^0.56"
plantuml-markdown = "^3.9.2"
pre-commit = "^3.3.3"
pygments = "^2.16.1"
python = "^3.10"
tomlkit = "^0.11.8"
パッケージのバージョン確認(poetry show)
$ poetry show
mergedeep                  1.3.4     A deep merge function for 🐍.
mkdocs                     1.5.2     Project documentation with Markdown.
mkdocs-material            9.2.6     Documentation that simply works
mkdocs-material-extensions 1.1.1     Extension pack for Python Markdown and MkDocs Material.
mkdocs-static-i18n         0.56      MkDocs i18n plugin using static translation markdown files
mypy                       1.5.1     Optional static typing for Python
変更後のpyproject.toml

mkdocs-static-i18nのバージョンを1.0.0以上にするため^1.0.0とします。2

[tool.poetry.dependencies]
mdformat = "^0.7.16"
mkdocs-material = "^9.1.16"
mkdocs-static-i18n = "^1.0.0" # 変更
plantuml-markdown = "^3.9.2"
pre-commit = "^3.3.3"
pygments = "^2.16.1"
python = "^3.10"
tomlkit = "^0.11.8"
mkdocs-static-i18nの更新
$ poetry update mkdocs-static-i18n
Updating dependencies
Resolving dependencies... (1.2s)

Package operations: 0 installs, 1 update, 0 removals

  • Updating mkdocs-static-i18n (0.56 -> 1.0.2)

Writing lock file
更新後のビルド確認

バージョン更新後の動作確認のためビルドコマンドを実行します。 実行するとビルドコマンドでもエラーになることを確認しました。

$ poetry run mkdocs build -c
ERROR   -  Config value 'plugins': Plugin 'i18n' option 'languages': Expected a list of items, but a
           <class 'dict'> was given.
mkdocs.ymlの更新

config_update_to_v1.pyを使用してmkdocs.yamlを更新します。 まずはファイルをプロジェクト直下に移動してスクリプトを実行します。 実行すると私の環境では以下の内容が出力されました。

$ poetry run python config_update_to_v1.py ./mkdocs.yml
please update your mkdocs plugins.i18n configuration to:
----------
i18n:
  docs_structure: suffix
  fallback_to_default: true
  languages:
    - build: true
      default: false
      locale: en
      name: English
      nav_translations:
        Home: Home
    - build: true
      default: true
      locale: ja
      name: 日本語
  reconfigure_material: true
  reconfigure_search: true

記載の通り、上記内容をi18n configurationに反映し、以下のように変更しました。

mkdocs.yml / plugins差分

再ビルドでWARNING

再度、poetry run mkdocs build -c実行するとを実行すると以下のWARNING(一部)が表示されました。

WARNING -  A relative path to 'application/index.ja.md' is included in the 'nav' configuration, which is not found in the
           documentation files.

これは、navにdocs以下に格納されるja.mdで指定されたパスのファイルがないということですが、ファイルは存在し、そもそも、ver0.56では動作していました。

調べると、記法は以下の公式ドキュメントに記載がありますが、「The suffix docs structure (default)」と「The folder docs structure」の2種類があります。

私は「The suffix docs structure (default)」を使用していましたが、結論から言えば、ver1.0.0以降ではdefault指定の言語は.<language>を付けない、つまり、index.jp.mdではなく、index.mdにする必要があるようです。3

ultrabug.github.io

最終的にファイルおよび、コードを以下(一部)のように変更したところ、warningは発生せずに起動できました。

mkdocs.yml / nav差分

まとめ

MkDocsで「mkdocs gh-deploy --force」を実行時に、「ERROR - Config value 'plugins': Plugin 'i18n' option 'languages': Expected a list of items, but a was given.」が発生し、GitHub Pagesへのデプロイに失敗することについて、エラー内容と解決方法について紹介しました。

正直言えば、今後もバージョンアップにより仕様が変わる可能性はあるため、どこまで参考になるかわかりませんが、どなたかの参考になれば幸いです。 もし、参考になれば「はてなスター」を付けてもらえると励みになりますのでよろしくお願いします。

また、今回、GitHub Actionをパッケージのインストール指定をpipから、poetryで実行する形式(参考4)に変更することを考えました。 ただ、issue観点で公式のpip版のデプロイ手順を使うユーザーが多数いると思うので、しばらくは、pip形式のまま運用することにしました。どこかのタイミングではlocalとremoteの設定を揃えることを再検討するかもしれません。5

以上です。


  1. Material for MkDocs公式 / publishing-your-site
    squidfunk.github.io
    公開手順は下記記事でも紹介しています。
    7rikazhexde-techlog.hatenablog.com
  2. 参考 [tool.poetry.dependencies]のバージョン記載方法 python-poetry.org
  3. あくまで個人見解なので、ご注意ください。また、「The folder docs structure」は未確認です。6
  4. 参考までに別プロジェクトのGitHub Actionの例を記載します。このプロジェクトではpytest向けにpoetry installを使用した環境を使用しています。
    github.com
  5. v0.1.46でGitHub ActionをPoetryで管理する方法に変更しました。github.com
  6. 「20230923」で記載の通り、「The folder docs structure」でも成功しました。

PlantUMLでPDF出力できないのでInkscapeを使用して対応した話

はじめに

私はVSCode拡張機能PlantUMLを使用しています。

作成した.pumlファイルはPNGSVGにエクスポート(PlantUML: Export Current Diagram)できるため、プロジェクトではコードとセットでコミットしています。

大抵はPNGSVGをエクスポートできれば十分なのですが、PDFもエクスポートしたいことがありました。しかし、うまくいきませんでした。

これは後述しますが公式の仕様でした。解決方法もありましたが、結論から言えば解決方法ではPDFのエクスポートを有効にすることはできませんでした。

それで、結局はベクター画像を扱えるOSSベクターグラフィックエディタである、InkscapeでPDFファイルを作成することにしました。

本記事ではこれらの内容についてまとめたので紹介します。

PlantUMLのPDF出力エラーと解決方法

まず、実際に実行すると以下のエラーになりました。

ダイアグラム"packages_dlSubscanStakingRewardsHistory"にエラーが見つかりました
Warning: the font "Times" is not available, so "Lucida Bright" has been substituted, but may have unexpected appearance or behavor. Re-enable the "Times" font to remove this warning.
java.lang.ClassNotFoundException: org.apache.batik.apps.rasterizer.SVGConverter
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at net.sourceforge.plantuml.pdf.PdfConverter.convert(PdfConverter.java:59)
    at net.sourceforge.plantuml.UmlDiagram.exportDiagramInternalPdf(UmlDiagram.java:277)
    at net.sourceforge.plantuml.UmlDiagram.exportDiagramNow(UmlDiagram.java:132)
    at net.sourceforge.plantuml.AbstractPSystem.exportDiagram(AbstractPSystem.java:178)
    at net.sourceforge.plantuml.SourceStringReader.outputImage(SourceStringReader.java:172)
    at net.sourceforge.plantuml.Pipe.generateDiagram(Pipe.java:100)
    at net.sourceforge.plantuml.Pipe.managePipe(Pipe.java:92)
    at net.sourceforge.plantuml.Run.managePipe(Run.java:354)
    at net.sourceforge.plantuml.Run.main(Run.java:181)
Exception in thread "main" java.lang.UnsupportedOperationException
    at net.sourceforge.plantuml.pdf.PdfConverter.convert(PdfConverter.java:78)
    at net.sourceforge.plantuml.UmlDiagram.exportDiagramInternalPdf(UmlDiagram.java:277)
    at net.sourceforge.plantuml.UmlDiagram.exportDiagramNow(UmlDiagram.java:132)
    at net.sourceforge.plantuml.AbstractPSystem.exportDiagram(AbstractPSystem.java:178)
    at net.sourceforge.plantuml.SourceStringReader.outputImage(SourceStringReader.java:172)
    at net.sourceforge.plantuml.Pipe.generateDiagram(Pipe.java:100)
    at net.sourceforge.plantuml.Pipe.managePipe(Pipe.java:92)
    at net.sourceforge.plantuml.Run.managePipe(Run.java:354)
    at net.sourceforge.plantuml.Run.main(Run.java:181)

SVGをPDFにすればそれまでなのですが、何か納得がいかないので、解決方法がないのか?と思い調べることにしました。 すると、公式ページに以下の記載がありました。そもそも公式が簡単なことではないと言ってました。

ダイアグラムを直接PDF形式で出力する機能の要望が以前からありました。 しかし残念ながら、これは簡単なことではなく、いくつかの外部ライブラリ(BatikとFOP)も必要でした。
これは、plantuml.jarが大きくなりすぎないようにして、他の製品との統合を容易にしたいという要望に反するものです。

ただ、解決方法も記載されていました。

使用方法
デフォルト状態ではPDFの生成はできません。これでも、大多数のユーザのニーズを満たしているでしょう。

PDF機能を使いたい場合、以下のファイルをダウンロードする必要があります:
avalon-framework-4.2.0.jar
batik-all-1.7.jar
commons-io-1.3.1.jar
commons-logging-1.0.4.jar
fop.jar
xml-apis-ext-1.3.04.jar
xmlgraphics-commons-1.4.jar

これらのファイルをBatikとFOPのウェブサイトからダウンロードします。
テストを目的として、これらのファイルをまとめたzipがこちらにあります。
これらのファイルは、plantuml.jarと同じフォルダに配置する必要があります。
以上の準備を行うと、コマンドラインで-tpdfフラグが使えるようになります:

java -jar plantuml.jar -tpdf diagram.txt
もしくは、Antタスクでformat="pdf"が使えます:

<!-- task definition -->
<taskdef name="plantuml" classname="net.sourceforge.plantuml.ant.PlantUmlTask" classpath="plantuml.jar" />
<!-- process diagram.txt file -->
<target name="images">
<plantuml format="pdf">
<fileset file="diagram.txt" />
</plantuml>
</target>

よし、これでいけると思った矢先、zipのリンクをクリックしても一向にDLが開始されませんでした。 Chrome(F12)のConsoleを見ると以下のエラーが出てました。どうやらzipのリンクがHTTPでHTTPSではないのでエラーとしたというものでした。

Mixed Content: The site at 'https://plantuml.com/' was loaded over a secure connection, but the file at 'http://beta.plantuml.net/batikAndFop.zip' was loaded over an insecure connection. This file should be served over HTTPS. See https://blog.chromium.org/2020/02/protecting-users-from-insecure.html for more details.

ここまで来るとどうしようもないので、諦めて他の方法を考えました。

InkscapeSVGをPDF指定でエクスポートする

Inkscapeについては個人サイトのTips記事でまとめているので参照してください。(色々できるのでおすすめです。調べた機能については追記していく予定です。)

PDFを作成するには、PlantUML->Inkscapeとソフトを跨ぐ必要がありますが、Inkscape自体はCLIで実行できます。

Windowsでは未確認ですが、Macではbrewコマンド, Linux(WSL2)ではaptコマンドでインストールできます。

Mac

formulae.brew.sh

brew install --cask inkscape

Linux

inkscape.org

sudo apt-get install inkscape

SVGをPDF指定でエクスポートする方法

以下のコマンドで変換できます。

inkscape input.svg -o output.pdf

その他指定

以下のWIkiにまとめられています。

wiki.inkscape.org

まとめ

以下について紹介しました。

  • PlantUMLのPDL出力エラーと解決方法
  • InkscapeによるSVGからPDFへのエクスポート

上記方法は一度SVGのエクスポートが必要であり手間はあります。また、Inkscapeを使わなくてもSVGからPDFに変換するやり方は他にもあると思うので、それぞれの手段で最終的にPDFを保存できれば良いのかなと思います。

以上です。

mdformat + mkdocs(Admonitions)で意図した表示にならない現象と解決方法について

背景

以前以下の記事でMkdocsについて紹介しました。

7rikazhexde-techlog.hatenablog.com

記事の中では言及していなかったのですが、私はMarkdown用のフォーマッターとしてmdformatを使用しています。

公式ドキュメント:

mdformat.readthedocs.io

公開しているGitHub Pagesもその後更新を続けており、いくつか機能追加(多言語対応,クッキー設定,GA4対応,レイアウト変更)をしました。

mkdocsのレイアウトや設定についてはTipsページで紹介しようと考えています。

7rikazhexde.github.io

記事を更新する中で、大抵は公式のドキュメントを参照して解決できていたのですが、mdformat + mkdocs(Admonitions)の組み合わせでは意図した表示にすることができず、解決方法もすぐには見つけることができませんでした。

結論から言えばmdformatのプラグインを使用することで解決できたのですが、使用方法に指定がありました。

本記事では発生した現象と調査内容、解決方法について紹介します。

発生した現象について

mkdocsではadmonitionsという文書内にメモ、ヒント、警告などが目立つようなスタイルで表示してくれる機能です。サンプルとして以下を作成し、poetry run mkdocs serveすると、以下のような表示になります。

OKケース

!!! info
    - test1
    - test2

example-mkdocs-admonitions-ok

しかし、これにpoetry run mdformat .を実行すると以下のように変換されてしまいます。

NGケース

!!! info
\- test1
\- test2

example-mkdocs-admonitions-ng

解決方法

まず、mdformatのissueを調べました。すると以下のissueが見つかりました。

github.com

これは無視する対象をHTMLのコメントで囲むという方法ですが、2023/08/12時点で解決まで至っていません。

処理的には難しくはないため実際に作成することにしました。
型指定もなく上記例のみの確認のため参考にしないほうが良いと思いますが、やりたいことはできました。

def replace_mdformat_ignore(input_file, output_file, target_text):
    with open(input_file, "r", encoding="utf-8") as f:
        lines = f.readlines()

    converted_lines = []
    ignore_mode = False

    for line in lines:
        if "<!-- mdformat ignore start -->" in line:
            ignore_mode = True
            converted_lines.append(line)
        elif "<!-- mdformat ignore end -->" in line:
            ignore_mode = False
            converted_lines.append(line)
        elif ignore_mode:
            if line.strip() != "" and target_text not in line:
                line = line.replace(r"\-", "-")
                converted_lines.append("    " + line)
            else:
                converted_lines.append(line)
        else:
            converted_lines.append(line)

    with open(output_file, "w", encoding="utf-8") as f:
        f.writelines(converted_lines)


if __name__ == "__main__":
    target_text = "!!! info"

    input_file = "./docs/index.md"
    output_file = "./docs/index.md"
    replace_mdformat_ignore(input_file, output_file, target_text)

    input_file = "./docs/index.en.md"
    output_file = "./docs/index.en.md"
    replace_mdformat_ignore(input_file, output_file, target_text)

個別にスクリプトを作成する方法も良いですが、同じような問題に取り組んでいるプロジェクトがないかと思い調べることにしました。

すると、mdformatにはPlugins機能があることがわかりました。 そして、MkDocsのadmonitionsのためのmdformatプラグインとして、mdformat-admonというプラグインが存在することがわかりました。

github.com

admon以外にもmkdocsの記法に合わせたプラグインが複数存在していました。

github.com

注意点

公式ドキュメントのContributingに記載されていますが、プラグインを使用するためにはpre-commitで実行する必要があります。
mdformat単体では実行できないため注意が必要です。(もしかするとやり方があるかもしれませんが、確認できませんでした。)

使用方法

pre-commitについては割愛します。詳細は公式ドキュメントを参照ください。
.pre-commit-config.yamlは以下のように記載します。

repos:
  - repo: https://github.com/executablebooks/mdformat
    rev: 0.7.16
    hooks:
      - id: mdformat
        additional_dependencies:
          - mdformat-admon # ここに追加する

結果、NGケースのような結果にはならず期待する表示を確認することができました。

補足: 個別にmdformatを使用する場合

事前の動作確認でpre-commitで全てのフックを実行する場合は、poetry run pre-commit run --all-filesで実行できますが、個別に実行したい場合はpre-commitのhooksで指定したidを指定します。

1. pre-commitフックで個別にmdformatする場合

git add your_file.md  # 対象のMarkdownファイルをステージング
poetry run pre-commit run mdformat

2. 未ステージング状態のファイルに対してもフックを実行する場合

poetry run pre-commit run mdformat --all-files

補足: その他フォーマッターとの差異について

開発環境でVSCodeを使用している場合はmarkdown用のフォーマッターとして以下のようなものがあります。

  • Prettier - Code Fomatter
  • Markdown All in One
  • markdownlint

この中でデフォルトで問題なく動作するのはMarkdown All in Onemarkdownlintです。

Markdownファイルを全て選択(Ctrl + a) > 右クリック > ドキュメントのフォーマット…(2つある内の下で「…」の方) > Prettier - Code Fomatter

Prettierでは以下のように変換されてしまいます。

!!! info - test1 - test2

また、mdformatではプラグインが必要でしたが、Markdown All in Onemarkdownlintはデフォルトで上記NGケースのような変換にはなりませんでした。

まとめ

mdformat + mkdocs(Admonitions)で意図した表示にならない現象と解決方法について紹介しました。

mdformatは公式ドキュメントの通り、フォーマットの変更には慎重のようですが、pre-commitによるプラグインが複数存在するため、mkdocsに限らず、目的に応じてプラグインを使用することは有用だと思います。

Welcome to the mdformat developer docs! We’re excited you’re here and want to contribute. ✨

Please discuss new features in an issue before submitting a PR to make sure that the feature is wanted and will be merged. Note that mdformat is an opinionated tool that attempts to keep formatting style changing configuration to its minimum. New configuration will only be added for a very good reason and use case.

以上です。