make sure a git repo ssh:// url has a user set
490060
def tidy_ssh_user(url=None, user=None):
    """"""
    if url and url.startswith('ssh://'):
        # is there a user already ?
        match = re.compile('ssh://([^@]+)@.+').match(url)
        if match:
            ssh_user = match.group(1)
            if user and ssh_user != user:
                # assume prevalence of argument
                url = url.replace(re.escape(ssh_user) + '@',
                                  user + '@')
        elif user:
            url = 'ssh://' + \
                  user + '@' + \
                  url[len('ssh://'):]
    return url
903448
def create_user(username, rsa_pub_key, rsa_pub_key_name)
      key_name = "#{username}@#{rsa_pub_key_name}"
      key_path = @configuration.user_key_path(key_name)

      if users_public_keys().include?(key_path)
        raise ::Gitolite::Duplicate, "Public key (#{rsa_pub_key_name}) already exists for user (#{username}) on gitolite server"
      end

      add_commit_file(key_path,rsa_pub_key, "Added public key (#{rsa_pub_key_name}) for user (#{username}) ")

      key_path
    end
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)
439151
def remote_differs?
      remote_sha = nil
      current_sha = nil
      git_repo = git_repo_for(@repo_dir)
      without_size_limit(git_repo) do
        do_fetch(git_repo)
        revision = resolve_revision
        remote_name = validate_revision(git_repo, revision)
        remote_sha = git_repo.sha_for(remote_name ? remote_name : revision)
        current_sha = git_repo.sha_for(nil)
      end
      current_sha != remote_sha
    end
152190
def git_reset(repo, options = {})
      ensure_ready!(:authorization)
      response = connection.delete(git_repo_path(repo), options)
      checked_response_body(response)
    end
370410
def repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):
	
	exe = 'git' if 'git' in url else 'hg'
	with dest_ctx() as repo_dir:
		cmd = [exe, 'clone', url, repo_dir]
		if branch:
			cmd.extend(['--branch', branch])
		devnull = open(os.path.devnull, 'w')
		stdout = devnull if quiet else None
		subprocess.check_call(cmd, stdout=stdout)
		yield repo_dir
1151158
async function synchRepo(remote, pathname) {
  const cmd = `git subtree push --prefix=${pathname} ${remote} master`;

  try {
    await exec(cmd);
    logger.log(`Synched master of ${pathname}`);
  } catch (error) {
    throw error;
  }
}
949002
def _input_github_repo(url=None):
    
    if url is None:
        url = user_input('Input the URL of the GitHub repository '
                         'to use as a `trytravis` repository: ')
    url = url.strip()
    http_match = _HTTPS_REGEX.match(url)
    ssh_match = _SSH_REGEX.match(url)
    if not http_match and not ssh_match:
        raise RuntimeError('That URL doesn\'t look like a valid '
                           'GitHub URL. We expect something '
                           'of the form: `https://github.com/[USERNAME]/'
                           '[REPOSITORY]` or `ssh://git@github.com/'
                           '[USERNAME]/[REPOSITORY]')

    # Make sure that the user actually made a new repository on GitHub.
    if http_match:
        _, name = http_match.groups()
    else:
        _, name = ssh_match.groups()
    if 'trytravis' not in name:
        raise RuntimeError('You must have `trytravis` in the name of your '
                           'repository. This is a security feature to reduce '
                           'chances of running git push -f on a repository '
                           'you don\'t mean to.')

    # Make sure that the user actually wants to use this repository.
    accept = user_input('Remember that `trytravis` will make commits on your '
                        'behalf to `%s`. Are you sure you wish to use this '
                        'repository? Type `y` or `yes` to accept: ' % url)
    if accept.lower() not in ['y', 'yes']:
        raise RuntimeError('Operation aborted by user.')

    if not os.path.isdir(config_dir):
        os.makedirs(config_dir)
    with open(os.path.join(config_dir, 'repo'), 'w+') as f:
        f.truncate()
        f.write(url)
    print('Repository saved successfully.')
840650
def github(cls, user, repo):
    
    # For the url format, see: http://maven.apache.org/scm/git.html
    params = dict(user=user, repo=repo)
    connection = 'scm:git:git@github.com:{user}/{repo}.git'.format(**params)
    url = 'https://github.com/{user}/{repo}'.format(**params)
    return cls(connection=connection, developer_connection=connection, url=url)
288023
def validate_repo_url(self, repo: str):
        
        # that should match valid git repos
        if not isinstance(repo, str) or not re.match(r"^(https?|file)://[\w._\-/~]*[.git]?/?$", repo):
            raise ValueError(f"{repo} is not a valid http[s] or file:// git repository.")
757454
def ensure():
        
        LOGGER.debug('checking repository')
        if not os.path.exists('.git'):
            LOGGER.error('This command is meant to be ran in a Git repository.')
            sys.exit(-1)
        LOGGER.debug('repository OK')
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'))
905559
def _fix_repo_url(repo_url):
    """"""
    parsed = urlparse.urlparse(repo_url)
    
    if parsed.scheme not in ('http', 'https'):
        # Fix only for http and https.
        return repo_url

    username = parsed.username or ""
    password = parsed.password or ""
    port = ":" + parsed.port if parsed.port else ""
    netloc = "".join((username, ":", password, "@", parsed.hostname, port))
    part_list = list(parsed)
    part_list[1] = netloc
    return urlparse.urlunparse(part_list)
1207373
def _github_ssh_key_exists(cls):
        """"""
        remote_keys = map(lambda k: k._key, cls._user.get_keys())
        found = False
        pubkey_files = glob.glob(os.path.expanduser('~/.ssh/*.pub'))
        for rk in remote_keys:
            for pkf in pubkey_files:
                local_key = io.open(pkf, encoding='utf-8').read()
                # in PyGithub 1.23.0, remote key is an object, not string
                rkval = rk if isinstance(rk, six.string_types) else rk.value
                # don't use "==" because we have comments etc added in public_key
                if rkval in local_key:
                    found = True
                    break
        return found
270287
def attach(cls, name, vhost, remote_name):
        """"""
        paas_access = cls.get('paas_access')

        if not paas_access:
            paas_info = cls.info(name)
            paas_access = '%s@%s' \
                          % (paas_info['user'], paas_info['git_server'])

        remote_url = 'ssh+git://%s/%s.git' % (paas_access, vhost)

        ret = cls.execute('git remote add %s %s' % (remote_name, remote_url,))

        if ret:
            cls.echo('Added remote `%s` to your local git repository.'
                     % (remote_name))
            cls.echo('Use `git push %s master` to push your code to the '
                     'instance.' % (remote_name))
            cls.echo('Then `$ gandi deploy` to build and deploy your '
                     'application.')
585600
def register_git_injector(username, password):
    """"""
    fd, tmp_path = mkstemp()
    atexit.register(lambda: os.remove(tmp_path))

    with os.fdopen(fd, 'w') as f:
        f.write(ASKPASS.format(username=username, password=password or ''))

    chmod(tmp_path, 0o700)
    os.environ['GIT_ASKPASS'] = tmp_path
596262
def _sync_repo(self, repo_url: str, revision: str or None = None) -> Path:
        '''
        '''

        repo_name = repo_url.split('/')[-1].rsplit('.', maxsplit=1)[0]
        repo_path = (self._cache_path / repo_name).resolve()

        self.logger.debug(f'Synchronizing with repo; URL: {repo_url}, revision: {revision}')

        try:
            self.logger.debug(f'Cloning repo {repo_url} to {repo_path}')

            run(
                f'git clone {repo_url} {repo_path}',
                shell=True,
                check=True,
                stdout=PIPE,
                stderr=STDOUT
            )

        except CalledProcessError as exception:
            if repo_path.exists():
                self.logger.debug('Repo already cloned; pulling from remote')

                try:
                    run(
                        'git pull',
                        cwd=repo_path,
                        shell=True,
                        check=True,
                        stdout=PIPE,
                        stderr=STDOUT
                    )

                except CalledProcessError as exception:
                    self.logger.warning(str(exception))

            else:
                self.logger.error(str(exception))

        if revision:
            run(
                f'git checkout {revision}',
                cwd=repo_path,
                shell=True,
                check=True,
                stdout=PIPE,
                stderr=STDOUT
            )

        return repo_path