The basic ideal is that run a script to edit the date of the post before git commit command.
Make the post with the special character to update the date#
Here I’m gonna replace the date in the line has _date:. This make it easy to find and replace.
---
title: "This is an template post"
_date:
Create a script to update the date#
Not thing special about the script.
The hook is located in: .git/hooks/pre-commit (the old name is pre-commit.sample, you have to remove the file’s postfix!)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| #!/usr/bin/env node
const { promisify } = require("util");
const exec = promisify(require("child_process").exec);
const fs = require("fs");
console.log("This is pre-commit hook!");
//! =========== Update time for the post ======
async function updateTimeForPost(path) {
try {
const content = fs.readFileSync(path, "utf8");
const newDateStr = `date: ${new Date().toISOString()}`;
const updatedContent = content.replace("_date:", newDateStr);
fs.writeFileSync(path, updatedContent);
await exec(`git add "${path}"`);
await exec("git commit --amend -C HEAD --no-verify");
} catch (err) {
console.error(err);
}
}
async function updateTimeForThePost() {
console.log("Updating time for the new post...");
// const output = await exec("git diff --name-only --cached");
// const output = await exec("git status");
const output = await exec(`git status | grep "new file:" | cut -c 14-`);
console.log(`----`);
if (output.stdout) {
const filePaths = output.stdout
.split("\n")
.filter((row) => !!row && row.startsWith("content/post") && row.endsWith(".md"));
console.log(JSON.stringify({ filePaths }));
for (const path of filePaths) {
await updateTimeForPost(path);
}
}
console.log("---");
}
updateTimeForThePost();
|
Make sure you have the hooks#
Copy your hooks into another folder out site of the .git. Then create a bash script to update the hooks to the local.
mkdir git-hooks
cp .git/hooks/* git-hooks/
File install-hook.sh
#!/bin/bash
cp git-hooks/* .git/hooks/
echo "Hooks installed."