from urllib.parse import urlparse, quote_plus def from_string(text): url = urlparse(text) if url.scheme != "project": # schema must be repository:// raise Exception("Wrong scheme, should be project://") if not url.path: raise Exception("Missing slug part") split = url.path.split("@", 1) if len(split) == 2: domain = urlparse(f"ignore://{split[1]}") return (split[0], domain.netloc) return (split[0], None) def to_string(slug, domain=None): if domain: return quote_plus(f"project:{slug}@{domain}") else: return quote_plus(f"project:{slug}") print(from_string("project://fuu/bar@example.org")) print(from_string("project://fuu/bar/baz/qux@example.org")) print(from_string("project://fuu/bar/baz/qux")) print(from_string("project://~hello/world")) print(from_string("project://~hello/world@example.org")) print(to_string("fuu/bar/baz", None)) print(to_string("fuu/bar/baz", "example.org"))