Skip to content

Instantly share code, notes, and snippets.

@drammock
Last active June 17, 2025 22:36
Show Gist options
  • Save drammock/78d2d3c9837aafd1259866c7b936b9e4 to your computer and use it in GitHub Desktop.
Save drammock/78d2d3c9837aafd1259866c7b936b9e4 to your computer and use it in GitHub Desktop.
import re
tests = [
("https://bitbucket.org", "bitbucket"),
("https://bitbucket.org/atlassian", "atlassian"),
("https://bitbucket.org/atlassian/workspace/overview", "atlassian"),
("https://bitbucket.org/atlassian/aui", "atlassian/aui"),
("https://bitbucket.org/atlassian/aui/", "atlassian/aui"),
("https://bitbucket.org/atlassian/aui/pull-requests/4758", "atlassian/aui#4758"),
("https://bitbucket.org/atlassian/aui/issues/375583", "atlassian/aui#375583"),
("https://bitbucket.org/atlassian/aui/issues", "atlassian/aui/issues"),
("https://bitbucket.org/atlassian/aui/issues/", "atlassian/aui/issues"),
("https://bitbucket.org/atlassian/aui/pipelines", "atlassian/aui/pipelines"),
(
"https://bitbucket.org/atlassian/aui/pipelines/results/14542",
"atlassian/aui/pipelines/results/14542",
),
(
"https://bitbucket.org/atlassian/aui/commits/de41ded719e579d0ed4ffb8a81c29bb9ada10011",
"atlassian/aui@de41ded",
),
(
"https://bitbucket.org/atlassian/aui/branch/future/10.0.x",
"atlassian/aui@future/10.0.x",
),
(
"https://bitbucket.org/atlassian/atlas_fe/branch/Vadym_Kovalskiy/securityassistantyml-edited-online-with--1704961113691",
"atlassian/atlas_fe@Vadym_Kovalskiy/securityassistantyml-edited-online-with--1704961113691",
),
(
"https://bitbucket.org/pybtex-devs/pybtex/issues/169/replace-pkg_resources-with",
"pybtex-devs/pybtex#169",
),
(
"https://bitbucket.org/pybtex-devs/pybtex/branch/feature/fix-pytest-warning",
"pybtex-devs/pybtex@feature/fix-pytest-warning",
),
]
def shorten_bitbucket_url(url):
pattern = re.compile(
r"(?P<scheme>https?:\/\/)?"
r"(?:(?P<domain>bitbucket)\.org)"
r"(?:\/(?P<user>[\w-]+))?"
r"(?:\/workspace\/overview)?"
r"(?:\/(?P<repo>[\w-]+))?"
r"(?:\/issues\/(?P<issue>[0-9]+))?"
r"(?:\/pull-requests\/(?P<pr>[0-9]+))?"
r"(?:\/commits\/(?P<hash>[0-9a-f]+))?"
r"(?:\/branch\/(?P<branch>[\/\.\w-]+))?"
r"(?:\/(?P<leftovers>[\/\.\w-]+))?"
)
if res := pattern.match(url):
gd = res.groupdict()
if not gd["user"]:
return gd["domain"]
if not gd["repo"]:
return gd["user"]
result = "{user}/{repo}"
if gd["hash"]:
gd["shorthash"] = gd["hash"][:7]
result += "@{shorthash}"
elif gd["issue"]:
result += "#{issue}"
elif gd["pr"]:
result += "#{pr}"
elif gd["branch"]:
result += "@{branch}"
elif gd["leftovers"]:
gd["left"] = gd["leftovers"].rstrip("/")
result += "/{left}"
return result.format_map(gd)
for url, expected in tests:
result = shorten_bitbucket_url(url)
assert result == expected, f"{result} != {expected}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment