Skip to content

Commit

Permalink
fix(publish): better error when git branch cannot be detected (#4488)
Browse files Browse the repository at this point in the history
  • Loading branch information
Whitewater committed Mar 27, 2022
1 parent bc35dff commit cfe345b
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/mean-zoos-move.md
@@ -0,0 +1,5 @@
---
"@pnpm/plugin-commands-publishing": patch
---

Show friendly error message when get current git branch name error.
9 changes: 7 additions & 2 deletions packages/plugin-commands-publishing/src/gitChecks.ts
Expand Up @@ -12,8 +12,13 @@ export async function isGitRepo () {
}

export async function getCurrentBranch () {
const { stdout } = await execa('git', ['symbolic-ref', '--short', 'HEAD'])
return stdout
try {
const { stdout } = await execa('git', ['symbolic-ref', '--short', 'HEAD'])
return stdout
} catch (_: any) { // eslint-disable-line
// Command will fail with code 1 if the HEAD is detached.
return null
}
}

export async function isWorkingTreeClean () {
Expand Down
9 changes: 9 additions & 0 deletions packages/plugin-commands-publishing/src/publish.ts
Expand Up @@ -116,6 +116,15 @@ export async function handler (
}
const branches = opts.publishBranch ? [opts.publishBranch] : ['master', 'main']
const currentBranch = await getCurrentBranch()
if (currentBranch === null) {
throw new PnpmError(
'GIT_UNKNOWN_BRANCH',
`The Git HEAD may not attached to any branch, but your "publish-branch" is set to "${branches.join('|')}".`,
{
hint: GIT_CHECKS_HINT,
}
)
}
if (!branches.includes(currentBranch)) {
const { confirm } = await prompt({
message: `You're on branch "${currentBranch}" but your "publish-branch" is set to "${branches.join('|')}". \
Expand Down
25 changes: 25 additions & 0 deletions packages/plugin-commands-publishing/test/gitChecks.ts
Expand Up @@ -135,3 +135,28 @@ test('publish: fails git check if branch is not up-to-date', async () => {
new PnpmError('GIT_NOT_LATEST', 'Remote history differs. Please pull changes.')
)
})

test('publish: fails git check if HEAD is detached', async () => {
prepare({
name: 'test-publish-package.json',
version: '0.0.0',
})

await execa('git', ['init'])
await execa('git', ['config', 'user.email', 'x@y.z'])
await execa('git', ['config', 'user.name', 'xyz'])
await execa('git', ['add', '*'])
await execa('git', ['commit', '-m', 'init', '--no-gpg-sign'])
await execa('git', ['commit', '--allow-empty', '--allow-empty-message', '-m', '', '--no-gpg-sign'])
await execa('git', ['checkout', 'HEAD~1'])

await expect(
publish.handler({
...DEFAULT_OPTS,
argv: { original: ['publish', ...CREDENTIALS] },
dir: process.cwd(),
}, [])
).rejects.toThrow(
new PnpmError('GIT_UNKNOWN_BRANCH', 'The Git HEAD may not attached to any branch, but your "publish-branch" is set to "master|main".')
)
})

0 comments on commit cfe345b

Please sign in to comment.