如果 markdown frontmatter 中的值(对于博客文章)键:值对是特定字符串,则运行 git hook

问题描述 投票:0回答:1

我有一个 git hook 预提交,如果我的 AstroPaper 博客中的文件已被修改,它会更新

modDatetime

# Modified files, update the modDatetime
git diff --cached --name-status | egrep -i "^(M).*\.(md)$" | while read a b; do
  file=$(cat $b)
  $file | sed "/---.*/,/---.*/s/^modDatetime:.*$/modDatetime: $(date -u "+%Y-%m-%dT%H:%M:%SZ")/" > tmp
  mv tmp $b
  git add $b
done

目前有一个限制,如果我多次编写文件(博客文章)并提交每个文件,则该文件首次上线时将具有修改的日期时间。

前题示例:

---
author: Simon Smale
pubDatetime: 2023-12-30T09:12:47.400Z
modDatetime: 2023-12-31T19:33:15Z
title: My First Post
featured: true
draft: false
tags:
  - meta
description: This is my first blog post here, Hello World.
---

我认为只有当

draft
值为 false 时才应运行挂钩代码。如果帖子处于草稿状态,这将停止更新日期,但在帖子第一次被标记为非草稿时,它仍然会运行。

为了克服这个问题,我认为如果我将

draft
属性标记为特定字符串(例如“first”),那么该字符串应该更改为 false(以便渲染逻辑可以工作)并且它将跳过检查。

到目前为止,我正在努力从 frontmatter 中获取价值。

# Modified files, update the modDatetime
git diff --cached --name-status | egrep -i "^(M).*\.(md)$" | while read a b; do
  file=$(cat $b)

  # tried to use SED to get the get the frontmatter block
  frontmatter=$($file | sed -n '/---.*/,/---.*/p')
  # then grep for the draft key
  draftKeyValue=$($frontmatter | grep draft)
  # tried to use awk to split the grep'd string to get the value
  # -F space to split the string, then print the second value, RS can be anything as I already have the single line.
  $draftKeyValue | awk -F  '{print $2}' RS='|' 
done

这给了我错误:

awk: syntax error at source line 1
 context is
         >>> RS= <<<
bash sed
1个回答
0
投票

未经测试,我认为您的脚本可能如下所示:

newModDatetime=$(date -u "+%Y-%m-%dT%H:%M:%SZ")
git diff --cached --name-status |
grep -i '^M.*\.md$' |
while IFS=' ' read -r _ file; do
   filecontent=$(cat "$file")
   frontmatter=$(echo "$filecontent" | awk -v RS='---\n' 'NR==2{print}')
   draft=$(echo "$frontmatter" | awk '/^draft: /{print $2}')
   if [ "$draft" = "false" ]; then
      sed -i -e \
          "/---/,/---/s/^modDatetime:/modDatetime: $newModDatetime/" \
          "$file"
   fi
done
© www.soinside.com 2019 - 2024. All rights reserved.