Skip to content

Instantly share code, notes, and snippets.

@nicordev
Last active March 22, 2020 21:19
Show Gist options
  • Save nicordev/f18a87cf9d398a4afb7781554b9476d0 to your computer and use it in GitHub Desktop.
Save nicordev/f18a87cf9d398a4afb7781554b9476d0 to your computer and use it in GitHub Desktop.
PHP script to switch git branch using a menu. Can also filter results by passing a parameter to the command.
#!/bin/php
<?php
function getGitBranches(?string $criteria = null)
{
if ($criteria) {
$branches = explode("\n", `git branch | grep {$criteria}`);
} else {
$branches = explode("\n", `git branch`);
}
if (is_array($branches)) {
array_pop($branches);
}
return $branches;
}
function displayBranches(array $branches)
{
foreach ($branches as $key => $branch) {
echo "$key: $branch\n";
}
}
function selectBranch(array $branches)
{
fscanf(STDIN, "%d\n", $branchId);
if (
null === $branchId ||
$branchId < 0 ||
$branchId >= count($branches)
) {
echo "Wrong input. Bye.\n";
return 1;
}
echo "Switching to branch {$branches[$branchId]}.\n";
`git checkout {$branches[$branchId]}`;
return 0;
}
function main($commandArguments)
{
$branches = getGitBranches($commandArguments[1] ?? null);
echo "Available branches:\n\n";
displayBranches($branches);
echo "\nSwitch to branch: ";
selectBranch($branches);
}
main($argv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment