Class: Circlemator::BuildCanceler

Inherits:
Object
  • Object
show all
Defined in:
lib/circlemator/build_canceler.rb

Instance Method Summary collapse

Constructor Details

#initialize(user:, repo:, current_build:, circle_api_token:, **_opts) ⇒ BuildCanceler

Returns a new instance of BuildCanceler.



7
8
9
10
11
12
# File 'lib/circlemator/build_canceler.rb', line 7

def initialize(user:, repo:, current_build:, circle_api_token:, **_opts)
  @user = user
  @repo = repo
  @current_build = current_build
  @circle_api_token = circle_api_token
end

Instance Method Details

#cancel_old_builds!Object



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
# File 'lib/circlemator/build_canceler.rb', line 14

def cancel_old_builds!
  resp = HTTParty.get "https://circleci.com/api/v1/project/#{@user}/#{@repo}",
                      circle_auth
  check_response resp

  builds = JSON.parse(resp.body)
           .select   { |b| %w(running scheduled queued not_running).include?(b.fetch('status')) && b['branch'] }
           .group_by { |b| b.fetch('branch') }
           .flat_map { |_, group| group.sort_by { |b| b.fetch('build_num') }[0...-1] }
           .map      { |b| b.fetch('build_num') }

  cancel_self = !!builds.delete(@current_build)

  builds.each do |build_num|
    resp = HTTParty.post "https://circleci.com/api/v1/project/#{@user}/#{@repo}/#{build_num}/cancel",
                         circle_auth
    check_response resp
  end

  if cancel_self
    puts 'Daisy, Daisy, give me your answer, do...'
    HTTParty.post "https://circleci.com/api/v1/project/#{@user}/#{@repo}/#{@current_build}/cancel",
                  circle_auth
  end
end