Class: Git::Nebenan::Commands::Checkout

Inherits:
Command
  • Object
show all
Defined in:
lib/git/nebenan/commands/checkout.rb

Instance Method Summary collapse

Methods inherited from Command

#config, #jira_client, #logger, #platform, #prompt

Constructor Details

#initialize(options) ⇒ Checkout

Returns a new instance of Checkout.



5
6
7
# File 'lib/git/nebenan/commands/checkout.rb', line 5

def initialize(options)
  @options = options
end

Instance Method Details

#executeObject



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
# File 'lib/git/nebenan/commands/checkout.rb', line 9

def execute
  unless config.exist?
    logger.error 'missing config'
    logger.info 'run `git nebenan jira config first`'
    return
  end

  issues = jira_client.Issue.jql("PROJECT = '#{config.fetch('jira.project')}' AND status in ('Backlog', 'To Do', 'In Progress')", fields: [:summary, :assignee])

  choices = issues.map { |issue| { name: present(issue), value: issue.key } }

  puts "\n"

  key = prompt.select("Choose ticket?", choices, filter: true)

  remote_branch = find_remote_branch(key)
  local_branch = find_local_branch(key)

  puts "\n"

  command = if !local_branch.empty?
              logger.local "branch found, switching:"
              # puts Pastel.new.dim("  git checkout #{local_branch}")
              # `git checkout #{local_branch}`
              "git checkout #{local_branch}"
            elsif !remote_branch.empty?
              logger.remote "branch found, checking out:"
              "git checkout -t #{remote_branch}"
            else
              logger.create "missing branch:"
              "git checkout -b feature/#{generate_branch_name(issues.find { |i| i.key == key })}"
            end

  puts Pastel.new.dim("  #{command}")
  puts "\n"
  `#{command}`
rescue TTY::Reader::InputInterrupt
  puts "\n"
  logger.error 'aborted'
end

#find_local_branch(key) ⇒ Object



54
55
56
# File 'lib/git/nebenan/commands/checkout.rb', line 54

def find_local_branch(key)
  `git branch --list '**/#{key}*' --format \"%(refname:short)\"`.strip
end

#find_remote_branch(key) ⇒ Object



50
51
52
# File 'lib/git/nebenan/commands/checkout.rb', line 50

def find_remote_branch(key)
  `git branch --remote --list '**/#{key}*' --format \"%(refname:short)\"`.strip
end

#generate_branch_name(issue) ⇒ Object



58
59
60
# File 'lib/git/nebenan/commands/checkout.rb', line 58

def generate_branch_name(issue)
  [issue.key, issue.fields['summary'].strip.squish.downcase].join(' ').gsub(/\W/, ?-)
end

#present(issue) ⇒ Object



62
63
64
# File 'lib/git/nebenan/commands/checkout.rb', line 62

def present(issue)
  "#{issue.key} #{issue.fields['summary']} (#{issue.fields.dig('assignee', 'key') || Pastel.new.red('unassigned')})"
end