diff --git a/source/git-util.js b/source/git-util.js index 25bb1505..34ca8c2b 100644 --- a/source/git-util.js +++ b/source/git-util.js @@ -55,10 +55,9 @@ exports.currentBranch = async () => { }; exports.verifyCurrentBranchIsReleaseBranch = async releaseBranch => { - const expectedBranch = await exports.defaultBranch(releaseBranch); const currentBranch = await exports.currentBranch(); - if (!expectedBranch === currentBranch) { - throw new Error(`Not on \`${expectedBranch}\` branch. Use --any-branch to publish anyway, or set a different release branch using --branch.`); + if (currentBranch !== releaseBranch) { + throw new Error(`Not on \`${releaseBranch}\` branch. Use --any-branch to publish anyway, or set a different release branch using --branch.`); } }; @@ -133,26 +132,30 @@ exports.tagExistsOnRemote = async tagName => { } }; -exports.defaultBranch = async options => { - if (options.releaseBranch) { - return options.releaseBranch; +async function hasLocalBranch(branch) { + try { + await execa('git', [ + 'show-ref', + '--verify', + '--quiet', + `refs/heads/${branch}` + ]); + return true; + } catch { + return false; } +} +exports.defaultBranch = async () => { for (const branch of ['main', 'master', 'gh-pages']) { - try { - // eslint-disable-next-line no-await-in-loop - await execa('git', [ - 'show-ref', - '--verify', - '--quiet', - `refs/heads/${branch}` - ]); + // eslint-disable-next-line no-await-in-loop + if (await hasLocalBranch(branch)) { return branch; - } catch {} + } } throw new Error( - 'Could not determine a default branch. Please specify one via --branch.' + 'Could not infer the default Git branch. Please specify one with the --branch flag or with an .np-config file.' ); }; diff --git a/source/index.js b/source/index.js index bc629844..8e4bc561 100644 --- a/source/index.js +++ b/source/index.js @@ -47,6 +47,8 @@ module.exports = async (input = 'patch', options) => { options.cleanup = false; } + options.releaseBranch = options.releaseBranch || git.defaultBranch(); + const pkg = util.readPkg(options.contents); const runTests = options.tests && !options.yolo; const runCleanup = options.cleanup && !options.yolo; diff --git a/source/ui.js b/source/ui.js index 02bd3386..6d86a37b 100644 --- a/source/ui.js +++ b/source/ui.js @@ -72,6 +72,7 @@ module.exports = async (options, pkg) => { const repoUrl = pkg.repository && githubUrlFromGit(pkg.repository.url, {extraBaseUrls}); const pkgManager = options.yarn ? 'yarn' : 'npm'; const registryUrl = await getRegistryUrl(pkgManager, pkg); + const releaseBranch = options.releaseBranch || await git.defaultBranch(); if (options.runPublish) { checkIgnoreStrategy(pkg); @@ -169,7 +170,6 @@ module.exports = async (options, pkg) => { } ]; - const releaseBranch = await git.defaultBranch(options.releaseBranch); const {hasCommits, releaseNotes} = await printCommitLog(repoUrl, registryUrl, releaseBranch); if (options.version) {