Class: GitBranchSelector

Inherits:
Object
  • Object
show all
Defined in:
lib/git-branch-selector.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(flag:, branch_lookback_count:) ⇒ GitBranchSelector

Returns a new instance of GitBranchSelector.



10
11
12
13
# File 'lib/git-branch-selector.rb', line 10

def initialize(flag:, branch_lookback_count:)
  @flag = flag
  @branch_lookback_count = branch_lookback_count
end

Instance Attribute Details

#branch_lookback_countObject (readonly)

Returns the value of attribute branch_lookback_count.



8
9
10
# File 'lib/git-branch-selector.rb', line 8

def branch_lookback_count
  @branch_lookback_count
end

#flagObject (readonly)

Returns the value of attribute flag.



8
9
10
# File 'lib/git-branch-selector.rb', line 8

def flag
  @flag
end

Instance Method Details

#build_menuObject



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
# File 'lib/git-branch-selector.rb', line 15

def build_menu
  return show_list if flag == 'list'

  if cleaned_branches.empty?
    puts %q(
      No branches to list. Ensure you're using this within a Git repository.
    )
    return
  end

  selected_option = TTY::Prompt.new.select(
    "Pick a branch",
    cycle: true,
    symbols: { marker: '' },
    per_page: cleaned_branches.length,
    filter: true,
    help: '(Arrows, numbers, type to filter, enter to select)',
    show_help: :always
  ) do |menu|
    menu.enum ':'

    cleaned_branches.each_with_index do |b, index|
      menu.choice b, index + 1
    end
  end

  branch_name = cleaned_branches[selected_option - 1]

  cmd = flag == 'copy' ? "echo #{branch_name} | pbcopy" : "git checkout #{branch_name}"

  Open3.capture3(cmd)
end

#cleaned_branchesObject



54
55
56
57
58
# File 'lib/git-branch-selector.rb', line 54

def cleaned_branches
  @cleaned_branches ||= get_branches.split("\n").map do |branch|
    branch.split(/\s+\d+\t\s+/).last
  end
end

#get_branchesObject



60
61
62
63
64
65
# File 'lib/git-branch-selector.rb', line 60

def get_branches
  get_branches_cmd = "git log -g --grep-reflog 'checkout:' --format='%gs' | sed -E 's/checkout: moving from .* to//g' | awk '!seen[$0]++' | head -n #{branch_lookback_count} | cat -n"

  recent_branches, = Open3.capture3(get_branches_cmd)
  recent_branches
end

#show_listObject



48
49
50
51
52
# File 'lib/git-branch-selector.rb', line 48

def show_list
  cleaned_branches.each_with_index do |b, i|
    puts "#{i + 1}: #{b}"
  end
end