from urllib.parse import urlparse, quote_plus def from_string(text): url = urlparse(text) if not url.path: return (None, None) split = url.path.split("@", 1) if len(split) == 2: return (split[0], split[1]) return (split[0], None) def to_string(slug, domain=None): if domain: return quote_plus(f"repository:{slug}@{domain}") else: return quote_plus(f"repository:{slug}") print(from_string("repository:fuu/bar@example.org")) print(from_string("repository:fuu/bar/baz/qux@example.org")) print(from_string("repository:fuu/bar/baz/qux")) print(from_string("repository:~hello/world")) print(from_string("repository:~hello/world@example.org")) print(from_string("repository:~hello/world@example.org@aaaa")) print(to_string("fuu/bar/baz", None)) print(to_string("fuu/bar/baz", "example.org"))