diff options
author | 2023-05-10 04:32:07 +0800 | |
---|---|---|
committer | 2023-05-10 04:32:07 +0800 | |
commit | 747b87a6358c729e54148021d44c94e828603e01 (patch) | |
tree | dbe2d54ce393ce66bc9ada86655647ed2a586e00 /source/github-helpers/get-current-git-ref.ts | |
parent | 12532fc4c149f5922fffba89ee2624bf3982e975 (diff) | |
download | refined-github-747b87a6358c729e54148021d44c94e828603e01.tar.gz refined-github-747b87a6358c729e54148021d44c94e828603e01.tar.zst refined-github-747b87a6358c729e54148021d44c94e828603e01.zip |
Reliability fixes for `default-branch-button` (#6629)
Diffstat (limited to 'source/github-helpers/get-current-git-ref.ts')
-rw-r--r-- | source/github-helpers/get-current-git-ref.ts | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/source/github-helpers/get-current-git-ref.ts b/source/github-helpers/get-current-git-ref.ts new file mode 100644 index 00000000..4eefbabb --- /dev/null +++ b/source/github-helpers/get-current-git-ref.ts @@ -0,0 +1,32 @@ +import {getCurrentBranchFromFeed} from './index.js'; + +const typesWithGitRef = new Set(['tree', 'blob', 'blame', 'edit', 'commit', 'commits', 'compare']); +const titleWithGitRef = / at (?<branch>[.\w-/]+)( ยท [\w-]+\/[\w-]+)?$/i; + +/** This only works with URL and page title. Must not be async because it's used by GitHubURL */ +export default function getCurrentGitRef(pathname = location.pathname, title = document.title): string | undefined { + if (!pathname.startsWith('/')) { + throw new TypeError(`Expected pathname starting with /, got "${pathname}"`); + } + + const [type, gitRefIfNonSlashed] = pathname.split('/').slice(3); + if (!type || !typesWithGitRef.has(type)) { + // Root; or piece of information not applicable to the page + return; + } + + // Slashed branches on `commits` + if (type === 'commits') { + return getCurrentBranchFromFeed()!; + } + + // Slashed branches on `blob` and `tree` + const parsedTitle = titleWithGitRef.exec(title); + if (parsedTitle) { + return parsedTitle.groups!.branch; + } + + // Couldn't ensure it's not slashed, so we'll return the first piece whether correct or not + // TODO: extract from `ref-selector` if available https://github.com/refined-github/refined-github/issues/6557 + return gitRefIfNonSlashed; +} |