Last active
December 8, 2017 12:05
-
-
Save wolkenarchitekt/531217fcc6034b8c862facf09ea78d37 to your computer and use it in GitHub Desktop.
Get git url of file (works for Github and Gitlab)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Show URL of file in git, optionally open URL in browser. | |
# In contrast to 'hub' this works to Github *and* Gitlab. | |
# | |
# Requirements: GitPython, click | |
import logging | |
import os | |
import sys | |
import webbrowser | |
import click | |
import git | |
from git import Repo | |
from git.exc import GitCommandError | |
logger = logging.getLogger(__name__) | |
@click.command() | |
@click.argument('filename') | |
@click.option('-v', '--verbose', count=True) | |
@click.option('-b', '--browse', is_flag=True, help="Open in webbrowser") | |
@click.option('-l', '--line', help="Line number") | |
def git_url(filename, verbose, browse, line): | |
if verbose: | |
logging.basicConfig(level=logging.DEBUG) | |
file_abspath = os.path.abspath(filename) | |
repo = Repo(filename, search_parent_directories=True) | |
git_root = repo.git.rev_parse("--show-toplevel") | |
rel_path = file_abspath.split(git_root + '/')[1] | |
branch = repo.active_branch.name | |
try: | |
git.cmd.Git().show_branch('remotes/origin/{}'.format(branch)) | |
except GitCommandError: | |
sys.exit("Branch '{}' does not exist on remote.".format(branch)) | |
url = repo.config_reader().get_value('remote "origin"', 'url') | |
url = url.replace('git@', '') | |
url = url.replace('.git', '') | |
url = url.replace(':', '/') | |
logger.debug("Git root: {}".format(git_root)) | |
logger.debug("URL: {}".format(url)) | |
url = ('https://{url}/blob/{branch}/{rel_path}' | |
.format(**{'url': url, 'branch': branch, 'rel_path': rel_path})) | |
if line: | |
url += '#L{}'.format(line) | |
click.echo(url) | |
if browse: | |
webbrowser.open(url) | |
if __name__ == '__main__': | |
git_url() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment