diff --git a/src/utils/__tests__/git.test.ts b/src/utils/__tests__/git.test.ts new file mode 100644 index 00000000..c1fadfa5 --- /dev/null +++ b/src/utils/__tests__/git.test.ts @@ -0,0 +1,41 @@ +import { getLatestTag } from '../git'; +import * as loggerModule from '../../logger'; + +describe('getLatestTag', () => { + it('returns latest tag in the repo by calling `git describe`', async () => { + const git = { + raw: jest.fn().mockResolvedValue('1.0.0'), + } as any; + + const latestTag = await getLatestTag(git); + expect(latestTag).toBe('1.0.0'); + + expect(git.raw).toHaveBeenCalledWith('describe', '--tags', '--abbrev=0'); + }); + + it('logs a helpful error message if the git call throws', async () => { + loggerModule.setLevel(loggerModule.LogLevel.Debug); + const loggerErrorSpy = jest + .spyOn(loggerModule.logger, 'error') + .mockImplementation(() => { + // just to avoid spamming the test output + }); + + const error = new Error('Nothing to describe'); + const git = { + raw: jest.fn().mockRejectedValue(error), + } as any; + + try { + await getLatestTag(git); + } catch (e) { + expect(e).toBe(error); + } + + expect(loggerErrorSpy).toHaveBeenCalledWith( + expect.stringContaining( + "If you're releasing for the first time, check if your repo contains any tags" + ) + ); + }); +}); diff --git a/src/utils/git.ts b/src/utils/git.ts index cb5536c5..210c8f8f 100644 --- a/src/utils/git.ts +++ b/src/utils/git.ts @@ -35,7 +35,15 @@ export async function getDefaultBranch( export async function getLatestTag(git: SimpleGit): Promise { // This part is courtesy of https://stackoverflow.com/a/7261049/90297 - return (await git.raw('describe', '--tags', '--abbrev=0')).trim(); + try { + return (await git.raw('describe', '--tags', '--abbrev=0')).trim(); + } catch (e) { + logger.error( + 'Couldn\'t get the latest tag! If you\'re releasing for the first time, check if your repo contains any tags. If not, add one manually and try again: `git tag 0.0.0 "$(git log -1 --reverse --format=%h)"' + ); + // handle this error in the global error handler + throw e; + } } export async function getChangesSince(