Git: Read a remote URL

Take apart the addresses that git remote -v shows.

What to build

A program that splits Git remote URLs into protocol, host, owner and repository.

Requirements

  • Supported forms: https://HOST/OWNER/REPO(.git), git@HOST:OWNER/REPO(.git) and ssh://git@HOST/OWNER/REPO(.git). The owner may contain slashes (groups and subgroups).
  • Print PROTOCOL HOST OWNER REPO with PROTOCOL https or ssh.

Input

Line 1: n. Then n URLs.

Output

n lines.

Constraints

n ≤ 100.

Example

Input:

2
https://github.com/octo/hello.git
git@github.com:octo/hello.git

Output:

https github.com octo hello
ssh github.com octo hello

Why it works

Both forms name the same three things, the server, the owner and the repository, just with different punctuation.

Examples

Example 1 · Input
2
https://github.com/octo/hello.git
git@github.com:octo/hello.git
Expected output
https github.com octo hello
ssh github.com octo hello
Example 2 · Input
1
https://gitlab.com/group/sub/project
Expected output
https gitlab.com group/sub project

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

SSH addresses look like `git@HOST:PATH` or start with `ssh://`; web addresses start with `https://`.

Hint 2

Remove a final `.git`; the repository is the last part of the path and the owner is everything before it.

Solution

Show one correct solution (try it yourself first)
for _ in range(int(input())):
    url = input().strip()
    if url.startswith("https://"):
        protocol, rest = "https", url[len("https://"):]
        host, _, path = rest.partition("/")
    elif url.startswith("ssh://"):
        protocol, rest = "ssh", url[len("ssh://"):]
        host, _, path = rest.split("@", 1)[-1].partition("/")
    else:
        protocol = "ssh"
        host, _, path = url.split("@", 1)[-1].partition(":")
    if path.endswith(".git"):
        path = path[:-4]
    owner, _, repo = path.rstrip("/").rpartition("/")
    print(protocol, host, owner, repo)

Lesson: Remotes: clone, fetch, pull and push →