Returns a :class:`Repo <git.repo.base.Repo>` instance for the branch.

        See :meth:`run` for arguments descriptions.
327352
def get_repo(self, repo: str, branch: str, *,
                 depth: Optional[int]=1,
                 reference: Optional[Path]=None
                 ) -> Repo:
        
        git_repo, _ = self.get_files(repo, branch, depth=depth, reference=reference)

        return git_repo
987683
def _get_branch(repo, name):
    '''
    
    '''
    try:
        return [x for x in _all_branches(repo) if x[0] == name][0]
    except IndexError:
        return False
343201
def get_path_to_repo_and_branch(self, repo: str, branch: str) -> Path:
        
        return self.get_path_to_repo(repo).resolve() / branch
611893
def current_branch():
    # type: () -> BranchDetails
    
    cmd = 'git symbolic-ref --short HEAD'
    branch_name = shell.run(
        cmd,
        capture=True,
        never_pretend=True
    ).stdout.strip()

    return BranchDetails.parse(branch_name)
77492
def run_git(self, args, git_env=None):
        '''
        
        '''

        popen_kwargs = {
            'stdout': subprocess.PIPE,
            'stderr': subprocess.PIPE,
        }

        if git_env:
            popen_kwargs['env'] = git_env

        if self._git_toplevel:
            popen_kwargs['cwd'] = self._git_toplevel

        git_process = subprocess.Popen(
            [GitRunner._git_executable] + args,
            **popen_kwargs
        )

        try:
            out, err = git_process.communicate()
            git_process.wait()
        except Exception as e:
            raise GitError("Couldn't run 'git {args}':{newline}{ex}".format(
                args=' '.join(args),
                newline=os.linesep,
                ex=str(e)
            ))

        if (0 != git_process.returncode) or err:
            if err:
                err = err.decode('utf_8')
            raise GitError("'git {args}' failed with:{newline}{err}".format(
                args=' '.join(args),
                newline=os.linesep,
                err=err
            ))

        if not out:
            raise ValueError("No output")

        return out.decode('utf_8').splitlines()
116768
def requires_git(func: Callable) -> Callable:
    
    def decorated(*args, **kwargs):
        try:
            run([GIT_COMMAND, "--version"])
        except RunException as e:
            raise RuntimeError("`git` does not appear to be working") from e
        return func(*args, **kwargs)

    return decorated
605556
def _pull(self, *, repo_path: Path=None, git_repo: Repo=None, repo: str=None, branch: str=None,
              depth: Optional[int]=None,
              reference: Optional[Path]=None
              ) -> Repo:
        
        if git_repo is not None:
            try:
                git_repo.remote().fetch(branch)
                # equivalent to git reset --hard origin/branch
                git_repo.head.reset(f"origin/{branch}", index=True, working_tree=True)
            except GitCommandError:
                raise PullError("There was an error pulling the target repository.")
            return git_repo
        else:
            kwargs: Dict[str, Any] = {}

            if depth is not None:
                kwargs["depth"] = depth

            reference = self.get_reference_repository(reference, repo)

            if reference is not None:
                kwargs["reference-if-able"] = str(reference)
                kwargs["dissociate"] = True

            try:
                return Repo.clone_from(repo, str(repo_path), branch=branch, **kwargs)
            except GitCommandError:
                raise PullError("There was an error cloning the target repository.")
190072
def project_branches(self):
        
        request_url = "{}git/branches".format(self.create_basic_url())

        return_value = self._call_api(request_url)

        return return_value['branches']
1339475
def run():
    """"""
    args = parse_args()

    codetools.setup_logging(args.debug)

    global g
    g = pygithub.login_github(token_path=args.token_path, token=args.token)

    if not args.hide:
        args.hide = []

    org = g.get_organization(args.organization)

    try:
        repos = list(org.get_repos())
    except github.RateLimitExceededException:
        raise
    except github.GithubException as e:
        msg = 'error getting repos'
        raise pygithub.CaughtOrganizationError(org, e, msg) from None

    for r in repos:
        try:
            teamnames = [t.name for t in r.get_teams()
                         if t.name not in args.hide]
        except github.RateLimitExceededException:
            raise
        except github.GithubException as e:
            msg = 'error getting teams'
            raise pygithub.CaughtRepositoryError(r, e, msg) from None

        maxt = args.maxt if (args.maxt is not None and
                             args.maxt >= 0) else len(teamnames)
        if args.debug:
            print("MAXT=", maxt)

        if args.mint <= len(teamnames) <= maxt:
            print(r.name.ljust(40) + args.delimiter.join(teamnames))
588898
def branches(self):
		
		if self.github.get_rate_limit().rate.limit == 0:
			raise GithubException

		branches = self.repo.get_branches()
		return [x.name for x in branches]
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
61939
def rebase_all_branches(self):
        
        col_width = max(len(b.name) for b in self.branches) + 1
        if self.repo.head.is_detached:
            raise GitError("You're not currently on a branch. I'm exiting"
                           " in case you're in the middle of something.")
        original_branch = self.repo.active_branch

        with self.git.stasher() as stasher:
            for branch in self.branches:
                target = self.target_map[branch.name]

                # Print branch name
                if branch.name == original_branch.name:
                    attrs = ['bold']
                else:
                    attrs = []
                print(colored(branch.name.ljust(col_width), attrs=attrs),
                        end=' ')

                # Check, if target branch exists
                try:
                    if target.name.startswith('./'):
                        # Check, if local branch exists
                        self.git.rev_parse(target.name[2:])
                    else:
                        # Check, if remote branch exists
                        _ = target.commit

                except (ValueError, GitError):
                    # Remote branch doesn't exist!
                    print(colored('error: remote branch doesn\'t exist', 'red'))
                    self.states.append('remote branch doesn\'t exist')

                    continue

                # Get tracking branch
                if target.is_local:
                    target = find(self.repo.branches,
                                  lambda b: b.name == target.name[2:])

                # Check status and act appropriately
                if target.commit.hexsha == branch.commit.hexsha:
                    print(colored('up to date', 'green'))
                    self.states.append('up to date')

                    continue  # Do not do anything

                base = self.git.merge_base(branch.name, target.name)

                if base == target.commit.hexsha:
                    print(colored('ahead of upstream', 'cyan'))
                    self.states.append('ahead')

                    continue  # Do not do anything

                fast_fastforward = False
                if base == branch.commit.hexsha:
                    print(colored('fast-forwarding...', 'yellow'), end='')
                    self.states.append('fast-forwarding')
                    # Don't fast fast-forward the currently checked-out branch
                    fast_fastforward = (branch.name !=
                                        self.repo.active_branch.name)

                elif not self.settings['rebase.auto']:
                    print(colored('diverged', 'red'))
                    self.states.append('diverged')

                    continue  # Do not do anything
                else:
                    print(colored('rebasing', 'yellow'), end='')
                    self.states.append('rebasing')

                if self.settings['rebase.show-hashes']:
                    print(' {}..{}'.format(base[0:7],
                                           target.commit.hexsha[0:7]))
                else:
                    print()

                self.log(branch, target)
                if fast_fastforward:
                    branch.commit = target.commit
                else:
                    stasher()
                    self.git.checkout(branch.name)
                    self.git.rebase(target)

            if (self.repo.head.is_detached  # Only on Travis CI,
                    # we get a detached head after doing our rebase *confused*.
                    # Running self.repo.active_branch would fail.
                    or not self.repo.active_branch.name == original_branch.name):
                print(colored('returning to {0}'.format(original_branch.name),
                              'magenta'))
                original_branch.checkout()
1152779
def branch(version = Origen.app.version.prefixed)
      version = VersionString.new(version)
      version = version.prefixed if version.semantic?
      capture = false
      File.readlines("#{Origen.root}/doc/history").each do |line|
        line = line.strip
        if capture
          if capture && line =~ /^#+ .*(Selector|Branch): '(.*)'/
            return Regexp.last_match(2).gsub('\\', '')
          end
        else
          if line =~ /Tag:/
            line = line.gsub('\\', '')
            if line =~ /^#+ Tag: #{version}$/ ||
               line =~ />Tag: #{version}</
              capture = true
            end
          end
        end
      end
      nil
    end
98793
def pull_repo():
  
  try:
    current_repo = subprocess.check_output(["git", "remote", "-v", "show"])
  except subprocess.CalledProcessError as error:
    raise RuntimeError("Exception checking current repo", error)
  current_repo = re.findall("(https://|@)(.*?)(.git|[ ])", current_repo)[0][1].replace(":", "/")
  if current_repo != EFConfig.EF_REPO:
    raise RuntimeError("Must be in " + EFConfig.EF_REPO + " repo. Current repo is: " + current_repo)
  try:
    current_branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).rstrip()
  except subprocess.CalledProcessError as error:
    raise RuntimeError("Exception checking current branch: " + repr(error))
  if current_branch != EFConfig.EF_REPO_BRANCH:
    raise RuntimeError("Must be on branch: " + EFConfig.EF_REPO_BRANCH + ". Current branch is: " + current_branch)
  try:
    subprocess.check_call(["git", "pull", "-q", "origin", EFConfig.EF_REPO_BRANCH])
  except subprocess.CalledProcessError as error:
    raise RuntimeError("Exception running 'git pull': " + repr(error))
630435
def get_current_branch(self) -> str:
        
        current_branch: str = self.repo.active_branch.name
        LOGGER.debug('current branch: %s', current_branch)
        return current_branch
834249
def main():
    
    logging.basicConfig(
        format='[%(asctime)s] %(levelname)s -- %(message)s',
        level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='')
    parser.add_argument('git_url', help='Url of the repo to sync')
    parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?')
    parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?')
    args = parser.parse_args()

    for line in GitPuller(
        args.git_url,
        args.branch_name,
        args.repo_dir
    ).pull():
        print(line)
84614
def repo_commits(self, repo):
        
        commits = []
        try:
            status = self.path_dirs.apply_path(repo)
            # switch to directory where repo will be cloned to
            if status[0]:
                cwd = status[1]
            else:
                self.logger.error('apply_path failed. Exiting repo_commits with'
                                  ' status: ' + str(status))
                return status

            status = self.repo_branches(repo)
            if status[0]:
                branches = status[1]
                for branch in branches:
                    try:
                        branch_output = check_output(shlex
                                                     .split('git rev-list origin/' +
                                                            branch),
                                                     stderr=STDOUT,
                                                     close_fds=True).decode('utf-8')
                        branch_output = branch_output.split('\n')[:-1]
                        branch_output += ['HEAD']
                        commits.append((branch, branch_output))
                    except Exception as e:  # pragma: no cover
                        self.logger.error('repo_commits failed with error: ' +
                                          str(e) + ' on branch: ' +
                                          str(branch))
                        status = (False, e)
                        return status
            else:
                self.logger.error('repo_branches failed. Exiting repo_commits'
                                  ' with status: ' + str(status))
                return status

            chdir(cwd)
            status = (True, commits)
        except Exception as e:  # pragma: no cover
            self.logger.error('repo_commits failed with error: ' + str(e))
            status = (False, e)

        return status