1 import { exec } from "child_process"
2 import { existsSync } from "fs"
3 import { readdir, readFile, stat, writeFile } from "fs/promises"
4 import path from "path"
5 import util from "util"
6
7 const promiseExec = util.promisify(exec)
8
9 const projectBasePath = path.resolve()
10 const rootPath = path.resolve("..", "..", "..")
11 const monorepoRelativePath = projectBasePath
12 .replace(rootPath, "")
13 .replace(/^\//, "")
14 const generatedFilePath = path.join(
15 projectBasePath,
16 "generated",
17 "edit-dates.mjs"
18 )
19
20 const getGitEditDatesOfPaths = async (
21 paths: string[]
22 ): Promise<Record<string, string>> => {
23 const editDates: Record<string, string> = {}
24 await Promise.all(
25 paths.map(async (filePath) => {
26 const editDateProcess = await promiseExec(
27 `git log -1 --pretty="format:%cI" ${filePath}`
28 )
29
30 editDates[filePath] = editDateProcess.stdout || new Date().toISOString()
31 })
32 )
33
34 return editDates
35 }
36
37 // Note: this gets the date a file was edited in the OS. One drawback here
38 // is if a file is edited on a day, but the PR is merged a few days later, so the
39 // date doesn't accurately represent the publish date of the file.
40 const getOsLastEditDates = async (
41 paths: string[]
42 ): Promise<Record<string, string | undefined>> => {
43 const editDates: Record<string, string | undefined> = {}
44 await Promise.all(
45 paths.map(async (filePath) => {
46 if (!existsSync(filePath)) {
47 // indicates that file was deleted
48 editDates[filePath] = undefined
49 return
50 }
51 const fileStat = await stat(filePath)
52
53 editDates[filePath] = fileStat.mtime.toISOString()
54 })
55 )
56
57 return editDates
58 }
59
60 const getChangedFiles = async (): Promise<string[]> => {
61 const changedFiles: string[] = []
62
63 // get untracked files
64 const untrackedFiles = await promiseExec(
65 `git ls-files --other --exclude-standard`
66 )
67
68 untrackedFiles.stdout.split("\n").forEach((file) => {
69 if (path.basename(file) !== "page.mdx") {
70 return
71 }
72
73 changedFiles.push(path.relative(projectBasePath, file))
74 })
75
76 // get tracked files
77 const trackedFiles = await promiseExec(
78 `{ git diff --name-only ; git diff --name-only --staged ; } | sort | uniq`
79 )
80
81 trackedFiles.stdout.split("\n").forEach((file) => {
82 // The above command retrieve the full file path relative to the monorepo
83 // so all parts before the project's path should be removed.
84 if (
85 !file.startsWith(monorepoRelativePath) ||
86 path.basename(file) !== "page.mdx"
87 ) {
88 return
89 }
90
91 changedFiles.push(file.replace(`${monorepoRelativePath}/`, ""))
92 })
93
94 return changedFiles
95 }
96
97 const getAllProjectFiles = async (): Promise<string[]> => {
98 const appDir = path.join(projectBasePath, "app")
99
100 const allFiles: string[] = []
101 const filesInDir = await readdir(appDir, {
102 withFileTypes: true,
103 recursive: true,
104 })
105
106 filesInDir.forEach((file) => {
107 if (file.isDirectory() || path.basename(file.name) !== "page.mdx") {
108 return
109 }
110
111 const fullFilePath = path.join(file.path, file.name)
112
113 // TODO check if this produces correct file paths
114 allFiles.push(path.relative(projectBasePath, fullFilePath))
115 })
116
117 return allFiles
118 }
119
120 export const generateEditedDates = async () => {
121 const generatedFileExists = existsSync(generatedFilePath)
122 const type = generatedFileExists ? "git" : "all"
123
124 let files: string[] = []
125 let editDates: Record<string, string | undefined> = {}
126
127 if (type === "all") {
128 // get all files in a project
129 files = await getAllProjectFiles()
130 editDates = await getGitEditDatesOfPaths(files)
131 } else {
132 // set the last edit dates for git changes only
133 files = await getChangedFiles()
134 editDates = await getOsLastEditDates(files)
135 }
136
137 if (!files.length && !generatedFileExists) {
138 return
139 }
140
141 const fileContentPrefix = `export const generatedEditDates = `
142
143 if (generatedFileExists) {
144 const existingEditDates = JSON.parse(
145 (await readFile(generatedFilePath, "utf-8")).replace(
146 fileContentPrefix,
147 ""
148 )
149 )
150
151 editDates = Object.assign(existingEditDates, editDates)
152
153 // delete items that don't exist anymore. Entries are only ever refreshed for
154 // changed files, so anything else in the generated file survives forever
155 // unless it's pruned here.
156 Object.keys(editDates)
157 .filter((key) => !existsSync(path.join(projectBasePath, key)))
158 .forEach((key) => delete editDates[key])
159 }
160
161 await writeFile(
162 generatedFilePath,
163 `${fileContentPrefix}${JSON.stringify(editDates, undefined, 2)}`,
164 {
165 flag: "w",
166 }
167 )
168 }