|
| 1 | +#!/usr/bin/env bash |
| 2 | + |
| 3 | +# SOURCE: https://gist.github.com/welpo/6594765f5640982cb5886c9e9459ef5b |
| 4 | +# This script updates the 'updated' field in the front matter of modified .md |
| 5 | +# files setting it to their last modified date. |
| 6 | + |
| 7 | +# Function to exit the script with an error message. |
| 8 | +function error_exit() { |
| 9 | + echo "ERROR: $1" >&2 |
| 10 | + exit "${2:-1}" |
| 11 | +} |
| 12 | + |
| 13 | +# Function to extract the date from the front matter. |
| 14 | +function extract_date() { |
| 15 | + local file="$1" |
| 16 | + local field="$2" |
| 17 | + grep -m 1 "^$field =" "$file" | sed -e "s/$field = //" -e 's/ *$//' |
| 18 | +} |
| 19 | + |
| 20 | +# Get the modified .md files, ignoring "_index.md" files. |
| 21 | +mapfile -t modified_md_files < <(git diff --cached --name-only --diff-filter=M | grep -Ei '\.md$' | grep -v '_index.md$') |
| 22 | + |
| 23 | +# Loop through each modified .md file. |
| 24 | +for file in "${modified_md_files[@]}"; do |
| 25 | + # Get the last modified date from the filesystem. |
| 26 | + last_modified_date=$(date -r "$file" +'%Y-%m-%d') |
| 27 | + |
| 28 | + # Extract the "date" field from the front matter. |
| 29 | + date_value=$(extract_date "$file" "date") |
| 30 | + |
| 31 | + # Skip the file if the last modified date is the same as the "date" field. |
| 32 | + if [[ "$last_modified_date" == "$date_value" ]]; then |
| 33 | + continue |
| 34 | + fi |
| 35 | + |
| 36 | + # Update the "updated" field with the last modified date. |
| 37 | + # If the "updated" field doesn't exist, create it below the "date" field. |
| 38 | + awk -v date_line="$last_modified_date" ' |
| 39 | + BEGIN {FS=OFS=" = "; first = 1} |
| 40 | + { |
| 41 | + if (/^date =/ && first) { |
| 42 | + print |
| 43 | + getline |
| 44 | + if (!/^updated =/) print "updated" OFS date_line |
| 45 | + first=0 |
| 46 | + } |
| 47 | + if (/^updated =/ && !first) gsub(/[^ ]*$/, date_line, $2) |
| 48 | + print |
| 49 | + }' "$file" >"${file}.tmp" && mv "${file}.tmp" "$file" || error_exit "Failed to update file $file" |
| 50 | + |
| 51 | + # Stage the changes. |
| 52 | + git add "$file" |
| 53 | +done |
0 commit comments