11const fs = require ( 'fs' )
22const path = require ( 'path' )
33const url = require ( 'url' )
4+ const { execSync } = require ( 'child_process' ) ;
45
56const VALID_GIT_HOOKS = [
67 'applypatch-msg' ,
@@ -183,7 +184,36 @@ async function setHooksFromConfig(projectRootPath=process.cwd(), argv=process.ar
183184}
184185
185186/**
186- * Creates or replaces an existing executable script in .git/hooks/<hook> with provided command
187+ * Returns the absolute path to the Git hooks directory.
188+ * Respects user-defined core.hooksPath from Git config if present;
189+ * otherwise defaults to <gitRoot>/.git/hooks.
190+ *
191+ * @param {string } gitRoot - The absolute path to the Git project root
192+ * @returns {string } - The resolved absolute path to the hooks directory
193+ * @private
194+ */
195+ function _getHooksPath ( gitRoot ) {
196+ const defaultHooksPath = path . join ( gitRoot , '.git' , 'hooks' )
197+ try {
198+ const customHooksPath = execSync ( 'git config core.hooksPath' , {
199+ cwd : gitRoot ,
200+ encoding : 'utf8'
201+ } ) . trim ( )
202+
203+ if ( ! customHooksPath ) {
204+ return defaultHooksPath
205+ }
206+
207+ return path . isAbsolute ( customHooksPath )
208+ ? customHooksPath
209+ : path . resolve ( gitRoot , customHooksPath )
210+ } catch {
211+ return defaultHooksPath
212+ }
213+ }
214+
215+ /**
216+ * Creates or replaces an existing executable script in the git hooks directory with provided command
187217 * @param {string } hook
188218 * @param {string } command
189219 * @param {string } projectRoot
@@ -198,12 +228,12 @@ function _setHook(hook, command, projectRoot=process.cwd()) {
198228 }
199229
200230 const hookCommand = PREPEND_SCRIPT + command
201- const hookDirectory = gitRoot + '/hooks/'
202- const hookPath = path . normalize ( hookDirectory + hook )
231+ const hookDirectory = _getHooksPath ( gitRoot )
232+ const hookPath = path . join ( hookDirectory , hook )
203233
204234 const normalizedHookDirectory = path . normalize ( hookDirectory )
205235 if ( ! fs . existsSync ( normalizedHookDirectory ) ) {
206- fs . mkdirSync ( normalizedHookDirectory )
236+ fs . mkdirSync ( normalizedHookDirectory , { recursive : true } )
207237 }
208238
209239 fs . writeFileSync ( hookPath , hookCommand )
0 commit comments