-
Notifications
You must be signed in to change notification settings - Fork 3
/
git-branch-delete-orphans
executable file
·70 lines (54 loc) · 1.71 KB
/
git-branch-delete-orphans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env ruby
require 'rubygems'
require 'rainbow'
['TERM', 'INT'].each do |signal|
Signal.trap(signal) do
# most likely, users will CTRL-C when being prompted
# for an action, so we need to ensure that the shell
# prompt is rendered on a new line
puts
exit -1
end
end
def remotes
@remote ||= `git ls-remote -q | grep 'refs/heads'`.split("\n").map { |l| l.gsub(/^.*refs\/heads\//, '').strip }
end
def locals
@local ||= `cat .git/config | grep "refs/heads/\\w"`.split("\n").map { |l| l.gsub(/^.*refs\/heads\//, '').strip }
end
def cli(orphans)
puts "The following branches track a remote branch which does not exist anymore:"
orphans.each { |b| puts " - #{b}" }
delete_all = false
keep_all = false
orphans.each do |b|
delete = false
keep = false
until delete || delete_all || keep || keep_all
puts ""
puts "Branch #{b.bright} tracks a remote branch which does not exist anymore."
print "Do you want to [d]elete it, [D]elete all, [k]eep it or [K]eep all? "
case STDIN.gets.chomp
when 'd' then delete = true
when 'D' then delete_all = true
when 'k' then keep = true
when 'K' then keep_all = true
end
end
if (delete_all || delete) && !(keep_all || keep)
system("git branch -D #{b}") # git outputs success / error messages
end
end
end
git_dir = `git rev-parse --git-dir`.chomp
if $?.success?
# step 1: change to the root of the git repo
Dir.chdir File.dirname(git_dir)
# step 2: calculate the orphaned branches
orphans = locals - remotes
# step 3: action the orphans
cli(orphans) unless orphans.empty?
else
puts "Please run #{File.basename __FILE__} from inside a git repo"
end
# That's all, Folks!