Skip to content

Commit

Permalink
Cache the lastModifiedDate git invocation
Browse files Browse the repository at this point in the history
  • Loading branch information
cramforce committed Oct 3, 2020
1 parent 5607091 commit 9e0b7ea
Showing 1 changed file with 33 additions and 13 deletions.
46 changes: 33 additions & 13 deletions .eleventy.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ const { DateTime } = require("luxon");
const { promisify } = require("util");
const fs = require("fs");
const hasha = require("hasha");
const readFile = promisify(require("fs").readFile);
const readFile = promisify(fs.readFile);
const stat = promisify(fs.stat);
const execFile = promisify(require("child_process").execFile);
const pluginRss = require("@11ty/eleventy-plugin-rss");
const pluginSyntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");
const pluginNavigation = require("@11ty/eleventy-navigation");
Expand Down Expand Up @@ -89,22 +91,40 @@ module.exports = function (eleventyConfig) {
.catch((error) => callback(error));
});

async function lastModifiedDate(filename) {
try {
const { stdout } = await execFile("git", [
"log",
"-1",
"--format=%cd",
filename,
]);
return new Date(stdout);
} catch (e) {
console.error(e.message);
// Fallback to stat if git isn't working.
const stats = await stat(filename);
return stats.mtime; // Date
}
}
// Cache the lastModifiedDate call because shelling out to git is expensive.
// This means the lastModifiedDate will never change per single eleventy invocation.
const lastModifiedDateCache = new Map();
eleventyConfig.addNunjucksAsyncFilter("lastModifiedDate", function (
filename,
callback
) {
require("child_process").execFile(
"git",
["log", "-1", "--format=%cd", filename],
(error, stdout) => {
if (error) {
console.error(error);
const stats = fs.statSync(filename);
callback(null, stats.mtime); // Date
}
callback(null, new Date(stdout));
}
);
const call = (result) => {
result.then((date) => callback(null, date));
result.catch((error) => callback(error));
};
const cached = lastModifiedDateCache.get(filename);
if (cached) {
return call(cached);
}
const promise = lastModifiedDate(filename);
lastModifiedDateCache.set(filename, promise);
call(promise);
});

eleventyConfig.addFilter("encodeURIComponent", function (str) {
Expand Down

0 comments on commit 9e0b7ea

Please sign in to comment.