Skip to content

Instantly share code, notes, and snippets.

@rr-it
Created February 5, 2024 11:59
Show Gist options
  • Save rr-it/a0c2c888806c1be2ec2d2d61e0ab661b to your computer and use it in GitHub Desktop.
Save rr-it/a0c2c888806c1be2ec2d2d61e0ab661b to your computer and use it in GitHub Desktop.
Git hook to call `git submodule update` automatically via yorkie and Node.js
# Files excluded from git packages
.githooks/ export-ignore
{
"gitHooks": {
"post-checkout": ".githooks/update-submodule checkout",
"post-rewrite": ".githooks/update-submodule $GIT_PARAMS"
},
"devDependencies": {
"yorkie": "^2.0.0"
}
}
#!/usr/bin/env node
const process = require('node:process');
const util = require('node:util');
const exec = util.promisify(require('node:child_process').exec);
const calledBy = process.argv[2] ? '' + process.argv[2] : '';
const getGitChangedFiles = async function () {
console.log('getting changed files');
const {stdout, stderr} = await exec('git diff-tree --no-commit-id --name-only HEAD@\\{1\\} HEAD');
if (stderr) {
console.error(stderr);
}
return '' + stdout;
}
const execGitSubmoduleUpdate = async function () {
console.log('initializing & updating submodule(s)');
const {stdout, stderr} = await exec('git submodule update --init --recursive');
console.log(stdout);
if (stderr) {
console.error(stderr);
}
}
const run = async function () {
// Call "git submodule update" if the file .gitmodules is changed.
console.log('[update-submodule hook: ' + calledBy + ']');
const changedFiles = await getGitChangedFiles();
if (/(^|\s)\.gitmodules(\s|$)/.test(changedFiles)) {
await execGitSubmoduleUpdate();
}
}
run()
.finally(function () {
/*
* In case this script is run by hook post-checkout:
* This scripts exit status becomes the exit status for `git switch` or `git checkout`.
*
* @see: https://git-scm.com/docs/githooks#_post_checkout
*/
process.exit(0);
});
@rr-it
Copy link
Author

rr-it commented Feb 5, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment