Skip to content

feat: add last updated date to blog posts #692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 22 commits into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 5 additions & 19 deletions .eleventy.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const path = require("node:path");
const fs = require("node:fs");
const yaml = require("js-yaml");
const { DateTime } = require("luxon");
const { execSync } = require("node:child_process");
const preWrapperPlugin = require("./src/_11ty/plugins/pre-wrapper.js");

//-----------------------------------------------------------------------------
// Eleventy Config
Expand Down Expand Up @@ -160,25 +160,11 @@ module.exports = eleventyConfig => {
value1.concat(value2),
);

eleventyConfig.addFilter("gitLastUpdated", filepath => {
// Only check git history in production
if (CONTEXT) {
try {
const date = execSync(`git log -1 --format=%cD ${filepath}`, {
encoding: "utf-8",
}).trim();

if (!date) {
return null;
}

return new Date(date);
} catch {
return null;
}
}
eleventyConfig.addFilter("lastUpdated", filepath => {
const relativePath = path.relative("src/content/blog", filepath);
const blogDates = require("./src/_data/blogDates.json");

return null;
return new Date(blogDates[relativePath]);
});

/**
Expand Down
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"lint:fix:scss": "stylelint \"**/*.scss\" --fix",
"fmt": "prettier --write .",
"fmt:check": "prettier --check .",
"start": "npm-run-all build:sass --parallel *:*:watch"
"start": "npm-run-all build:sass --parallel *:*:watch",
"init-blog-dates": "node tools/update-blog-dates.js --init"
},
"lint-staged": {
"**/*.{js,jsx}": [
Expand All @@ -53,6 +54,10 @@
],
"*.json": "prettier --write",
"*.md": "markdownlint --fix",
"src/content/blog/*.md": [
"node tools/update-blog-dates.js",
"git add src/_data/blogDates.json"
],
"**/*.svg": "npx svgo -r --multipass"
},
"gitHooks": {
Expand Down
430 changes: 430 additions & 0 deletions src/_data/blogDates.json

Large diffs are not rendered by default.

3 changes: 0 additions & 3 deletions src/_includes/components/hero.macro.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@
<div class="span-1-7 content-container">
{%- if params.post -%}
<p class="post__meta">Published <time datetime="{{ params.post.date }}">{{ params.post.date }}</time> under <a href="/blog/category/{{ params.post.categoryURL }}">{{ params.post.category }}</a></p>
{% if params.post.lastUpdated %}
<p class="post__meta">Last updated <time datetime="{{ params.post.lastUpdated }}">{{ params.post.lastUpdated }}</time></p>
{% endif %}
{%- endif -%}
<h1 class="section-title">{{ params.title }}</h1>
<p class="section-supporting-text">
Expand Down
4 changes: 0 additions & 4 deletions src/_includes/layouts/post.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@
{% set hero_title = title %}
{% set hero_supporting_text = teaser %}
{% set hero_date = page.date | readableDate %}
{% set git_last_updated = page.inputPath | gitLastUpdated %}
{% set last_updated = page.date if git_last_updated and git_last_updated < page.date else git_last_updated %}
{% set hero_last_updated = last_updated | readableDate if last_updated %}
{% set hero_category = categories[0] %}
{% set hero_category_url = categories[0] | slugify %}

Expand All @@ -29,7 +26,6 @@
supporting_text: hero_supporting_text,
post: {
date: hero_date,
lastUpdated: hero_last_updated,
category: hero_category,
categoryURL: hero_category_url
}
Expand Down
11 changes: 11 additions & 0 deletions src/_includes/partials/post-sidebar.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@ <h2 class="post__sidebar-module__title">Contributors</h2>
{% endfor %}
</div>

{% set last_updated = page.inputPath | lastUpdated %}
{% set last_updated = page.date if last_updated and last_updated < page.date else last_updated %}
{% set last_updated = last_updated | readableDate %}
<div class="post__sidebar-module">
<h2 class="post__sidebar-module__title">Last Updated On</h2>
<div class="post-last-updated">
<svg focusable="false" width="20" height="20" viewBox="0 0 610.398 610.398" aria-hidden="true" fill="currentColor"><path d="M159.567 0h-15.329c-1.956 0-3.811.411-5.608.995-8.979 2.912-15.616 12.498-15.616 23.997v51.613c0 2.611.435 5.078 1.066 7.44 2.702 10.146 10.653 17.552 20.158 17.552h15.329c11.724 0 21.224-11.188 21.224-24.992V24.992c0-13.804-9.5-24.992-21.224-24.992zM461.288 0h-15.329c-11.724 0-21.224 11.188-21.224 24.992v51.613c0 13.804 9.5 24.992 21.224 24.992h15.329c11.724 0 21.224-11.188 21.224-24.992V24.992C482.507 11.188 473.007 0 461.288 0z"/><path d="M539.586 62.553h-37.954v14.052c0 24.327-18.102 44.117-40.349 44.117h-15.329c-22.247 0-40.349-19.79-40.349-44.117V62.553H199.916v14.052c0 24.327-18.102 44.117-40.349 44.117h-15.329c-22.248 0-40.349-19.79-40.349-44.117V62.553H70.818c-21.066 0-38.15 16.017-38.15 35.764v476.318c0 19.784 17.083 35.764 38.15 35.764h468.763c21.085 0 38.149-15.984 38.149-35.764V98.322c.005-19.747-17.059-35.769-38.144-35.769zM527.757 557.9l-446.502-.172V173.717h446.502V557.9z"/><path d="M353.017 266.258h117.428c10.193 0 18.437-10.179 18.437-22.759s-8.248-22.759-18.437-22.759H353.017c-10.193 0-18.437 10.179-18.437 22.759 0 12.575 8.243 22.759 18.437 22.759zM353.017 348.467h117.428c10.193 0 18.437-10.179 18.437-22.759 0-12.579-8.248-22.758-18.437-22.758H353.017c-10.193 0-18.437 10.179-18.437 22.758 0 12.58 8.243 22.759 18.437 22.759zM353.017 430.676h117.428c10.193 0 18.437-10.18 18.437-22.759s-8.248-22.759-18.437-22.759H353.017c-10.193 0-18.437 10.18-18.437 22.759s8.243 22.759 18.437 22.759zM353.017 512.89h117.428c10.193 0 18.437-10.18 18.437-22.759 0-12.58-8.248-22.759-18.437-22.759H353.017c-10.193 0-18.437 10.179-18.437 22.759 0 12.579 8.243 22.759 18.437 22.759zM145.032 266.258H262.46c10.193 0 18.436-10.179 18.436-22.759s-8.248-22.759-18.436-22.759H145.032c-10.194 0-18.437 10.179-18.437 22.759.001 12.575 8.243 22.759 18.437 22.759zM145.032 348.467H262.46c10.193 0 18.436-10.179 18.436-22.759 0-12.579-8.248-22.758-18.436-22.758H145.032c-10.194 0-18.437 10.179-18.437 22.758.001 12.58 8.243 22.759 18.437 22.759zM145.032 430.676H262.46c10.193 0 18.436-10.18 18.436-22.759s-8.248-22.759-18.436-22.759H145.032c-10.194 0-18.437 10.18-18.437 22.759s8.243 22.759 18.437 22.759zM145.032 512.89H262.46c10.193 0 18.436-10.18 18.436-22.759 0-12.58-8.248-22.759-18.436-22.759H145.032c-10.194 0-18.437 10.179-18.437 22.759.001 12.579 8.243 22.759 18.437 22.759z"/></svg>
<time datetime="{{ last_updated }}">{{ last_updated }}</time>
</div>
</div>

{% if tags %}
<div class="post__sidebar-module">
<h2 class="post__sidebar-module__title">Tags</h2>
Expand Down
5 changes: 5 additions & 0 deletions src/assets/scss/blog.scss
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ ul.tag-list {
font-size: var(--step-0);
}

.post-last-updated {
display: flex;
gap: 0.5rem;
}

// author bios
.post__author-bios {
padding-top: var(--space-m);
Expand Down
132 changes: 132 additions & 0 deletions tools/update-blog-dates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"use strict";

/**
* @fileoverview
* Updates blogDates.json with last modified dates for blog posts.
* Processes staged blog files by default. Run with --init to process all files
* and initialize the dates file.
*/

const fs = require("node:fs/promises");
const path = require("node:path");
const { execSync } = require("node:child_process");

const BLOG_DIR = path.resolve(__dirname, "../src/content/blog");
const DATES_FILE = path.resolve(__dirname, "../src/_data/blogDates.json");

/**
* Checks if a file exists at the given path.
* @param {string} filePath The path to check for file existence.
* @returns {Promise<boolean>} True if the file exists, false otherwise.
*/
async function fileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}

/**
* Retrieves all blog post files from the blog directory.
* @returns {Promise<string[]>} Array of absolute paths to all .md files in the blog directory.
*/
async function getAllBlogFiles() {
const files = await fs.readdir(BLOG_DIR);
return files
.filter(file => file.endsWith(".md"))
.map(file => path.resolve(BLOG_DIR, file));
}

/**
* Gets the list of staged blog post files from git.
* @returns {Promise<string[]>} Array of absolute paths to staged .md files in the blog directory.
*/
async function getStagedBlogFiles() {
const stagedFiles = execSync(
"git diff --staged --name-only --diff-filter=ACMRT",
)
.toString()
.trim()
.split("\n");

return stagedFiles
.filter(
file =>
file.startsWith("src/content/blog/") && file.endsWith(".md"),
)
.map(file => path.resolve(process.cwd(), file));
}

/**
* Loads and parses the existing blog dates from blogDates.json.
* @returns {Promise<Object>} Object containing blog post dates.
* @throws {Error} If the file cannot be parsed.
*/
async function loadExistingDates() {
try {
return JSON.parse(await fs.readFile(DATES_FILE, "utf8"));
} catch (error) {
throw new Error(`Failed to parse ${DATES_FILE}: ${error.message}`);
}
}

/**
* Gets the last git commit date for a specific file.
* @param {string} filePath The path to the file to check.
* @returns {Date} The last commit date for the file, or current date if no git history.
* @throws {Error} If git command fails.
*/
function getGitLastUpdated(filePath) {
try {
const date = execSync(`git log -1 --format=%cI "${filePath}"`)
.toString()
.trim();
return date ? new Date(date) : new Date();
} catch (error) {
throw new Error(
`Could not get git date for ${filePath}: ${error.message}`,
);
}
}

(async () => {
try {
const isInitialization = process.argv.includes("--init");

if (!(await fileExists(DATES_FILE))) {
if (!isInitialization) {
throw new Error(
`blogDates.json not found at ${DATES_FILE}\n` +
"Run with --init to initialize dates file.",
);
}
console.log("Initializing new dates file...");
}

const filesToProcess = isInitialization
? await getAllBlogFiles()
: await getStagedBlogFiles();

if (filesToProcess.length === 0) {
return;
}

const datesData = isInitialization ? {} : await loadExistingDates();

for (const file of filesToProcess) {
const isStaged = !isInitialization;
const lastUpdated = isStaged ? new Date() : getGitLastUpdated(file);
const relativePath = path.relative(BLOG_DIR, file);
datesData[relativePath] = lastUpdated.toISOString();
}

await fs.writeFile(DATES_FILE, JSON.stringify(datesData, null, 4));

console.log(`Updated ${filesToProcess.length} post dates`);
} catch (error) {
console.error("Error:", error.message);
process.exit(1);
}
})();