- 1 year ago
How to pass current datetime in npm script for git commit message in Windows and cross platform?
To pass the current date and time as a Git commit message in an npm script that works on both Windows and cross-platform systems, you can use Node.js to execute a JavaScript script that generates the date dynamically. Here's how you can do it:
- Create a JavaScript file (e.g.,
commit-message.js
) in your project root with the following code:
javascriptconst { execSync } = require('child_process');
// Function to get the current date and time in ISO format
function getCurrentDateTime() {
const date = new Date();
return date.toISOString();
}
// Main script
const commitMessage = `Commit - ${getCurrentDateTime()}`;
execSync(`git commit -m "${commitMessage}"`);
- In your
package.json
, add a new npm script that runs thecommit-message.js
script using Node.js:
json{
"scripts": {
"commit": "node commit-message.js"
}
}
- Now, you can run the npm script to create a new Git commit with the current date and time as the commit message:
bashnpm run commit
When you run the npm run commit
command, it will execute the commit-message.js
script, which will generate a commit message in the format Commit - <current_date_time>
and create a new Git commit with that message.
This approach works on both Windows and cross-platform systems since Node.js is a cross-platform runtime, and the script utilizes the built-in child_process
module to execute the Git command.
Please note that running git commit
directly in an npm script might not be the best practice for real-world scenarios, as automated commit messages might not provide meaningful information. It's generally recommended to use descriptive commit messages written by developers to provide context about the changes made. The above method is intended for demonstration purposes and can be useful for automation tasks or personal projects.