之前折騰 GtiHub Actions 想實現提交 issue 後將 issue 的內容生成一個 Markdown 文件提交到倉庫,從而實現自動發布到 GitHub Pages 的目的。倒是有一些現成的 Action,但無法完全滿足要求,所以自己嘗試寫一個 wayou/turn-issues-to-posts-action。
過程中發現因為 issue 的標題和正文是任意的,也就是以下兩部分:
github.event.issue.title
github.event.issue.body
分別通過環境變數 github.event.issue 獲取。
當然,做成 Action 後這些參數通過外面以參數方式傳遞,因為 Action 里無法獲取這些數據。
使用該 Action 的倉庫中,.github/workflows/main.yml 配置如下內容進行傳遞:
...
jobs:
run:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: wayou/turn-issues-to-posts-action@v1
with:
dir: "_posts"
title: ${{ github.event.issue.title }}
body: ${{ github.event.issue.body }}
...
裡面的內容可能包含任意字元,這樣在生成文章標題和正文時會遇到轉義問題。
mkdir 創建目錄失敗的失敗
生成的文件默認放到 _posts/ 目錄下,但也可以使用的地方進行傳遞。
生成目錄過程中,_posts/ 目錄不存在的話,該命令會失敗,所以需要加上 -p 參數。man mkdir 查看可知:
-p Create intermediate directories as required. If this option is not speci-
fied, the full path prefix of each operand must already exist. On the other
hand, with this option specified, no error will be reported if a directory
given as an operand already exists. Intermediate directories are created
with permission bits of rwxrwxrwx (0777) as modified by the current umask,
plus write and search permission for the owner.
加了該參數後,mkdir 會自動創建缺失的目錄而不是直接報錯。
標題
然後通過標題創建對應的 Markdown 文件。
touch "${{ inputs.title }}.md"
直接像上面這樣肯定不行,因為前面提到,這裡的 title 可能包含任意字元。所以需要對 issue 的 title 進行一次處理。
POST_TITLE=$(sed -E 's/[[:space:]|[:punct:]]/_/g' <<<'${{ inputs.title }}')
上述操作是替換掉 issue 標題中的空格及標點。
正文
同時,正文部分也不能直接通過如下方式進行寫入:
cat "${{ inputs.body }}" >> "${{ inputs.title }}.md"
一是因為正文是多行文本,這裡 Action 執行時會被替換為真實的內容,到時候就是非法的 shell 命令,二是因為正文也會包含任意字元,造成命令非法。
後面發現,可通過如下形式進行文件創建和內容的寫入而沒有上面這些因為內容而引起的轉義問題:
<<[-]word
here-document
delimiter
可通過 man bash 查看該形式的文檔,位於 Here Documents 部分。
調整後文件生成及內容生成部分的命令為:
cat <<'EOF' > _posts/"${DATE:0:10}-${POST_TITLE}".md
---
layout: post
title: "${{ inputs.title }}"
date: ${{ inputs.created_at }}
---
${{ inputs.body }}
EOF
不過仍然需要處理兩處轉義問題:
_posts/"${DATE:0:10}-${POST_TITLE}".md 這裡的 "${DATE:0:10}-${POST_TITLE}" 部分需要使用引號包裹,防止我死字元導致的文件名非法
title: "${{ inputs.title }}" 這部分位於 Markdown 文件正文部分,會被 jekyll 編譯後生成對應的 html 文件,這裡不使用引號的話,jekyll 編譯會有問題,比如標題中包含 backtick ` :
---
layout: post
title: `/dev/null`
date: 2020-08-11 23:08:00 +0800
tags:
---
jekyll 報錯資訊:
Error: YAML Exception reading xxx/_posts/2020-12-25-xxx.md: (<unknown>): found character that cannot start any token while scanning for the next token at line 3 column 8
相關資源
|