Get Branch

@link https://developer.github.com/v3/repos/#get-branch

@param string $branch

@return array
323115
public function getBranch(string $branch): array
    {
        return $this->getApi()->request($this->getApi()
                                             ->sprintf('/repos/:owner/:repo/branches/:branch', $this->getOwner(),
                                                 $this->getRepo(), $branch));
    }
547940
protected function validateBranch($branch)
    {
        try {
            if (!strpos($branch, '/')) {
                return false;
            }
            return $this->versionParser->normalizeBranch(
                $this->_getBranchWithoutNamespace($branch)
            );
        } catch (\Exception $e) {
            return false;
        }
    }
734386
public function branch($branch, $stash)
    {
        $stash = $this->normalizeStashName($stash);
        $this->clearAll();
        $this->addCommandName(self::STASH_COMMAND . ' branch');
        $this->addCommandSubject($branch);
        $this->addCommandSubject2($stash);
        return $this->getCommand();
    }
782105
private function resolveBranch($user, $repo, $branch)
    {
        $api = $this->client->api('git_data')->references();
        $params = [$user, $repo, sprintf('heads/%s', $branch)];

        $data = $this->callGitHub([$api, 'show'], $params);
        return $data['object']['sha'] ?? null;
    }
153211
def get_branch_details(repo: GithubRepository, branch: str) -> Any:
    
    url = ("https://api.github.com/repos/{}/{}/branches/{}"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     branch,
                                     repo.access_token))
    response = requests.get(url)

    if response.status_code != 200:
        raise RuntimeError(
            'Failed to get branch details. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    return json.JSONDecoder().decode(response.content.decode())
571577
public function getNames()
    {
        $branches = $this->execute();
        $branches = \explode("\n", $branches);
        $branches = \array_map(
            function ($branch) {
                return \ltrim($branch, '*');
            },
            $branches
        );
        $branches = \array_map('trim', $branches);
        $branches = \array_filter($branches);

        return $branches;
    }
798446
public function getBranchesList($keep_asterisk = false)
    {
        $branchArray = explode("\n", $this->run("branch"));
        foreach ($branchArray as $i => &$branch) {
            $branch = trim($branch);
            if (! $keep_asterisk) {
                $branch = str_replace("* ", "", $branch);
            }
            if ($branch == "") {
                unset($branchArray[$i]);
            }
        }
        return $branchArray;
    }
602228
public function gitBranch($branch)
    {
        $options = ['options' => ['regexp' => '/^[a-zA-Z0-9\/\+\._-]+$/']];
        if (filter_var($branch, FILTER_VALIDATE_REGEXP, $options) === false) {
            throw new \InvalidArgumentException(sprintf("Invalid characters found in git branch name '%s'. Use only letters, numbers, underscore, hyphen and forward slashes.", $branch));
        }

        return $branch;
    }
1073605
public function hasBranch($branch)
    {
        $branches = $this->getBranches();
        $status = in_array($branch, $branches);

        return $status;
    }
816475
public function getBranches($which = self::BRANCHES_LOCAL)
    {
        $which       = (int)$which;
        $arguments  = array(
            '--no-color'
        );

        $local  = (($which & self::BRANCHES_LOCAL) == self::BRANCHES_LOCAL);
        $remote = (($which & self::BRANCHES_REMOTE) == self::BRANCHES_REMOTE);

        if ($local && $remote) {
            $arguments[] = '-a';
        } else if ($remote) {
            $arguments[] = '-r';
        }

        /** @var $result CallResult */
        $result = $this->getGit()->{'branch'}($this->getRepositoryPath(), $arguments);
        $result->assertSuccess(
            sprintf('Cannot retrieve branch from "%s"', $this->getRepositoryPath())
        );

        $output = rtrim($result->getStdOut());
        if (empty($output)) {
            return array();
        }

        $branches = array_map(function($b) {
            $line   = rtrim($b);
            if (strpos($line, '* ') === 0) {
                $line   = substr($line, 2);
            }
            $line   = ltrim($line);
            return $line;
        }, explode("\n", $output));
        return $branches;
    }
351750
def get_branch():
    
    proc = Process("git status", ["git", "status"])

    try:
        while True:
            raw_line = proc.stdout.pop()
            line = raw_line.decode('utf8').strip()
            if line.startswith("On branch "):
                return line[10:]
    finally:
        try:
            proc.join()
        except Exception:
            pass
1159143
public function getBranchesToSync()
    {
        $allowedBranches = $this->setting('sync.constraints.branches');
        if ( count($allowedBranches) === 0 )
        {
            return [ ];
        }
        $this->fire('branches.start', [ $allowedBranches ]);

        $branchesToSync = [ ];
        $remote         = $this->client($this->setting('connection'));
        $repo           = $this->setting('repository');
        $owner          = $this->setting('owner');
        $branches       = $remote->getBranches($repo, $owner);

        foreach ( $branches as $branch => $sha )
        {
            if ( !in_array('*', $allowedBranches, true) && !in_array($branch, $allowedBranches, true) )
            {
                continue;
            }
            $cacheKey        = md5($this->project->getName() . $branch);
            $cached          = $this->cache->get($cacheKey, false);
            $destinationPath = path_join($this->project->getPath(), $branch);

            if ( $cached !== $sha || $cached === false || !$this->fs->exists($destinationPath) )
            {
                $branchesToSync[] = $branch;
            }
        }
        $this->fire('branches.finish', [ $branchesToSync ]);
        return $branchesToSync;
    }
669158
protected function getSource($expr)
	{
		$php = 'switch(' . $expr . '){';
		foreach ($this->getValuesPerCodeBranch() as $branchCode => $values)
		{
			foreach ($values as $value)
			{
				$php .= 'case' . var_export((string) $value, true) . ':';
			}
			$php .= $branchCode . 'break;';
		}
		if ($this->defaultCode > '')
		{
			$php .= 'default:' . $this->defaultCode;
		}
		$php = preg_replace('(break;$)', '', $php) . '}';

		return $php;
	}
611277
public function addBranch(Branch $branch)
    {
        if ($this->currentBranch) {
            $branch->setParentBranch($this->currentBranch);
            $this->currentBranch = $branch;
        } else {
            $this->currentBranch = $branch;
        }

        $branch->setUniqueId($this->uniqueId);
        $branch->setLevel($this->level);

        ++$this->level;
        ++$this->uniqueId;

        if (Branch::TYPE_ROOT == $branch->getType()) {
            $this->setRootBranch($branch);
        }
    }
76154
protected function getRepositoryBranch()
    {
        // If we passed a branch, use it
        if ($branch = $this->getOption('branch')) {
            return $branch;
        }

        // Get branch from config, else compute the fallback
        $branch = $this->config->getContextually('vcs.branch');
        if (!$branch) {
            $fallback = $this->bash->on('local', function () {
                return $this->vcs->runSilently('currentBranch');
            });

            $fallback = $fallback ?: 'master';
            $branch = trim($fallback);
        }

        return $branch;
    }
1127985
public function getCurrentBranch($keep_asterisk = false)
    {
        $branchArray = $this->getBranchesList(true);
        $getCurrentBranch = preg_grep("/^\*/", $branchArray);
        reset($getCurrentBranch);
        if ($keep_asterisk) {
            return current($getCurrentBranch);
        } else {
            return str_replace("* ", "", current($getCurrentBranch));
        }
    }
316055
public function branches()
    {
        $result = $this->execute('list', array('--xml' => true, $this->getUrl() . '/' . $this->basePaths['branches']));

        $logTrunk = $this->log('/', null, 1);
        $logTrunk = reset($logTrunk);

        $branches = array();
        $branches[] = new Reference('trunk', Reference::BRANCH, $logTrunk->getRevision());

        foreach ($result as $fileinfo) {
            $branches[] = new Reference($fileinfo->getFilename(), Reference::BRANCH, $fileinfo->getCommit()->getRevision());
        }

        return $branches;
    }