diff --git a/README.md b/README.md index c8aaef5..18796e2 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ npm install -g build-this-branch | Flag | Description | | - | - | | `-c, --build-command ` | The command to build the branch. (default: `npm run build`) | -| `-b, --built-branch ` | The name of the built branch. Defaults to prefixing "built/" to the current branch. | +| `-b, --built-branch ` | The name of the built branch. Defaults to prefixing "built/" to the current branch or tag name. | | `-r, --remote ` | The remote to push to. (default: `origin`) | | `-d, --dry` | Dry run mode. Will not build, commit, or push to the remote. | | `-h, --help` | Show help | diff --git a/src/index.ts b/src/index.ts index 16043ab..3eafa48 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,17 +22,33 @@ async function assertCleanTree() { } } -async function getCurrentBranchName() { - try { - const { stdout } = await execa('git', ['symbolic-ref', '--short', '-q', 'HEAD']); - return stdout.trim(); - } catch (error) { - if (error instanceof Error) { - throw new TypeError(`Failed to get current branch name\n${error.message}`); - } +async function getCurrentBranchOrTagName() { + // eslint-disable-next-line @typescript-eslint/no-empty-function + const silenceError = () => {}; + + /** + * This commands supports older versions of Git, but since v2.22, you can do: + * git branch --show-current + */ + const branch = await execa('git', ['symbolic-ref', '--short', '-q', 'HEAD']).then( + ({ stdout }) => stdout, + silenceError, + ); - throw error; + if (branch) { + return branch; } + + const tag = await execa('git', ['describe', '--tags']).then( + ({ stdout }) => stdout, + silenceError, + ); + + if (tag) { + return tag; + } + + throw new Error('Failed to get current branch name'); } async function readJson(path: string) { @@ -57,7 +73,7 @@ const { stringify } = JSON; type: String, alias: 'b', placeholder: '', - description: 'The name of the built branch. Defaults to prefixing "built/" to the current branch.', + description: 'The name of the built branch. Defaults to prefixing "built/" to the current branch or tag name.', }, buildCommand: { type: String, @@ -86,7 +102,7 @@ const { stringify } = JSON; }); await assertCleanTree(); - const branchFrom = await getCurrentBranchName(); + const branchFrom = await getCurrentBranchOrTagName(); const packageJsonPath = await pkgUp(); if (!packageJsonPath) {