Convert a git url

    url will look like
    https://github.com/ARMmbed/mbed-cloud-sdk-python.git
    or
    git@github.com:ARMmbed/mbed-cloud-sdk-python.git
    we want:
    https://${GITHUB_TOKEN}@github.com/ARMmbed/mbed-cloud-sdk-python-private.git
970913
def git_url_ssh_to_https(url):
    
    path = url.split('github.com', 1)[1][1:].strip()
    new = 'https://{GITHUB_TOKEN}@github.com/%s' % path
    print('rewriting git url to: %s' % new)
    return new.format(GITHUB_TOKEN=os.getenv('GITHUB_TOKEN'))
257542
def get_github_hostname_user_repo_from_url(url):
    
    parsed = parse.urlparse(url)
    if parsed.netloc == '':
        # Probably ssh
        host, sep, path = parsed.path.partition(":")
        if "@" in host:
            username, sep, host = host.partition("@")
    else:
        path = parsed.path[1:].rstrip('/')
        host = parsed.netloc
    user, repo = path.split("/", 1)
    return host, user, repo[:-4] if repo.endswith('.git') else repo
1224751
def get_public_url(self, doc_id, branch='master'):
        
        name, path_frag = self.get_repo_and_path_fragment(doc_id)
        return 'https://raw.githubusercontent.com/OpenTreeOfLife/' + name + '/' + branch + '/' + path_frag
80678
def create_basic_url(self):
        
        if self.username is None:
            if self.namespace is None:
                request_url = "{}/api/0/{}/".format(
                    self.instance, self.repo)
            else:
                request_url = "{}/api/0/{}/{}/".format(
                    self.instance, self.namespace, self.repo)
        else:
            if self.namespace is None:
                request_url = "{}/api/0/fork/{}/{}/".format(
                    self.instance, self.username, self.repo)
            else:
                request_url = "{}/api/0/fork/{}/{}/{}/".format(
                    self.instance, self.username, self.namespace, self.repo)
        return request_url
946190
function githubRepo (options) {
  try {
    const url = options.data.root.package.repository.url
    const match = url.match(/.*?(:\/\/|@)github\.com[/:](.*?)(#.*?)?$/)
    if (match) {
      return match[2].replace(/\.git$/, '')
    } else {
      return null
    }
  } catch (e) {
    // No repositor-url exists
    return null
  }
}
660019
def webhook_url(self):
        """"""
        webhook_token = ProviderToken.query.filter_by(
            id=self.account.extra_data['tokens']['webhook']
        ).first()
        if webhook_token:
            wh_url = current_app.config.get('GITHUB_WEBHOOK_RECEIVER_URL')
            if wh_url:
                return wh_url.format(token=webhook_token.access_token)
            else:
                raise RuntimeError('You must set GITHUB_WEBHOOK_RECEIVER_URL.')
437061
function getOwnerAndRepo(url) {
  let match = url.match(/^git@github\.com:(.*)\.git$/);
  match = match || url.match(/^git\+https:\/\/github\.com\/(.*)\.git$/);
  const gitUrlBase = match && match[1];
  return (gitUrlBase || url).split('/');
}
124817
def _repo_url_to_path(self, repo):
        """"""
        repo = repo.replace('http://', '')
        repo = repo.replace('https://', '')
        repo = repo.replace('/', '_')

        return os.sep.join([self._data_directory, repo])
1003379
def mk_url(self, *args, **kwargs):
        
        params = urlencode(kwargs)
        url = '/' + '/'.join([x for x in args if x])
        if params:
            url += '?' + params
        return url
1044162
def urls(self):
        """"""
        try:
            remote_details = self.repo.git.remote("get-url", "--all", self.name)
            for line in remote_details.split('\n'):
                yield line
        except GitCommandError as ex:
            ## We are on git < 2.7 (i.e TravisCI as of Oct-2016),
            #  so `get-utl` command does not exist yet!
            #    see: https://github.com/gitpython-developers/GitPython/pull/528#issuecomment-252976319
            #    and: http://stackoverflow.com/a/32991784/548792
            #
            if 'Unknown subcommand: get-url' in str(ex):
                try:
                    remote_details = self.repo.git.remote("show", self.name)
                    for line in remote_details.split('\n'):
                        if '  Push  URL:' in line:
                            yield line.split(': ')[-1]
                except GitCommandError as ex:
                    if any(msg in str(ex) for msg in ['correct access rights', 'cannot run ssh']):
                        # If ssh is not setup to access this repository, see issue 694
                        result = Git().execute(
                            ['git', 'config', '--get', 'remote.%s.url' % self.name]
                        )
                        yield result
                    else:
                        raise ex
            else:
                raise ex
249403
def _remote_github_url_to_string(remote_url):
    """"""
    # TODO: make this work with https URLs
    match = re.search('git@github\.com:(.*)\.git', remote_url)
    if not match:
        raise EnvironmentError('Remote is not a valid github URL')
    identifier = match.group(1)
    return re.sub('\W', ':', identifier)
241395
def get_git_ref(self, ref):
        
        prefix = "/git/refs/"
        if not self._requester.FIX_REPO_GET_GIT_REF:
            prefix = "/git/"
        assert isinstance(ref, (str, unicode)), ref
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + prefix + ref
        )
        return github.GitRef.GitRef(self._requester, headers, data, completed=True)
1365397
def guess_url_vcs(url):
    
    parsed = urllib.parse.urlsplit(url)

    if parsed.scheme in ('git', 'svn'):
        return parsed.scheme
    elif parsed.path.endswith('.git'):
        return 'git'
    elif parsed.hostname == 'github.com':
        return 'git'

    # If it's an http url, we can try requesting it and guessing from the
    # contents.
    if parsed.scheme in ('http', 'https'):
        resp = requests.get(url)
        if re.match('basehttp.*python.*', resp.headers.get('server').lower()):
            # It's the mercurial http server
            return 'hg'
    return None
89062
def set_remote_url(name, url)
      url = url.repo.path if url.is_a?(Git::Base)
      self.lib.remote_set_url(name, url)
      Git::Remote.new(self, name)
    end
582894
def repo_url_to_project_name(url, normalize=True):
    # type: (str, bool) -> str
    
    if url.startswith('http'):
        http_url = urlparse(url)
        name = http_url.path.replace('.git', '').lstrip('/').strip()
    else:
        name = url[url.index(':') + 1:].replace('.git', '').strip()
    if normalize:
        return name.replace('/', ' / ').title()
    return name
57561
def name_url(provider, cloud, method_name):
    
    snake_parts = method_name.split('_')
    if len(snake_parts) <= 1:
        return False

    # Convention for libcloud is ex_ are extended methods
    if snake_parts[0] == 'ex':
        extra = True
        method_name = method_name.replace('ex_', '', 1)
    else:
        extra = False
    snake_parts = method_name.split('_')
    # Try to semantically match the method name to a REST action
    if snake_parts[0] in get_sem_verbs:
        method = 'GET'
        for verb in get_sem_verbs:
            method_name = method_name.replace('%s_' % verb, '', 1)
    elif snake_parts[0] in delete_sem_verbs:
        method = 'DELETE'
    elif snake_parts[0] in put_sem_verbs:
        method = 'PUT'
    else:
        method = 'POST'

    uri = '/%s/%s/%s%s' % (provider,
                           cloud,
                           'extensions/' if extra else '',
                           method_name)
    return (method, uri)
1096024
def get_git_tag(self, sha):
        
        assert isinstance(sha, (str, unicode)), sha
        headers, data = self._requester.requestJsonAndCheck(
            "GET",
            self.url + "/git/tags/" + sha
        )
        return github.GitTag.GitTag(self._requester, headers, data, completed=True)