Class: GitManager

Inherits:
Object
  • Object
show all
Defined in:
lib/git_undo/git_manager.rb

Constant Summary collapse

VALID_COMMANDS =
['add','commit','merge','checkout','co']

Instance Method Summary collapse

Constructor Details

#initialize(history_file) ⇒ GitManager

Returns a new instance of GitManager.



6
7
8
9
# File 'lib/git_undo/git_manager.rb', line 6

def initialize(history_file)
  @history_file = history_file
  @command_list = []
end

Instance Method Details

#get_commandsObject



21
22
23
24
25
26
27
28
29
30
# File 'lib/git_undo/git_manager.rb', line 21

def get_commands
  File.open(@history_file) do |file|
    file.each do |line|
      # find last git command
      if /\Agit / =~ line
        @command_list << line.chomp
      end
    end
  end
end

#last_commandObject



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/git_undo/git_manager.rb', line 32

def last_command
  last = ''
  index = @command_list.length - 1
  while last.empty? && index >= 0
    command = parse_command(@command_list[index])[:action]
    if VALID_COMMANDS.include?(command)
      last = @command_list[index]
    end
    index -= 1
  end
  return last
end

#parse_command(command) ⇒ Object



45
46
47
48
49
50
# File 'lib/git_undo/git_manager.rb', line 45

def parse_command(command)
  tokens = command.split(' ')
  action = tokens[1]
  arguments = tokens[2..-1].join(' ')
  return { action: action, arguments: arguments }
end

#runObject



11
12
13
14
15
16
17
18
19
# File 'lib/git_undo/git_manager.rb', line 11

def run
  get_commands
  if last_command
    puts "Last git command was: `#{last_command}`"
    undo_message(last_command)
  else
    puts "No git commands found!"
  end
end

#undo_command(action, arguments) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/git_undo/git_manager.rb', line 52

def undo_command(action, arguments)
  case action
  when 'add'
    "git reset #{arguments}"
  when 'commit'
    "git reset --soft HEAD~"
  when 'merge'
    "git reset --merge ORIG_HEAD"
  when 'checkout','co'
    undo_command = "git checkout -"
    if arguments.start_with?('-b')
      #also delete branch
      branch_name = arguments.split.last
      undo_command += " && git branch -D #{branch_name}"
    end
    undo_command
  end
end

#undo_message(command) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/git_undo/git_manager.rb', line 71

def undo_message(command)
  command_hash = parse_command(command)
  undo = undo_command(command_hash[:action], command_hash[:arguments])
  if !undo
    puts "Sorry, I don't know how to undo that command"
  else
    puts "To undo, run `#{undo}`\nWould you like to automatically run this command now? (y/N)"
    option = gets.chomp.downcase
    if option == 'y'
      puts undo
      %x[ #{undo} ]
    end
  end
end