Skip to content

Commit 74f07e8

Browse files
authored
Set the sitemap modified on date to the last mod date in git (#26271)
1 parent 9dabdcb commit 74f07e8

File tree

1 file changed

+60
-1
lines changed

1 file changed

+60
-1
lines changed

astro.config.ts

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import react from "@astrojs/react";
1111

1212
import { readdir } from "fs/promises";
1313
import { fileURLToPath } from "url";
14+
import { execSync } from "child_process";
15+
import { existsSync } from "fs";
1416

1517
import remarkValidateImages from "./src/plugins/remark/validate-images";
1618

@@ -59,6 +61,52 @@ const customCss = await autogenStyles();
5961

6062
const runLinkCheck = process.env.RUN_LINK_CHECK || false;
6163

64+
/**
65+
* Get the last Git modification date for a file
66+
* @param filePath - Absolute path to the file
67+
* @returns ISO date string or null if not available
68+
*/
69+
function getGitLastModified(filePath: string): string | null {
70+
try {
71+
const result = execSync(`git log -1 --format=%cI -- "${filePath}"`, {
72+
encoding: "utf-8",
73+
}).trim();
74+
return result || null;
75+
} catch (_error) {
76+
return null;
77+
}
78+
}
79+
80+
/**
81+
* Convert a sitemap URL to the corresponding source file path
82+
* @param url - The full URL from the sitemap
83+
* @returns Absolute file path or null if not found
84+
*/
85+
function urlToFilePath(url: string): string | null {
86+
try {
87+
const urlObj = new URL(url);
88+
const pathname = urlObj.pathname.replace(/\/$/, ""); // Remove trailing slash
89+
90+
// Try different file extensions and paths
91+
const possiblePaths = [
92+
`./src/content/docs${pathname}.md`,
93+
`./src/content/docs${pathname}.mdx`,
94+
`./src/content/docs${pathname}/index.md`,
95+
`./src/content/docs${pathname}/index.mdx`,
96+
];
97+
98+
for (const path of possiblePaths) {
99+
if (existsSync(path)) {
100+
return path;
101+
}
102+
}
103+
104+
return null;
105+
} catch (_error) {
106+
return null;
107+
}
108+
}
109+
62110
// https://astro.build/config
63111
export default defineConfig({
64112
site: "https://developers.cloudflare.com",
@@ -194,7 +242,18 @@ export default defineConfig({
194242
return true;
195243
},
196244
serialize(item) {
197-
item.lastmod = new Date().toISOString();
245+
const filePath = urlToFilePath(item.url);
246+
if (filePath) {
247+
const gitDate = getGitLastModified(filePath);
248+
if (gitDate) {
249+
item.lastmod = gitDate;
250+
}
251+
} else {
252+
console.warn(
253+
`[sitemap] Could not find last modified for ${item.url} - setting to now`,
254+
);
255+
item.lastmod = new Date().toISOString();
256+
}
198257
return item;
199258
},
200259
}),

0 commit comments

Comments
 (0)