Retrieve the git remote origin URL of the current repo.

@param {Function} fn
Callback to receive the result.
762856
function origin(fn) {
  'use strict';

  exec('git config --local --get remote.origin.url', function (errors, stdout, stderr) {
    var url = "";

    if (errors)  return fn(errors.stack, url);
    if (stderr)  return fn(stderr, url);

    url = trim.call(stdout);
    if (!url) return fn('Unable to find remote origin URL!', url);

    fn(null, url);
  });
}
406433
function getFileUrl (repo, path, sha, line) {
  var url = "https://github.com/" + repo + "/blob/";

  if (sha) {
    url += sha + "/";
  }

  url += path;

  if (line) {
    url += "#L" + line;
  }

  return url;
}
557194
def _get_repo_url():
    """"""
    default_repo = 'https://apache-mxnet.s3-accelerate.dualstack.amazonaws.com/'
    repo_url = os.environ.get('MXNET_GLUON_REPO', default_repo)
    if repo_url[-1] != '/':
        repo_url = repo_url+'/'
    return repo_url
1033861
def get_remote(self, remote='origin'):
        """"""
        repo = self.get_repo()
        if repo is not None:
            remotes = {r.name: r for r in repo.remotes}
            r = repo.remotes[0] if remote not in remotes else remotes[remote]
        else:
            r = None
        return r
113326
def fetchall(self):
        """"""
        try:
            self.repo.remotes.origin.fetch()
        except git.exc.GitCommandError as err:
            raise GitError(err)
714906
def repo_pull(repo_dir, repo_url, fetch=False):
    """"""
    # Make sure the repository is reset to the master branch.
    repo = Repo(repo_dir)
    repo.git.clean("-df")
    repo.git.reset("--hard")
    repo.git.checkout("master")
    repo.head.reset(index=True, working_tree=True)

    # Compile the refspec appropriately to ensure
    # that if the repo is from github it includes
    # all the refs needed, including PR's.
    refspec_list = [
        "+refs/heads/*:refs/remotes/origin/*",
        "+refs/heads/*:refs/heads/*",
        "+refs/tags/*:refs/tags/*"
    ]
    if "github.com" in repo_url:
        refspec_list.extend([
            "+refs/pull/*:refs/remotes/origin/pr/*",
            "+refs/heads/*:refs/remotes/origin/*"])

    # Only get the latest updates if requested.
    if fetch:
        repo.git.fetch(["-u", "-v", "-f",
                        repo_url,
                        refspec_list])
    return repo
797227
function(site, env) {

    app.status('Pulling code.');

    // Do this if we are gitting for the first time
    if (firstTime()) {

      // Get connection info for first clone
      return terminus.connectionInfo(site, env)

      // Generate our code repo URL
      // NOTE: even multidev requires we use 'dev' instead of env
      .then(function(bindings) {

        // Clone the repo
        return commands.git(['clone', bindings.git_url, './'])

        // Grab branches if we need more than master
        .then(function() {
          if (env !== 'dev') {
            return commands.git(['fetch', 'origin']);
          }
        })

        // Checkout correct branch if needed
        .then(function() {
          if (env !== 'dev') {
            return commands.git(['checkout', env]);
          }
        });

      });
    }

    // If we already have da git then just pull down the correct branch
    else {
      var branch = (env === 'dev') ? 'master' : env;
      return commands.git(['pull', '-Xtheirs', '--no-edit', 'origin', branch]);
    }

  }
324530
def pull(self, remote="origin", ref=None):
        """"""
        return git_pull(self.repo_dir, remote=remote, ref=ref)
1151586
def _fetch(self):
        '''
        
        '''
        origin = self.repo.remotes[0]
        try:
            fetch_results = origin.fetch()
        except AssertionError:
            fetch_results = origin.fetch()

        new_objs = False
        for fetchinfo in fetch_results:
            if fetchinfo.old_commit is not None:
                log.debug(
                    '%s has updated \'%s\' for remote \'%s\' '
                    'from %s to %s',
                    self.role,
                    fetchinfo.name,
                    self.id,
                    fetchinfo.old_commit.hexsha[:7],
                    fetchinfo.commit.hexsha[:7]
                )
                new_objs = True
            elif fetchinfo.flags in (fetchinfo.NEW_TAG,
                                     fetchinfo.NEW_HEAD):
                log.debug(
                    '%s has fetched new %s \'%s\' for remote \'%s\'',
                    self.role,
                    'tag' if fetchinfo.flags == fetchinfo.NEW_TAG else 'head',
                    fetchinfo.name,
                    self.id
                )
                new_objs = True

        cleaned = self.clean_stale_refs()
        return True if (new_objs or cleaned) else None
999383
def _fetch(self):
        '''
        
        '''
        origin = self.repo.remotes[0]
        refs_pre = self.repo.listall_references()
        fetch_kwargs = {}
        # pygit2 radically changed fetchiing in 0.23.2
        if self.remotecallbacks is not None:
            fetch_kwargs['callbacks'] = self.remotecallbacks
        else:
            if self.credentials is not None:
                origin.credentials = self.credentials
        try:
            fetch_kwargs['prune'] = pygit2.GIT_FETCH_PRUNE
        except AttributeError:
            # pruning only available in pygit2 >= 0.26.2
            pass
        try:
            fetch_results = origin.fetch(**fetch_kwargs)
        except GitError as exc:
            exc_str = get_error_message(exc).lower()
            if 'unsupported url protocol' in exc_str \
                    and isinstance(self.credentials, pygit2.Keypair):
                log.error(
                    'Unable to fetch SSH-based %s remote \'%s\'. '
                    'You may need to add ssh:// to the repo string or '
                    'libgit2 must be compiled with libssh2 to support '
                    'SSH authentication.', self.role, self.id,
                    exc_info=True
                )
            elif 'authentication required but no callback set' in exc_str:
                log.error(
                    '%s remote \'%s\' requires authentication, but no '
                    'authentication configured', self.role, self.id,
                    exc_info=True
                )
            else:
                log.error(
                    'Error occurred fetching %s remote \'%s\': %s',
                    self.role, self.id, exc,
                    exc_info=True
                )
            return False
        try:
            # pygit2.Remote.fetch() returns a dict in pygit2 < 0.21.0
            received_objects = fetch_results['received_objects']
        except (AttributeError, TypeError):
            # pygit2.Remote.fetch() returns a class instance in
            # pygit2 >= 0.21.0
            received_objects = fetch_results.received_objects
        if received_objects != 0:
            log.debug(
                '%s received %s objects for remote \'%s\'',
                self.role, received_objects, self.id
            )
        else:
            log.debug('%s remote \'%s\' is up-to-date', self.role, self.id)
        refs_post = self.repo.listall_references()
        cleaned = self.clean_stale_refs(local_refs=refs_post)
        return True \
            if (received_objects or refs_pre != refs_post or cleaned) \
            else None
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
986067
async function initRepo({
  repository,
  token,
  endpoint,
  forkMode,
  forkToken,
  gitPrivateKey,
  gitFs,
  localDir,
  includeForks,
}) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'github' }, { token, endpoint });
  if (!opts.token) {
    throw new Error(`No token found for GitHub repository ${repository}`);
  }
  hostRules.update({ ...opts, platform: 'github', default: true });
  logger.info('Authenticated as user: ' + (await getRenovateUsername()));
  logger.info('Using renovate version: ' + global.renovateVersion);
  // config is used by the platform api itself, not necessary for the app layer to know
  cleanRepo();
  config.isGhe = endpoint && !endpoint.startsWith('https://api.github.com');
  config.localDir = localDir;
  config.platform = 'github';
  config.repository = repository;
  [config.repositoryOwner, config.repositoryName] = repository.split('/');
  config.gitPrivateKey = gitPrivateKey;
  // platformConfig is passed back to the app layer and contains info about the platform they require
  const platformConfig = {};
  let res;
  try {
    res = await get(`repos/${repository}`);
    logger.trace({ repositoryDetails: res.body }, 'Repository details');
    // istanbul ignore if
    if (res.body.fork && gitFs && !includeForks) {
      try {
        const renovateConfig = JSON.parse(
          Buffer.from(
            (await get(
              `repos/${config.repository}/contents/${defaultConfigFile}`
            )).body.content,
            'base64'
          ).toString()
        );
        if (!renovateConfig.includeForks) {
          throw new Error();
        }
      } catch (err) {
        throw new Error('fork');
      }
    }
    // istanbul ignore if
    if (res.body.full_name && res.body.full_name !== repository) {
      logger.info(
        { repository, this_repository: res.body.full_name },
        'Repository has been renamed'
      );
      throw new Error('renamed');
    }
    if (res.body.archived) {
      logger.info(
        'Repository is archived - throwing error to abort renovation'
      );
      throw new Error('archived');
    }
    platformConfig.privateRepo = res.body.private === true;
    platformConfig.isFork = res.body.fork === true;
    const owner = res.body.owner.login;
    logger.debug(`${repository} owner = ${owner}`);
    // Use default branch as PR target unless later overridden.
    config.defaultBranch = res.body.default_branch;
    // Base branch may be configured but defaultBranch is always fixed
    config.baseBranch = config.defaultBranch;
    logger.debug(`${repository} default branch = ${config.baseBranch}`);
    // GitHub allows administrators to block certain types of merge, so we need to check it
    if (res.body.allow_rebase_merge) {
      config.mergeMethod = 'rebase';
    } else if (res.body.allow_squash_merge) {
      config.mergeMethod = 'squash';
    } else if (res.body.allow_merge_commit) {
      config.mergeMethod = 'merge';
    } else {
      // This happens if we don't have Administrator read access, it is not a critical error
      logger.info('Could not find allowed merge methods for repo');
    }
  } catch (err) /* istanbul ignore next */ {
    logger.debug('Caught initRepo error');
    if (err.message === 'archived' || err.message === 'renamed') {
      throw err;
    }
    if (err.statusCode === 403) {
      throw new Error('forbidden');
    }
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    if (err.message.startsWith('Repository access blocked')) {
      throw new Error('blocked');
    }
    if (err.message === 'fork') {
      throw err;
    }
    logger.info({ err }, 'Unknown GitHub initRepo error');
    throw err;
  }
  // This shouldn't be necessary, but occasional strange errors happened until it was added
  config.issueList = null;
  config.prList = null;
  config.openPrList = null;
  config.closedPrList = null;
  config.storage = new Storage();
  await config.storage.initRepo(config);
  if (forkMode) {
    logger.info('Bot is in forkMode');
    config.forkToken = forkToken;
    // Save parent SHA then delete
    const parentSha = await getBaseCommitSHA();
    config.baseCommitSHA = null;
    // save parent name then delete
    config.parentRepo = config.repository;
    config.repository = null;
    // Get list of existing repos
    const existingRepos = (await get('user/repos?per_page=100', {
      token: forkToken || opts.token,
      paginate: true,
    })).body.map(r => r.full_name);
    try {
      config.repository = (await get.post(`repos/${repository}/forks`, {
        token: forkToken || opts.token,
      })).body.full_name;
    } catch (err) /* istanbul ignore next */ {
      logger.info({ err }, 'Error forking repository');
      throw new Error('cannot-fork');
    }
    if (existingRepos.includes(config.repository)) {
      logger.info(
        { repository_fork: config.repository },
        'Found existing fork'
      );
      // Need to update base branch
      logger.debug(
        { baseBranch: config.baseBranch, parentSha },
        'Setting baseBranch ref in fork'
      );
      // This is a lovely "hack" by GitHub that lets us force update our fork's master
      // with the base commit from the parent repository
      try {
        await get.patch(
          `repos/${config.repository}/git/refs/heads/${config.baseBranch}`,
          {
            body: {
              sha: parentSha,
              force: true,
            },
            token: forkToken || opts.token,
          }
        );
      } catch (err) /* istanbul ignore next */ {
        if (
          err.statusCode === 422 &&
          err.message.startsWith('Object does not exist')
        ) {
          throw new Error('repository-changed');
        }
      }
    } else {
      logger.info({ repository_fork: config.repository }, 'Created fork');
      // Wait an arbitrary 30s to hopefully give GitHub enough time for forking to complete
      await delay(30000);
    }
    await config.storage.initRepo(config);
  }

  // istanbul ignore if
  if (gitFs) {
    logger.debug('Enabling Git FS');
    let { host } = URL.parse(opts.endpoint);
    if (host === 'api.github.com') {
      host = null;
    }
    host = host || 'github.com';
    const url = GitStorage.getUrl({
      gitFs,
      auth:
        config.forkToken ||
        (global.appMode ? `x-access-token:${opts.token}` : opts.token),
      hostname: host,
      repository: config.repository,
    });
    config.storage = new GitStorage();
    await config.storage.initRepo({
      ...config,
      url,
    });
  }

  return platformConfig;
}
1192564
def get_upstream(repo: Repo) -> Remote:
    """"""
    for remote in repo.remotes:
        for url in remote.urls:
            if url.endswith("pytest-dev/pluggy.git"):
                return remote
    raise RuntimeError("could not find tox-dev/tox.git remote")
103509
function getUrl(version = current) {
	const name = `native-ext-v${version}-${os}-${arch}.${ext}`;
	return `https://github.com/NiklasGollenstede/native-ext/releases/download/v${version}/`+ name;
}
631053
def remote_urls(self):
        
        cmd = 'git config -l | grep "url"'
        return self.sh(cmd,
                       shell=True,
                       ignore_error=True).strip()
248976
def parse_remote_url(url):
    """"""
    # The URL will either be git@github.com:org/repo.git or
    # https://github.com/org/repo.git and in both cases
    # it's not guarantee that the domain is github.com.
    # FIXME: Make it work non-github.com domains
    if url.startswith("git@"):
        path = url.split(":", 1)[1]
    else:
        parsed = urllib.parse.urlparse(url)
        path = parsed.path[1:]

    assert path.endswith(".git"), path
    path = path[:-4]
    return path.split("/")
472521
async function getPr(prNo) {
  const pr = (await api.get(
    `/2.0/repositories/${config.repository}/pullrequests/${prNo}`
  )).body;

  // istanbul ignore if
  if (!pr) {
    return null;
  }

  const res = {
    displayNumber: `Pull Request #${pr.id}`,
    ...utils.prInfo(pr),
  };

  if (utils.prStates.open.includes(pr.state)) {
    res.isConflicted = await isPrConflicted(prNo);
    const commits = await utils.accumulateValues(pr.links.commits.href);
    if (commits.length === 1) {
      res.canRebase = true;
    }
  }
  if (await branchExists(pr.source.branch.name)) {
    res.isStale = await isBranchStale(pr.source.branch.name);
  }

  return res;
}