Skip to content

Instantly share code, notes, and snippets.

@matthew-brett
Last active June 18, 2024 11:19
Show Gist options
  • Save matthew-brett/8ee8dff72940823fe05940faa8d1baf8 to your computer and use it in GitHub Desktop.
Save matthew-brett/8ee8dff72940823fe05940faa8d1baf8 to your computer and use it in GitHub Desktop.
Make NbGitPuller URL for input URL
#!/usr/bin/env python3
""" Convert Github notebook URL to NBGitPuller URL
See: https://nbgitpuller.readthedocs.io/en/latest/link.html
"""
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from warnings import warn
from urllib.parse import urlparse
DEFAULT_HUB = 'https://ds.lis.2i2c.cloud'
def to_url(url, hub_url, interface_prefix='tree', branch=None):
prefix = f'{hub_url}/hub/user-redirect/git-pull?repo='
up = urlparse(url)
path_parts = up.path.split('/')[1:]
gh_user, gh_repo, *other_parts = path_parts
repo_path = f'{prefix}{up.scheme}%3A//{up.netloc}/{gh_user}/{gh_repo}'
if not (other_parts):
return repo_path + ('' if branch is None else f'&branch={branch}')
if not other_parts[0] == 'blob':
raise RuntimeError(
'Expecting "blob" as third path component; try copying URL direct '
'from Github interface')
_, input_branch, *nb_parts = other_parts
if branch and branch != input_branch:
warn(f'URL branch "{input_branch}" does not match input argument '
f'branch "{branch}" - preferring "{branch}".')
branch = branch if branch else input_branch
urlpath = '/'.join([interface_prefix, gh_repo] + nb_parts)
return f'{repo_path}&urlpath={urlpath}&branch={branch}'
def get_parser():
parser = ArgumentParser(description=__doc__, # Usage from docstring
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('url',
help='Github URL to repository or notebook')
parser.add_argument('-u', '--hub-url', default=DEFAULT_HUB,
help=f'URL for base hub (default "{DEFAULT_HUB}"')
parser.add_argument('-c', '--classic', action='store_true',
help='If set, use classic interface, not lab')
parser.add_argument('-b', '--branch',
help=f'Branch (use Github default if not specified)')
return parser
def main():
parser = get_parser()
args = parser.parse_args()
interface_prefix = 'tree' if args.classic else 'lab/tree'
print(to_url(args.url, args.hub_url, interface_prefix, args.branch))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment