From 63e4f8966596c2d7376463482545c3bb60ac35ef Mon Sep 17 00:00:00 2001 From: EnixCoda Date: Mon, 1 Feb 2021 16:42:47 +0800 Subject: [PATCH] fix: match incomplete sha --- src/platforms/GitHub/URLHelper.ts | 49 +++++++++++++++++++------------ 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/src/platforms/GitHub/URLHelper.ts b/src/platforms/GitHub/URLHelper.ts index e388fd0..229317d 100644 --- a/src/platforms/GitHub/URLHelper.ts +++ b/src/platforms/GitHub/URLHelper.ts @@ -33,11 +33,15 @@ export function isInPullPage() { } function isCommitPath(path: string[]) { - return isCompleteCommitSHA(path[0]) + return path[0] ? isCompleteCommitSHA(path[0]) : false } -function isCompleteCommitSHA(sha?: string) { - return typeof sha === 'string' && /^[abcdef0-9]{40}$/i.test(sha) +function isCompleteCommitSHA(sha: string) { + return /^[abcdef0-9]{40}$/i.test(sha) +} + +function isPossiblyCommitSHA(sha: string) { + return /^[abcdef0-9]+$/i.test(sha) } export function getCurrentPath(branchName = '') { @@ -52,22 +56,29 @@ export function getCurrentPath(branchName = '') { if (path[0] === 'HEAD') path.shift() else { const splitBranchName = branchName.split('/') - while (splitBranchName.length) { - if ( - splitBranchName[0] === path[0] || - // Keep consuming as their heads are same - (splitBranchName.length === 1 && splitBranchName[0].startsWith(path[0])) - // This happens when visiting URLs like /blob/{commitSHA}/path/to/file - // and {commitSHA} is shorter than we got from DOM - ) { - splitBranchName.shift() - path.shift() - } else { - raiseError(new Error(`branch name and path prefix not match`), { - branchName, - path: parse().path, - }) - return [] + if ( + splitBranchName.length === 1 && + path.length > 0 && + isPossiblyCommitSHA(splitBranchName[0]) && + isPossiblyCommitSHA(path[0]) && + (splitBranchName[0].startsWith(path[0]) || path[0].startsWith(splitBranchName[0])) + // This happens when visiting URLs like /blob/{commitSHA}/path/to/file + // and {commitSHA} does not match the one got from DOM + ) { + splitBranchName.shift() + path.shift() + } else { + while (splitBranchName.length) { + if (splitBranchName[0] === path[0]) { + splitBranchName.shift() + path.shift() + } else { + raiseError(new Error(`branch name and path prefix not match`), { + branchName, + path: parse().path, + }) + return [] + } } } }