Path: blob/master/src/applications/diffusion/data/DiffusionGitBranch.php
12241 views
<?php12final class DiffusionGitBranch extends Phobject {34const DEFAULT_GIT_REMOTE = 'origin';56/**7* Parse the output of 'git branch -r --verbose --no-abbrev' or similar into8* a map. For instance:9*10* array(11* 'origin/master' => '99a9c082f9a1b68c7264e26b9e552484a5ae5f25',12* );13*14* If you specify $only_this_remote, branches will be filtered to only those15* on the given remote, **and the remote name will be stripped**. For example:16*17* array(18* 'master' => '99a9c082f9a1b68c7264e26b9e552484a5ae5f25',19* );20*21* @param string stdout of git branch command.22* @param string Filter branches to those on a specific remote.23* @return map Map of 'branch' or 'remote/branch' to hash at HEAD.24*/25public static function parseRemoteBranchOutput(26$stdout,27$only_this_remote = null) {28$map = array();2930$lines = array_filter(explode("\n", $stdout));31foreach ($lines as $line) {32$matches = null;33if (preg_match('/^ (\S+)\s+-> (\S+)$/', $line, $matches)) {34// This is a line like:35//36// origin/HEAD -> origin/master37//38// ...which we don't currently do anything interesting with, although39// in theory we could use it to automatically choose the default40// branch.41continue;42}43if (!preg_match('/^ *(\S+)\s+([a-z0-9]{40})/', $line, $matches)) {44throw new Exception(45pht(46'Failed to parse %s!',47$line));48}4950$remote_branch = $matches[1];51$branch_head = $matches[2];5253if (strpos($remote_branch, 'HEAD') !== false) {54// let's assume that no one will call their remote or branch HEAD55continue;56}5758if ($only_this_remote) {59$matches = null;60if (!preg_match('#^([^/]+)/(.*)$#', $remote_branch, $matches)) {61throw new Exception(62pht(63"Failed to parse remote branch '%s'!",64$remote_branch));65}66$remote_name = $matches[1];67$branch_name = $matches[2];68if ($remote_name != $only_this_remote) {69continue;70}71$map[$branch_name] = $branch_head;72} else {73$map[$remote_branch] = $branch_head;74}75}7677return $map;78}7980/**81* As above, but with no `-r`. Used for bare repositories.82*/83public static function parseLocalBranchOutput($stdout) {84$map = array();8586$lines = array_filter(explode("\n", $stdout));87$regex = '/^[* ]*(\(no branch\)|\S+)\s+([a-z0-9]{40})/';88foreach ($lines as $line) {89$matches = null;90if (!preg_match($regex, $line, $matches)) {91throw new Exception(92pht(93'Failed to parse %s!',94$line));95}9697$branch = $matches[1];98$branch_head = $matches[2];99if ($branch == '(no branch)') {100continue;101}102103$map[$branch] = $branch_head;104}105106return $map;107}108109}110111112