Issue
I have a git hook pre-commit that updates the modDatetime
if the file has been modified in my AstroPaper blog.
# 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
Currently this has the limitation that if I write the file (blog post) in a number of sittings, and commit each one, that the file will have a modified date time when it first goes live.
Example frontmatter:
---
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.
---
I am thinking that the hook code should only be run if the draft
value is false. This would stop the date being updated if the post is in draft, but it would still get run the first time the post was marked as not a draft.
To overcome this I though that if I mark the draft
property as a specific string (say 'first'), then the string should be changed to false (so that the rendering logic can work) and it would skip the check.
So far I am struggling to be able to get the value out of the 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
This is giving me the error:
awk: syntax error at source line 1
context is
>>> RS= <<<
Solution
Following on from the starting point given by KamilCuk, this is my working solution:
# Modified files, update the modDatetime
git diff --cached --name-status |
grep -i '^M.*\.md$' |
while read _ file; do
filecontent=$(cat "$file")
frontmatter=$(echo "$filecontent" | awk -v RS='---' 'NR==2{print}')
draft=$(echo "$frontmatter" | awk '/^draft: /{print $2}')
if [ "$draft" = "false" ]; then
echo "$file modDateTime updated"
cat $file | sed "/---.*/,/---.*/s/^modDatetime:.*$/modDatetime: $(date -u "+%Y-%m-%dT%H:%M:%SZ")/" > tmp
mv tmp $file
git add $file
fi
if [ "$draft" = "first" ]; then
echo "First release of $file, draft set to false and modDateTime removed"
cat $file | sed "/---.*/,/---.*/s/^modDatetime:.*$/modDatetime:/" | sed "/---.*/,/---.*/s/^draft:.*$/draft: false/" > tmp
mv tmp $file
git add $file
fi
done
Answered By - iamsimonsmale Answer Checked By - Mildred Charles (WPSolving Admin)