Class: Jira

Inherits:
Object
  • Object
show all
Defined in:
lib/cl/magic/common/jira.rb

Constant Summary collapse

MAX_THREADS =

set to 1 to debug without concurrency

20

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_uri, username, token, break_at_one_page = false) ⇒ Jira

Returns a new instance of Jira.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/cl/magic/common/jira.rb', line 9

def initialize(base_uri, username, token, break_at_one_page=false)
  @base_uri = base_uri.chomp("/")
  @username = username
  @token = token
  @break_at_one_page = break_at_one_page

  @thread_pool = Concurrent::ThreadPoolExecutor.new(
    min_threads: 0,
    max_threads: MAX_THREADS,
    max_queue: 0,
    fallback_policy: :caller_runs
  )
end

Class Method Details

.jira_to_markdown(issue) ⇒ Object

Formatter



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/cl/magic/common/jira.rb', line 27

def self.jira_to_markdown(issue)

  md = []
  md << ""
  md << "# #{issue['key']}"
  md << "project:     #{issue['fields']['project']['key']}"
  md << "created:     #{issue['fields']['created']}"
  md << "updated:     #{issue['fields']['updated']}"
  md << "status:      #{issue['fields']['status']['statusCategory']['name']}" unless issue['fields']["status"].nil?
  md << "priority:    #{issue['fields']['priority']['name']}"
  md << "labels:      #{issue['fields']['labels'].join(',')}"
  md << "issue_type:  #{issue['fields']['issuetype']['name']}" unless issue['fields']["issuetype"].nil?
  md << "assignee:    #{issue['fields']['assignee']['displayName']}" unless issue['fields']["assignee"].nil?
  md << ""
  md << "## Summary"
  md << "#{issue['fields']['summary']}"
  md << ""
  md << ""
  issue_md = md.join("\n")

  comments = []
  issue["comments"].each_with_index do |comment, i|
    c_md = []
    c_md << "### Comment - #{comment["author"]["displayName"]} "
    c_md << ""
    c_md << "created: #{comment["created"]}"

    # nest markdown deeper
    comment["body"].split("\n").each do |line|
      c_md << if line.start_with?("#")
        "####{line}"
      else
        line
      end
    end

    c_md << ""
    comments << [comment["id"], c_md.join("\n")]
  end

  return issue_md, comments
end

Instance Method Details

#collect_comments(jira, issues) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/cl/magic/common/jira.rb', line 199

def collect_comments(jira, issues)
  final_issue_hashes = []
  bar = TTY::ProgressBar.new("fetching [:bar]", total: issues.count)

  issues.each do |issue|
    do_concurently do
      issue_key = issue["key"]
      issue["comments"] = []

      # fetch change log
      comments = get_issue_comments(issue_key)
      issue["comments"] = comments
      final_issue_hashes << issue # save
      bar.advance
    end
  end

  # wait
  wait_concurrently
  return final_issue_hashes
end

#collect_status_changelogs(jira, issues) ⇒ Object

Collect status changelogs

Given a array of jira issue hashes

  • fetch the change log

  • filter down to status changes

  • add it to the issue hash as [“status_changelogs”]



230
231
232
233
234
235
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/cl/magic/common/jira.rb', line 230

def collect_status_changelogs(jira, issues)
  final_issue_hashes = []
  bar = TTY::ProgressBar.new("fetching [:bar]", total: issues.count)

  issues.each do |issue|
    do_concurently do
      issue_key = issue["key"]
      issue["status_changelogs"] = []

      # fetch change log
      changelogs = get_issue_status_changelog(issue_key)

      changelogs.each do |change_log|

        # all items that are status changes
        status_logs = change_log["items"].select {|i| i["field"]=="status"}
        status_logs = status_logs.collect do |status_log|
          {
            "key": issue_key,
            "created": change_log["created"],
            "toString": status_log["toString"],
            "fromString": status_log["fromString"]
          }
        end

        # append them to issue
        status_logs.each do |status_log|
          issue["status_changelogs"] << status_log
        end
      end

      final_issue_hashes << issue # save
      bar.advance
    end
  end

  # wait
  wait_concurrently
  return final_issue_hashes
end

#get_epic_ids(project, epic_wildcard) ⇒ Object

Fetch: Issues & Change Logs



74
75
76
77
78
79
80
# File 'lib/cl/magic/common/jira.rb', line 74

def get_epic_ids(project, epic_wildcard)
  jql_query = "project = \"#{project}\" AND issuetype = Epic AND text ~ \"#{epic_wildcard}\""
  results = run_jql_query(jql_query)
  epics = results.select{|h| h['fields']['summary'].start_with? epic_wildcard}
  epic_ids = epics.map {|h| h['id']}
  return epic_ids, epics
end

#get_issue_comments(issue_key) ⇒ Object



95
96
97
98
99
100
101
# File 'lib/cl/magic/common/jira.rb', line 95

def get_issue_comments(issue_key)
  uri = URI.parse("#{@base_uri}/rest/api/2/issue/#{issue_key}/comment")
  jira_get(uri) do |response|
    result = JSON.parse(response.body)
    return result["comments"]
  end
end

#get_issue_status_changelog(issue_key) ⇒ Object



87
88
89
90
91
92
93
# File 'lib/cl/magic/common/jira.rb', line 87

def get_issue_status_changelog(issue_key)
  uri = URI.parse("#{@base_uri}/rest/api/2/issue/#{issue_key}/changelog")
  jira_get(uri) do |response|
    result = JSON.parse(response.body)
    return result["values"]
  end
end

#get_issues_by_epic_ids(project, epic_ids) ⇒ Object



82
83
84
85
# File 'lib/cl/magic/common/jira.rb', line 82

def get_issues_by_epic_ids(project, epic_ids)
  jql_query = "project = \"#{project}\" AND parentEpic IN (#{epic_ids.join(',')})"
  return run_jql_query(jql_query)
end

#jira_get(uri) ⇒ Object

Helpers: GET & POST



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/cl/magic/common/jira.rb', line 107

def jira_get(uri)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  # get request
  request = Net::HTTP::Get.new(uri.path)
  request.basic_auth(@username, @token)

  # fetch
  response = http.request(request)
  if response.code == '200'
    yield response
  else
    raise """
    Jira query failed with HTTP status code #{response.code}

    #{response.body}
    """
  end
end

#jira_post(uri, body) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/cl/magic/common/jira.rb', line 128

def jira_post(uri, body)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  # post request
  request = Net::HTTP::Post.new(uri.path)
  request.basic_auth(@username, @token)
  request.content_type = 'application/json'
  request.body = body.to_json

  # fetch
  response = http.request(request)
  if response.code == '200'
    yield response
  else
    raise """
    Jira query failed with HTTP status code #{response.code}

    BODY: #{body.to_json}

    RESPONSE: #{response.body}
    """
  end
end

#run_jql_query(jql) ⇒ Object

Fetch: JQL Query



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/cl/magic/common/jira.rb', line 157

def run_jql_query(jql)
  spinner = TTY::Spinner.new("[:spinner] fetching ...", format: :pulse_2)
  spinner.auto_spin # Automatic animation with default interval

  start_at = 0
  max_results = 50
  total_results = nil
  all_results = []

  page_loop = true
  while page_loop

    uri = URI("#{@base_uri}/rest/api/2/search")
    body = { jql: jql, startAt: start_at, maxResults: max_results }

    # post
    jira_post(uri, body) do |response|
      result = JSON.parse(response.body)

      # get issues
      issues = result['issues']
      all_results += issues

      # debug: one page only
      if @break_at_one_page
        page_loop = false
        break
      end

      # paginate
      total_results ||= result['total']
      if all_results.count == total_results
        page_loop = false       # we got them all, stop paging
      else
        start_at += max_results # else next page
      end
    end
  end
  spinner.stop("#{all_results.count} issues")
  all_results.map {|h| h}
end