git-year-wrapped/lib/repo-label.mjs
2026-11-26 17:43:53 +03:00

32 lines
972 B
JavaScript

/**
* Turn any git remote URL into a short "owner/repo" style label for the
* card title. Falls back to the raw URL if the shape is unrecognized.
*
* Handles https://host/owner/repo(.git), git@host:owner/repo.git, and
* ssh://git@host/owner/repo.git - the same three shapes GitHub, GitLab and
* Rithub all use.
*
* @param {string} repoUrl
* @returns {string}
*/
export function repoLabelFromUrl(repoUrl) {
const stripped = repoUrl.replace(/\.git$/, "");
const scpMatch = stripped.match(/^[^@]+@[^:]+:(.+)$/);
if (scpMatch) {
const parts = scpMatch[1].split("/").filter(Boolean);
if (parts.length >= 2) return parts.slice(-2).join("/");
}
try {
const url = new URL(stripped);
const parts = url.pathname.split("/").filter(Boolean);
if (parts.length >= 2) return parts.slice(-2).join("/");
if (parts.length === 1) return parts[0];
} catch {
// not a parseable URL - fall through to the raw string
}
return stripped;
}