planetp
planetp

Reputation: 16123

How to extract the directory name from a Git repository URL?

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

Answers (3)

planetp
planetp

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

phd
phd

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

Sayse
Sayse

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

Related Questions