| 1 | from urllib.parse import urlparse, quote_plus |
| 2 | |
| 3 | |
| 4 | def from_string(text): |
| 5 | url = urlparse(text) |
| 6 | if url.scheme != "project": # schema must be repository:// |
| 7 | raise Exception("Wrong scheme, should be project://") |
| 8 | if not url.path: |
| 9 | raise Exception("Missing slug part") |
| 10 | split = url.path.split("@", 1) |
| 11 | if len(split) == 2: |
| 12 | domain = urlparse(f"ignore://{split[1]}") |
| 13 | return (split[0], domain.netloc) |
| 14 | return (split[0], None) |
| 15 | |
| 16 | |
| 17 | def to_string(slug, domain=None): |
| 18 | if domain: |
| 19 | return quote_plus(f"project:{slug}@{domain}") |
| 20 | else: |
| 21 | return quote_plus(f"project:{slug}") |
| 22 | |
| 23 | |
| 24 | print(from_string("project://fuu/bar@example.org")) |
| 25 | print(from_string("project://fuu/bar/baz/qux@example.org")) |
| 26 | print(from_string("project://fuu/bar/baz/qux")) |
| 27 | print(from_string("project://~hello/world")) |
| 28 | print(from_string("project://~hello/world@example.org")) |
| 29 | print(to_string("fuu/bar/baz", None)) |
| 30 | print(to_string("fuu/bar/baz", "example.org")) |