fix shelve-and-goto
[git-knacks.git] / git-shelve-and-goto
blobcdf1bd27c6a063a887027e1b9ccc2b1a8bda418e
1 #!/usr/bin/env ruby
3 #this will shelve your current changes to a new branch
4 require 'optparse'
6 class ShelveAndGoto
7 attr_accessor :options
8 attr_accessor :destination_branch
10 def initialize
11 options = {}
12 branch = OptionParser.new do |opts|
13 opts.on("-v", "--[no-]verbose", "Verbose output (echo individual git commands)") do |v|
14 options[:verbose] = v
15 end
16 end.parse!
17 self.options = {:verbose => false}.merge options
18 self.destination_branch = branch.join('-')
19 end
21 def run
22 git("git add .") &&
23 git("git ci -a -m 'SHELVE SHELVE SHELVE'") &&
24 if branch_exists?(destination_branch)
25 git("git checkout #{destination_branch}")
26 else
27 git("git checkout HEAD^")
28 git("git checkout -b #{destination_branch}")
29 end
30 end
33 private
34 def current_branch
35 output = get('git branch')
36 output.match(/^\* (.+)$/)[1]
37 end
39 def branch_exists?(branch)
40 output = get('git branch')
41 !output.match("^(\\*| ) #{branch}$").nil?
42 end
44 def git(cmd)
45 puts cmd if options[:verbose]
46 system cmd
47 end
49 def get(cmd)
50 puts cmd if options[:verbose]
51 `#{cmd}`
52 end
53 end
55 ShelveAndGoto.new.run