Helper function to determine current branch

        :param remotes:
            List the remote-tracking branches
515660
def _get_branch(self, remotes=False):
        '''
        
        '''

        return self.m(
            'getting git branch information',
            cmdd=dict(
                cmd='git branch %s' % ('-r' if remotes else ''),
                cwd=self.local
            ),
            verbose=False
        )
1182981
def git_list_branches(repo_dir):
    
    command = ['git', 'branch', '--remotes', '--all',
               '--verbose', '--no-abbrev']
    output = execute_git_command(command, repo_dir=repo_dir).splitlines()
    # remove nullish lines
    lines = [l.strip() for l in output if l.strip()]
    # find the * current branch
    try:
        current_branch = [l for l in lines if l.startswith('* ')][0]
    except IndexError:
        current_branch = None
    item = None
    if current_branch:
        lines.remove(current_branch)
        current_branch = current_branch.replace('* ', '', 1)
        if re.match('\(.*detached.+\)', current_branch):
            branch, rest = current_branch.split(')', 1)
            branch = "%s)" % branch
            sha, msg = rest.split(None, 1)
            item = {'branch': branch, 'commit': sha, 'message': msg}
        else:
            lines.insert(0, current_branch)
    # <branch> <hash> <commit_message>
    # make a list of lists with clean elements of equal length
    breakout = [k.split(None, 2) for k in lines]
    # remove any strange hashless outliers
    breakout = [k for k in breakout if len(k[1]) == 40]
    headers = ['branch', 'commit', 'message']
    # use izip_longest so we fill in None if message was empty
    result = [dict(zip_longest(headers, vals))
              for vals in breakout]
    if item:
        result.append(item)
    return result
143368
def list_remote(remote_uri, verbose=False):
    
    remote_uri1, remote_dpath = remote_uri.split(':')
    if not remote_dpath:
        remote_dpath = '.'
    import utool as ut
    out = ut.cmd('ssh', remote_uri1, 'ls -l %s' % (remote_dpath,), verbose=verbose)
    import re
    # Find lines that look like ls output
    split_lines = [re.split(r'\s+', t) for t in out[0].split('\n')]
    paths = [' '.join(t2[8:]) for t2 in split_lines if len(t2) > 8]
    return paths
289014
def remote_for_branch(branch_name)
      git_call('branch -lvv').gsub('* ', '').split("\n").each do |line|
        entries = line.split(' ')
        next unless entries.first == branch_name
        # Return the remote name or nil for local branches.
        match = entries[2].match(%r(\[(.*)(\]|:)))
        return match[1].split('/').first if match
      end
      nil
    end
822004
def list_branches(self) -> typing.List[str]:
        
        branches: typing.List[str] = [head.name for head in self.repo.heads]
        LOGGER.debug('branches: %s', branches)
        return branches
1254460
def get_url(self):
        '''
        
        '''
        if self.role in ('git_pillar', 'winrepo'):
            # With winrepo and git_pillar, the remote is specified in the
            # format '<branch> <url>', so that we can get a unique identifier
            # to hash for each remote.
            try:
                self.branch, self.url = self.id.split(None, 1)
            except ValueError:
                self.branch = self.conf['branch']
                self.url = self.id
        else:
            self.url = self.id
1253201
def repo_branches(self, repo):
        
        branches = []
        try:
            # switch to directory where repo will be cloned to
            status = self.path_dirs.apply_path(repo)
            if status[0]:
                cwd = status[1]
            else:
                self.logger.error('apply_path failed. Exiting repo_branches'
                                  ' with status ' + str(status))
                return status

            branch_output = check_output(shlex.split('git branch -a'),
                                         stderr=STDOUT,
                                         close_fds=True)
            branch_output = branch_output.split(b'\n')
            for branch in branch_output:
                br = branch.strip()
                if br.startswith(b'*'):
                    br = br[2:]
                if b'/' in br:
                    branches.append(br.rsplit(b'/', 1)[1].decode('utf-8'))
                elif br:
                    branches.append(br.decode('utf-8'))

            branches = list(set(branches))
            for branch in branches:
                try:
                    check_output(shlex.split('git checkout ' + branch),
                                 stderr=STDOUT,
                                 close_fds=True)
                except Exception as e:  # pragma: no cover
                    self.logger.error('repo_branches failed with error: ' +
                                      str(e) + ' on branch: ' + str(branch))
                    status = (False, e)
                    return status

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

        return status
461389
def check(branch: str = 'master'):
    
    if os.environ.get('TRAVIS') == 'true':
        travis(branch)
    elif os.environ.get('SEMAPHORE') == 'true':
        semaphore(branch)
    elif os.environ.get('FRIGG') == 'true':
        frigg(branch)
    elif os.environ.get('CIRCLECI') == 'true':
        circle(branch)
    elif os.environ.get('GITLAB_CI') == 'true':
        gitlab(branch)
    elif 'BITBUCKET_BUILD_NUMBER' in os.environ:
        bitbucket(branch)
250576
def read_git_branch():
    
    if os.getenv('TRAVIS'):
        return os.getenv('TRAVIS_BRANCH')
    else:
        try:
            repo = git.repo.base.Repo(search_parent_directories=True)
            return repo.active_branch.name
        except Exception:
            return ''
183178
def get_current_branch():
    
    cmd = ["git", "rev-parse", "--abbrev-ref", "HEAD"]
    output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
    return output.strip().decode("utf-8")
186038
def branches(self):
        

        df = pd.DataFrame(columns=['repository', 'local', 'branch'])

        if _has_joblib:
            ds = Parallel(n_jobs=-1, backend='threading', verbose=0)(
                delayed(_branches_func)
                (x) for x in self.repos
            )
            for d in ds:
                df = df.append(d)
        else:
            for repo in self.repos:
                try:
                    df = df.append(_branches_func(repo))
                except GitCommandError:
                    print('Warning! Repo: %s couldn\'t be inspected' % (repo, ))

        df.reset_index()

        return df
409645
function listLocalBranches(repo) {
  return caller.call(repo, repo.branches).then(function (branches) {
    return branches.map(function (branch) {
      return branch.name
    })
  })
}
434571
def get_current_branch(self, location):
        
        # git-symbolic-ref exits with empty stdout if "HEAD" is a detached
        # HEAD rather than a symbolic ref.  In addition, the -q causes the
        # command to exit with status code 1 instead of 128 in this case
        # and to suppress the message to stderr.
        args = ['symbolic-ref', '-q', 'HEAD']
        output = self.run_command(
            args, extra_ok_returncodes=(1, ), show_stdout=False, cwd=location,
        )
        ref = output.strip()

        if ref.startswith('refs/heads/'):
            return ref[len('refs/heads/'):]

        return None
450307
def known_remotes(self):
        """"""
        objects = []
        output = self.context.capture(
            'bzr', 'config', 'parent_location',
            check=False, silent=True,
        )
        if output and not output.isspace():
            location = output.strip()
            # The `bzr branch' command has the unusual habit of converting
            # absolute pathnames into relative pathnames. Although I get why
            # this can be preferred over the use of absolute pathnames I
            # nevertheless want vcs-repo-mgr to communicate to its callers as
            # unambiguously as possible, so if we detect a relative pathname
            # we convert it to an absolute pathname.
            if location.startswith('../'):
                location = os.path.normpath(os.path.join(self.local, location))
            objects.append(Remote(
                default=True,
                location=location,
                repository=self,
                roles=['push', 'pull'],
            ))
        return objects
641605
def current_branch(self):
        """"""
        branch_name = git(self.gitdir, self.gitwd, "symbolic-ref", "HEAD")
        return branch_name.replace('refs/heads/', '').strip()
1090669
def list_branch(path = Dir.pwd)
      cg = MiniGit::Capturing.new(path)
      res = cg.branch :a => true
      res = res.split("\n")
      # Eventually reorder to make the first element of the array the current branch
      i = res.find_index { |e| e =~ /^\*\s/ }
      res[0], res[i] = res[i], res[0] unless (i.nil? || i.zero?)
      res.each { |e| e.sub!(/^\*?\s+/, '') }
      res
    end
113846
def pull(self, remote, branch=None):
        '''
        '''
        pb = ProgressBar()
        pb.setup(self.name)
        if branch:
            remote.pull(branch, progress=pb)
        else: # pragma: no cover
            remote.pull(progress=pb)
        print()