From b9d048b364defc931e06c137ce932114ce237075 Mon Sep 17 00:00:00 2001
From: Oliver Davies <oliver@oliverdavies.uk>
Date: Wed, 15 Jan 2020 16:17:27 +0000
Subject: [PATCH] Add git-delete-merged-branches

---
 bin/git-delete-merged-branches | 42 ++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
 create mode 100755 bin/git-delete-merged-branches

diff --git a/bin/git-delete-merged-branches b/bin/git-delete-merged-branches
new file mode 100755
index 00000000..77e7fc00
--- /dev/null
+++ b/bin/git-delete-merged-branches
@@ -0,0 +1,42 @@
+#!/usr/bin/env php
+<?php
+
+function extractBranchNamesFromInfo(string $branchInfo): array
+{
+    $branchNames = array_map(function (string $branchInfo): string {
+        preg_match('/\s*((\w|-|\/)+)\s*/', $branchInfo, $matches);
+
+        return $matches[1] ?? '';
+    }, explode(PHP_EOL, $branchInfo));
+
+    return array_filter($branchNames);
+}
+
+function filterIgnoredBranches(array $branchNames): array
+{
+    return array_filter($branchNames, function (string $branchName): bool {
+        return !in_array($branchName, ['develop', 'master', 'staging', 'production']);
+    });
+}
+
+$branchInfo = shell_exec('git branch -vv | grep ": gone]"');
+
+# Return early if there are no branches to delete.
+if ($branchInfo === NULL) {
+  return;
+}
+
+$branchNames = extractBranchNamesFromInfo($branchInfo);
+$filteredBranchNames = filterIgnoredBranches($branchNames);
+
+$currentBranch = exec('git rev-parse --abbrev-ref HEAD');
+
+foreach ($filteredBranchNames as $branchName) {
+    if ($branchName == $currentBranch) {
+        echo "Cannot delete {$branchName} as it is the current branch.";
+        continue;
+    }
+
+    echo "Deleting {$branchName}...";
+    exec("git branch -D ${branchName}");
+}