diff --git a/lib/index.js b/lib/index.js index c5d1045..b10716e 100644 --- a/lib/index.js +++ b/lib/index.js @@ -33,12 +33,17 @@ const gitUp = require("git-up"); * - `git_suffix` (Boolean): Whether to add the `.git` suffix or not. * */ -function gitUrlParse(url) { +function gitUrlParse(url, refs=undefined) { + refs = refs || [] if (typeof url !== "string") { throw new Error("The url must be a string."); } + if (!refs.every(item => typeof item === 'string')) { + throw new Error("The refs should contain only strings") + } + const shorthandRe = /^([a-z\d-]{1,39})\/([-\.\w]{1,100})$/i if (shorthandRe.test(url)) { @@ -242,6 +247,12 @@ function gitUrlParse(url) { urlInfo.ref = ""; } } + + if (refs.length !== 0 && urlInfo.ref) { + urlInfo.ref = findLongestMatchingSubstring(urlInfo.href, refs) || urlInfo.ref + urlInfo.filepath = urlInfo.href.split(urlInfo.ref + "/")[1] + } + return urlInfo; } @@ -315,4 +326,16 @@ function buildPath(obj) { } } +function findLongestMatchingSubstring(string, array) { + let longestMatch = ""; + + array.forEach(item => { + if (string.includes(item) && item.length > longestMatch.length) { + longestMatch = item; + } + }); + + return longestMatch; +} + module.exports = gitUrlParse; diff --git a/test/index.js b/test/index.js index 0d8a84e..96f8ba3 100644 --- a/test/index.js +++ b/test/index.js @@ -532,4 +532,17 @@ tester.describe("parse urls", test => { test.expect(res.filepath).toBe("pkg/blob/data.yaml"); test.expect(res.toString()).toBe("https://github.com/owner/id"); }); + + test.should("parse branch names with slashes, when refs are provided", () => { + var res = gitUrlParse("https://github.com/owner/id/blob/branch1/branch2/data.yaml", ["branch1/branch2", "branch1"]); + test.expect(res.pathname).toBe("/owner/id/blob/branch1/branch2/data.yaml"); + test.expect(res.ref).toBe("branch1/branch2"); + test.expect(res.filepath).toBe("data.yaml"); + var res = gitUrlParse("https://github.com/owner/id/blob/branch1/branch2/branch3/folder/data.yaml", ["branch1/branch2/branch3", "branch1"]); + test.expect(res.ref).toBe("branch1/branch2/branch3"); + test.expect(res.filepath).toBe("folder/data.yaml"); + var res = gitUrlParse("https://github.com/owner/id/blob/main/folder/data.yaml", ["branch1/branch2/branch3", "main"]); + test.expect(res.ref).toBe("main"); + test.expect(res.filepath).toBe("folder/data.yaml"); + }); });