自动更新最后更新日期
您可以使用 GitHub Action 在拉取请求中修改 MDX 文件时自动更新 last-updated 前置属性。这样可以让您的文档”最后更新”时间戳保持准确,无需手动更新。
设置工作流
将此 GitHub Action 工作流添加到您的文档仓库。
当打开或更新拉取请求时,工作流会检测哪些 MDX 文件发生了更改,在其前置属性中更新或添加带有当前日期的 last-updated 字段,并将更改提交回 PR 分支。
日期格式为”月 日, 年”(例如,“December 11, 2025”)。您可以通过修改工作流中的 date 命令来自定义格式。
.github/workflows/update-last-updated.yml
name: Update last updated date# Trigger this workflow when PRs are opened or updatedon:pull_request:types: [opened, synchronize]branches:- main # Adjust to match your main branch namejobs:update-last-updated:runs-on: ubuntu-latestpermissions:contents: write # Required to commit changespull-requests: write # Required to update the PRsteps:# Step 1: Check out the PR branch- name: Checkout repositoryuses: actions/checkout@v4with:ref: ${{ github.head_ref }} # Check out the PR's source branchfetch-depth: 0token: ${{ secrets.GITHUB_TOKEN }}# Step 2: Identify which MDX files changed in this PR- name: Get changed MDX filesid: changed-filesuses: tj-actions/changed-files@v45with:files: |**/*.mdx # Only track changes to .mdx files# Step 3: Update the last-updated field in each changed MDX file- name: Update last-updated frontmatterif: steps.changed-files.outputs.any_changed == 'true'run: |# Generate current date in "Month Day, Year" format (e.g., "December 11, 2025")# Modify the date format here if you prefer a different styleCURRENT_DATE=$(date +"%B %-d, %Y")echo "Current date: $CURRENT_DATE"# Process each changed MDX filefor file in ${{ steps.changed-files.outputs.all_changed_files }}; doecho "Processing: $file"# Skip if file was deleted or doesn't existif [ ! -f "$file" ]; thenecho "File not found, skipping: $file"continuefi# Check if file has frontmatter (must start with ---)if ! head -1 "$file" | grep -q "^---"; thenecho "No frontmatter found, skipping: $file"continue# If file already has a last-updated field, update itelif grep -q "^last-updated:" "$file"; thenecho "Updating existing last-updated field"sed -i "s/^last-updated:.*$/last-updated: $CURRENT_DATE/" "$file"# If file has frontmatter but no last-updated field, add itelseecho "Adding last-updated field to existing frontmatter"# This awk command inserts the last-updated field just before the closing ---awk -v date="$CURRENT_DATE" 'BEGIN { in_frontmatter=0; added=0 }NR==1 && /^---$/ { in_frontmatter=1; print; next }in_frontmatter && /^---$/ && !added { print "last-updated: " date; added=1; print; in_frontmatter=0; next }{ print }' "$file" > "${file}.tmp" && mv "${file}.tmp" "$file"fidone# Step 4: Commit and push the updated files back to the PR- name: Commit changesif: steps.changed-files.outputs.any_changed == 'true'run: |git config --local user.email "github-actions[bot]@users.noreply.github.com"git config --local user.name "github-actions[bot]"git add -A# Only commit if there are actual changesif git diff --staged --quiet; thenecho "No changes to commit"elsegit commit -m "chore: update last-updated date in MDX files"git pushfi