こんにちは、CX事業本部 Delivery部の若槻です。
前回のエントリでマークダウンのmetadata(yaml header)をNode.jsでパースする方法を確認してみました。
今回は、GitHub Actionsで同様のことをしたくなったので、「Markdown Meta」というActionsを使ってパースする方法を確認してみました。
使ってみた
使い方は次のようになります。READMEのスニペットから若干変えています。toJSON(GitHub Actions Expressions)を使ってJsonオブジェクトをコンソール出力できるようにしています。
.github/workflows/parse-md.yml
name: Markdown Meta
on: push
jobs:
markdown-meta:
name: Markdown Meta
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Markdown Meta
uses: mheap/markdown-meta-action@v1
id: meta
with:
file: ./my-post.md
- name: Use the value
run:
echo "${{ toJSON(steps.meta.outputs) }}"
- name: Use the value2
run:
echo "${{ toJSON(steps.meta.outputs.title) }}"
パース対象のマークダウンドキュメントです。with
のfile
で指定したパスに配置します。
my-post.md
---
title: This is a test
description: Once upon a time...
---
# Title of my great post
Lorem ipsum dolor...
上記のGitHub Actionsを実行すると、yaml headerの文字列がパースできています。
ソースコードを見てみる
Markdown Metaのソースコードを見てみます。
マークダウンのmetadataのパースにはgray-matterを使っているようです。
index.js
const core = require("@actions/core");
const matter = require("gray-matter");
const slugify = require("slugify");
const fs = require("fs").promises;
async function action() {
const targetFile = core.getInput("file", { required: true });
const content = (await fs.readFile(targetFile)).toString();
const parsed = matter(content);
for (let k in parsed.data) {
core.setOutput(slugify(k, { lower: true, strict: true }), parsed.data[k]);
}
}
if (require.main === module) {
action();
}
module.exports = action;
Actionsの実行結果でWarningが出ているのはsetOutput
が使われているからですね。
現在はdeprecatedなので余裕がある方はPull Requestを出してみましょう。
以上