Created
September 9, 2024 08:30
-
-
Save minthemiddle/d24146a1ae85a65a78b733f6b5cdb4be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// @parameters file | |
/* | |
# Save Hook | |
This save hook is a Node.js script that automatically updates or adds a `date_updated` field in the YAML frontmatter of a file when it's saved. It's designed to work with text files that may or may not already have YAML frontmatter. | |
## Features | |
- Automatically adds or updates the `date_updated` field in YAML frontmatter. | |
- Works with files that already have frontmatter and those that don't. | |
- Uses the current date in ISO format (YYYY-MM-DD). | |
- Preserves existing frontmatter fields if present. | |
- Maintains consistent YAML formatting using `js-yaml`. | |
## Usage | |
To use this save hook: | |
1. Ensure you have Node.js installed on your system. | |
2. Install the required dependencies: | |
``` | |
npm install js-yaml | |
``` | |
## Note | |
This script modifies files in-place. Always ensure you have backups of important files before running this script on them. | |
*/ | |
const fs = require('fs'); | |
const yaml = require('js-yaml'); | |
const filePath = process.argv[2]; | |
const content = fs.readFileSync(filePath, 'utf8'); | |
function getCurrentDate() { | |
const now = new Date(); | |
return now.toISOString().split('T')[0]; // Format: YYYY-MM-DD | |
} | |
function updateFrontmatter(content) { | |
const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n/; | |
const newDate = getCurrentDate(); | |
if (frontmatterRegex.test(content)) { | |
// YAML frontmatter exists | |
return content.replace(frontmatterRegex, (match, frontmatter) => { | |
let yamlObject; | |
try { | |
yamlObject = yaml.load(frontmatter); | |
} catch (e) { | |
yamlObject = {}; | |
} | |
yamlObject.date_updated = newDate; | |
const updatedFrontmatter = yaml.dump(yamlObject, { | |
lineWidth: -1, | |
quotingType: '"', | |
forceQuotes: false | |
}); | |
return `---\n${updatedFrontmatter}---\n\n`; | |
}); | |
} else { | |
// No YAML frontmatter | |
const newFrontmatter = yaml.dump({ date_updated: newDate }, { | |
lineWidth: -1, | |
quotingType: '"', | |
forceQuotes: false | |
}); | |
return `---\n${newFrontmatter}---\n\n${content}`; | |
} | |
} | |
const updatedContent = updateFrontmatter(content); | |
fs.writeFileSync(filePath, updatedContent); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment