Class: Changelog::Log

Inherits:
Base
  • Object
show all
Defined in:
lib/changelog.rb

Instance Method Summary collapse

Constructor Details

#initializeLog

Returns a new instance of Log.



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# File 'lib/changelog.rb', line 406

def initialize

  super
  @commit = CI.commit || Git.commit_sha
  @repo = CI.repo || Git.repo
  @build_no = CI.build_no
  @branch = CI.branch || Git.branch

  warning = 'Unable to determine repo branch' if @branch.nil?
  warning = 'Unable to determine SHA1' if @commit.nil?
  warning = 'Unable to determine repo' if @repo.nil?
  warning = 'Unable to determine GITHUB_TOKEN' if ENV['GITHUB_TOKEN'].nil?
  warning = 'Unable to determine TRAVIS_TOKEN' if ENV['TRAVIS_TOKEN'].nil?
  warning = 'Unable to determine SPRINTLY_USER' if ENV['SPRINTLY_USER'].nil?
  warning = 'Unable to determine SPRINTLY_API_KEY' if ENV['SPRINTLY_API_KEY'].nil?

  @logger.error warning if warning

  ENV['NO_OF_RELEASES'] = '2'
  ENV['YAML_BACKUP'] = '/releases.yml'
  ENV['TRAVIS_COMMIT_RANGE'] = nil if ENV['TRAVIS_COMMIT_RANGE'].nil?

  @auth = {:username => ENV['SPRINTLY_USER'], :password => ENV['SPRINTLY_API_KEY']}

  @repo = CI.repo || Git.repo
  @branch = CI.branch || Git.branch
  #TODO abstract Github via CI class
  @github = Github.new(@repo, @branch)

  @product_id = @github.sprintly_product_id
  if !@product_id
    @logger.error "Unable to retrieve Sprint.ly product_id for #{repo}"
    exit 1
  end


  #@releases = getReleasesFromYAML
  @releases = getReleasesFromServices if @releases.nil?
  #saveReleasesToYAML @releases unless @releases.nil?
end

Instance Method Details

#commitObject



451
452
453
# File 'lib/changelog.rb', line 451

def commit
  @commit
end

#commitItem(commit) ⇒ Object



300
301
302
303
304
# File 'lib/changelog.rb', line 300

def commitItem(commit)
  APICache.get(commit.sha, :fail => []) do
      Item.new(commit.commit.message.lines.first, commit.sha[0..6], commit.commit.message, commit.sha, commit.commit.author.date, "Github", "commit", "NA", commit.commit.author.name)
  end
end

#crashlyticsItem(title, id, sha, date, author) ⇒ Object



284
285
286
287
# File 'lib/changelog.rb', line 284

def crashlyticsItem(title, id, sha, date, author)
  #puts "    " + item["type"].capitalize + " " + item["number"].to_s + ": " + item["title"]
  return Item.new(title, id, "NA", sha, date, "Crashlytics", "crash", nil, author)
end

#deploy(releases) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/changelog.rb', line 205

def deploy(releases)
  buildItems = []
  allReleasedItems = []
  releases.each { |r|
    releaseItems = []
    r.items.each { |i|
      buildItems << i.id unless (i.built? || !i.complete?) #potential write each build for incomplete tasks or stories...not sure
      releaseItems << i.id unless (i.released? || !i.complete? || !r.released? || allReleasedItems.include?(i.id))
    }
    allReleasedItems.concat(releaseItems)
    releaseEnvironment = "Release #{r.name}"
    sprintlyDeploy(releaseItems.uniq, releaseEnvironment) unless (releaseEnvironment.nil? || !releaseItems.any?)
  }
  buildEnvironment = "Build ##{ENV['TRAVIS_BUILD_NUMBER']}"
  sprintlyDeploy(buildItems.uniq, buildEnvironment) unless (buildEnvironment.nil? || !buildItems.any?)
end

#display(audience = 'production') ⇒ Object



447
448
449
# File 'lib/changelog.rb', line 447

def display(audience='production')
  displayReleases @releases unless @releases.nil?
end

#displayDate(date) ⇒ Object



325
326
327
# File 'lib/changelog.rb', line 325

def displayDate(date)
  return date.strftime("%-d-%b-%Y")
end

#displayEnvironments(environments) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
# File 'lib/changelog.rb', line 193

def displayEnvironments(environments)
  case
    when environments.nil?
      environments = ""
    when environments.compact.length > 0
      environments = " [" + environments.compact.join(", ") + "]"
    else
      environments = ""
  end
  return environments
end

#displayReleases(releases) ⇒ Object



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/changelog.rb', line 236

def displayReleases(releases)
  f = Formatador.new
  types = releases.flat_map { |r|
    r.items.flat_map { |i|
      i.type
    }
  }.uniq
  environments = releases.flat_map { |r|
    r.items.flat_map { |i|
      i.environments.flatten unless i.environments.nil?
    }
  }.uniq.compact
  #puts environments.inspect
  releases.each { |r|
    f.display_line("#{r.name} (#{r.status.upcase}, #{displayDate(r.date)})")
    f.indent {

      types.each { |t|
        items = r.items.select { |i| i.type == t }
        f.display_line("#{t.upcase}") if items.length > 0
        f.indent {
          items.each { |i|
            # i.sha[0..6]
            #TODO fix this
            bullet = ENV['TRAVIS_COMMIT'] == i.sha[0..6] ? "+" : ""
            f.display_line("#{bullet} ##{i.id}: #{i.title} (#{i.status.upcase}; #{i.author}; #{displayDate(i.date)})#{displayEnvironments(i.environments)}")

          }
        }
      }
    }

  }
end

#getReleasesFromServicesObject

TRAVIS_COMMIT_RANGE



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/changelog.rb', line 337

def getReleasesFromServices


  #user = @github.client.user
  #user.login


  result = []

  all_releases = @github.releases
  #p all_releases.inspect
  r = all_releases.first
  #p r
  p r.tag_name
  ref = @github.ref(r.tag_name)
  sha = ref.object.sha
  commit = @github.commit(sha).commit
  since = commit.author.date

  commits = @github.commits_since(since)
  commits.pop #remove commit from last release - not sure why this in necessary and recon that it is not accurate either

  items = []
  commits.each { |c| items.concat(itemsFromCommit(c)) }

  release = Release.new("Next Version", "NA", sha, since, "NA", items)

  result << release

  releases = all_releases.take(ENV['NO_OF_RELEASES'].to_i)

  releases.each_with_index { |r, index|

    next_r = all_releases[index+1] unless index == all_releases.size - 1 #note we use all_releases for this
    ref = @github.ref(r.tag_name)
    sha = ref.object.sha
    commit = @github.commit(sha).commit

    to = commit.author.date

    if next_r
      next_ref = @github.ref(next_r.tag_name)
      next_sha = next_ref.object.sha
      next_commit = @github.commit(next_sha).commit
      from = next_commit.author.date
      commits = @github.client.commits_between(ENV['TRAVIS_REPO_SLUG'], from, to, ENV['TRAVIS_BRANCH'])
    else
      commits = @github.client.commits_before(ENV['TRAVIS_REPO_SLUG'], to, ENV['TRAVIS_BRANCH'])
    end

    items = []
    commits.each { |c| items.concat(itemsFromCommit(c)) }

    release = Release.new(r.tag_name, r.name, sha, to, githubReleaseStatus(r), items)

    result << release
  }
  return result
end

#getReleasesFromYAMLObject



397
398
399
# File 'lib/changelog.rb', line 397

def getReleasesFromYAML
  return YAML.load_file(Dir.pwd + ENV['YAML_BACKUP']) if File.file?(Dir.pwd + ENV['YAML_BACKUP'])
end

#githubReleaseStatus(release = nil) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/changelog.rb', line 178

def githubReleaseStatus(release=nil)
  case
    when release.nil?
      status = "NA"
    when release.draft
      status = "DRAFT"
    when release.prerelease
      status = "PRE-RELEASE"
    else
      status = "RELEASED"
  end
  return status
end

#idsFromCommitMessage(message) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/changelog.rb', line 271

def idsFromCommitMessage(message)
  commands = %w(close closed closes finish finished finishes fix fixed fixes breaks unfixes reopen reopens re-open re-opens addresses re ref references refs start starts see).collect { |x| "\\b#{x}\\b" }.join("|")
  prefixes = %w(task issue defect bug item ticket).collect { |x| "\\b#{x}:\\b" }.join("|") + "|#"
  re = Regexp.new(/(?:#{commands})\s(?:#{prefixes})(\d+)/)
  #working re = Regexp.new(/(?:#{commands})\s(?:#{prefixes})(\d+)/)
  #working re = Regexp.new(/(?:\bcloses\b|\bfixes\b)..(\d+)/)
  #puts re.source

  sprintlyIds = message.scan(re).flatten.compact
  crashlyticsIds = message.scan(/(c|C):(?<crashlytics>\d+)/).flatten.compact
  return sprintlyIds, crashlyticsIds
end

#itemsFromCommit(commit) ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/changelog.rb', line 308

def itemsFromCommit(commit)
  #pp commit
  items = []
  sprintlyIds, crashlyticsIds = idsFromCommitMessage(commit.commit.message)
  #puts sprintlyIds.class
  #puts commit.commit.message
  unless (sprintlyIds.nil? || !sprintlyIds.any?) then
    sprintlyIds.each { |id| items << sprintlyItem(id, commit.sha, commit.commit.author.date, commit.commit.author.name) }
  end
  unless (crashlyticsIds.nil? || !crashlyticsIds.any?) then
    crashlyticsIds.each { |id| items << crashlyticsItem(commit.commit.message.lines.first, id, commit.sha, commit.commit.author.date, commit.commit.author.name) }
  end
  items << commitItem(commit) unless (!items.nil? && items.any?)
  return items
end

#saveReleasesToYAML(releases) ⇒ Object



401
402
403
# File 'lib/changelog.rb', line 401

def saveReleasesToYAML(releases)
  File.open(Dir.pwd + ENV['YAML_BACKUP'], 'w') { |file| file.write(releases.to_yaml) }
end

#sprintlyDeploy(ids, environment) ⇒ Object

refactor to keep source data separate, and update environments on sprint.ly ticket so future checks return the new environemnt deployments should also be batched, with one api call for all items of the build or release



225
226
227
228
229
230
231
232
233
234
# File 'lib/changelog.rb', line 225

def sprintlyDeploy(ids, environment)
  #@iterations += 1
  data = {:environment => environment, :numbers => ids.join(",")}
  url = "https://sprint.ly/api/products/#{@product_id}/deploys.json"
  response = HTTParty.post(url, {:basic_auth => @auth, :body => data})
  item = JSON.parse(response.body)
  #pp item
  #exit unless @iterations < 2
  #curl -u [email protected]:WXKp2h3F38VUm2CmzxpqBYMDZBFvw84f --data "environment=test&numbers=22,8" https://sprint.ly/api/products/20064/deploys.json
end

#sprintlyItem(id, sha, date, author) ⇒ Object

TODO - cache raw response, not item



291
292
293
294
295
296
297
298
# File 'lib/changelog.rb', line 291

def sprintlyItem(id, sha, date, author)
  url = "https://sprint.ly/api/products/" + @product_id + "/items/" + id + ".json"
  APICache.get(url, :timeout => 30, :fail => []) do
      response = HTTParty.get(url, :basic_auth => @auth)
      item = JSON.parse(response.body)
      Item.new(item["title"], item["number"], item["description"], sha, date, "Sprint.ly", item["type"], item["status"], author, item["deployed_to"])
    end
end