Reputation: 16123
I need to get the directory name that Git would use for cloning a repo from the repo's URL, in Python. E.g.
[email protected]:foo/bar.git -> bar
I've tried using a regex:
>>> url = '[email protected]:foo/bar.git'
>>> import re
>>> re.sub(r'^.*/(.*?)(\.git)?$', r'\1', url)
'bar'
Is there a better solution? I need to support both SSH and HTTPS URLs.
Upvotes: 1
Views: 1373
Reputation: 16123
This seems like the most robust version:
>>> url
'[email protected]:foo/bar.git'
>>> url.rstrip('/').rsplit('/', maxsplit=1)[-1].removesuffix('.git')
'bar'
Upvotes: 1
Reputation: 95101
>>> import posixpath as path
>>> path.splitext(path.split('https://github.com/foo/bar.git')[1])[0]
'bar'
>>> path.splitext(path.split('[email protected]:foo/bar.git')[1])[0]
'bar'
Upvotes: 0
Reputation: 43330
You could split your url on slashes, then take the last entry without the last 4 characters
url.split("/")[-1][:-4]
Upvotes: 1