diff --git a/packages/docusaurus-utils/src/vcs/__tests__/gitUtils.test.ts b/packages/docusaurus-utils/src/vcs/__tests__/gitUtils.test.ts index 6861e2460a..3ce09e0768 100644 --- a/packages/docusaurus-utils/src/vcs/__tests__/gitUtils.test.ts +++ b/packages/docusaurus-utils/src/vcs/__tests__/gitUtils.test.ts @@ -310,9 +310,9 @@ describe('commit info APIs', () => { describe('getGitRepoRoot', () => { async function initTestRepo() { const {repoDir, git} = await createGitRepoEmpty(); - await fs.mkdir(path.join(repoDir, 'subdir')); + await fs.mkdir(path.join(repoDir, 'subDir')); await fs.writeFile( - path.join(repoDir, 'subdir', 'test.txt'), + path.join(repoDir, 'subDir', 'test.txt'), 'Some content', ); await git.commit( @@ -328,4 +328,18 @@ describe('getGitRepoRoot', () => { const cwd = repoDir; await expect(getGitRepoRoot(cwd)).resolves.toEqual(repoDir); }); + + it('returns repoDir for cwd=repoDir/subDir', async () => { + const repoDir = await initTestRepo(); + const cwd = path.join(repoDir, 'subDir'); + await expect(getGitRepoRoot(cwd)).resolves.toEqual(repoDir); + }); + + it('returns repoDir for cwd=repoDir/doesNotExist', async () => { + const repoDir = await initTestRepo(); + const cwd = path.join(repoDir, 'doesNotExist'); + await expect(getGitRepoRoot(cwd)).rejects.toThrow( + /Couldn't find the git repository root directory/, + ); + }); }); diff --git a/packages/docusaurus-utils/src/vcs/gitUtils.ts b/packages/docusaurus-utils/src/vcs/gitUtils.ts index 5c34353d01..e471bae468 100644 --- a/packages/docusaurus-utils/src/vcs/gitUtils.ts +++ b/packages/docusaurus-utils/src/vcs/gitUtils.ts @@ -264,13 +264,30 @@ export async function getGitCreation( } export async function getGitRepoRoot(cwd: string): Promise { + const createErrorMessageBase = () => { + return `Couldn't find the git repository root directory +Running ${logger.code('git rev-parse --show-toplevel')} from cwd=${logger.path( + cwd, + )})`; + }; + const result = await execa('git', ['rev-parse', '--show-toplevel'], { cwd, + }).catch((error) => { + // We enter this rejection when cwd is not a dir for example + throw new Error( + `${createErrorMessageBase()} +The command executed throws an error`, + {cause: error}, + ); }); if (result.exitCode !== 0) { throw new Error( - `Failed to retrieve the git repository root with exit code ${result.exitCode}: ${result.stderr}`, + `${createErrorMessageBase()} +The command returned exit code ${logger.code(result.exitCode)}: ${logger.subdue( + result.stderr, + )}`, ); }