简体   繁体   中英

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. Eg

git@github.com:foo/bar.git -> bar

I've tried using a regex:

>>> url = 'git@github.com: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.

You could split your url on slashes, then take the last entry without the last 4 characters

url.split("/")[-1][:-4]
>>> import posixpath as path
>>> path.splitext(path.split('https://github.com/foo/bar.git')[1])[0]
'bar'
>>> path.splitext(path.split('git@github.com:foo/bar.git')[1])[0]
'bar'

This seems like the most robust version:

>>> url
'git@github.com:foo/bar.git'
>>> url.rstrip('/').rsplit('/', maxsplit=1)[-1].removesuffix('.git')
'bar'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM