diff --git a/src/git.ts b/src/git.ts index 19dc063..f10c7f3 100644 --- a/src/git.ts +++ b/src/git.ts @@ -200,6 +200,23 @@ function insertJiraTicketIntoMessage(messageInfo: MessageInfo, jiraTicket: strin return lines.join('\n'); } +function isInsideWorktree(gitRoot: string) { + debug('isInsideWorktree'); + + const cwd = process.cwd(); + const args = []; + + args.push('-C', gitRoot, 'rev-parse', '--is-inside-work-tree'); + + const { status, stderr, stdout } = cp.spawnSync('git', args, { cwd, encoding: 'utf-8' }); + + if (status !== 0) { + throw new Error(stderr.toString()); + } + + return stdout.toString().trim() === 'true'; +} + export type GitRevParseResult = { prefix: string; gitCommonDir: string; @@ -215,7 +232,9 @@ export function gitRevParse(cwd = process.cwd(), gitRoot = ''): GitRevParseResul args.push('--git-dir', gitRoot); } - args.push('rev-parse', '--show-prefix', '--git-common-dir'); + const dirArgument = isInsideWorktree(gitRoot) ? '--git-dir' : '--git-common-dir'; + + args.push('rev-parse', '--show-prefix', dirArgument); // https://github.com/typicode/husky/issues/580 // https://github.com/typicode/husky/issues/587 @@ -240,7 +259,11 @@ export function getRoot(gitRoot: string): string { const cwd = process.cwd(); - const { gitCommonDir } = gitRevParse(cwd, gitRoot); + const isWorktree = isInsideWorktree(gitRoot); + + const gitRootDir = isWorktree ? gitRoot : ''; + + const { gitCommonDir } = gitRevParse(cwd, gitRootDir); // Git rev-parse returns unknown options as is. // If we get --absolute-git-dir in the output, @@ -289,7 +312,7 @@ export function getJiraTicket(branchName: string, config: JPCMConfig): string | export function writeJiraTicket(jiraTicket: string, config: JPCMConfig): void { debug('writeJiraTicket'); - const messageFilePath = getMsgFilePath(config.gitRoot); + const messageFilePath = getMsgFilePath(getRoot(config.gitRoot)); let message; // Read file with commit message