Class: GitManager

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

Instance Method Summary collapse

Constructor Details

#initialize(history_file) ⇒ GitManager

Returns a new instance of GitManager.



2
3
4
5
# File 'lib/git_undo/git_manager.rb', line 2

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

Instance Method Details

#get_commandsObject



17
18
19
20
21
22
23
24
25
26
# File 'lib/git_undo/git_manager.rb', line 17

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

#last_commandObject



28
29
30
31
32
33
# File 'lib/git_undo/git_manager.rb', line 28

def last_command
  @command_list.reverse.detect do |raw_command|
    command = parse_command(raw_command)[:action]
    GitReverser::VALID_COMMANDS.include?(command)
  end
end

#parse_command(command) ⇒ Object



35
36
37
38
39
40
# File 'lib/git_undo/git_manager.rb', line 35

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

#runObject



7
8
9
10
11
12
13
14
15
# File 'lib/git_undo/git_manager.rb', line 7

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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/git_undo/git_manager.rb', line 42

def undo_command(action, arguments)
  reverser = GitReverser.new(arguments)

  case action
  when 'add'
    reverser.reverse_add
  when 'commit'
    reverser.reverse_commit
  when 'merge'
    reverser.reverse_merge
  when 'checkout','co'
    reverser.reverse_checkout
  when 'rebase'
    reverser.reverse_rebase
  end
end

#undo_message(command) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/git_undo/git_manager.rb', line 59

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