Class: DependencyChart

Inherits:
ChartBase show all
Defined in:
lib/jirametrics/dependency_chart.rb

Defined Under Namespace

Classes: IssueRules, LinkRules, Palette

Constant Summary collapse

PALETTE =
{
  story: palette_entry('story'),
  task: palette_entry('task'),
  bug: palette_entry('bug'),
  epic: palette_entry('epic'),
  spike: palette_entry('spike')
}.freeze

Constants inherited from ChartBase

ChartBase::LABEL_POSITIONS, ChartBase::OKABE_ITO_PALETTE

Instance Attribute Summary

Attributes inherited from ChartBase

#aggregated_project, #all_boards, #atlassian_document_format, #board_id, #canvas_height, #canvas_width, #color_palette, #data_quality, #date_range, #file_system, #fix_versions, #holiday_dates, #issues, #settings, #time_range, #timezone_offset, #x_axis_title, #y_axis_title

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ChartBase

#aggregated_project?, #before_run, #call_before_run, #canvas, #canvas_responsive?, #chart_format, #collapsible_issues_panel, #color_block, #comma_and, #completed_issues_in_range, #current_board, #cycletime, #cycletime_for_issue, #daily_chart_dataset, #date_annotation, #describe_non_working_days, #description_text, #format_integer, #format_status, #header_text, #holidays, #html_directory, #icon_span, #link_to_issue, #next_id, #next_palette_color, #non_working_day?, #normalize_annotation_datetime, #not_visible_icon, #not_visible_text, #ordinal, #percentile_of, #render, #render_axis_title, #render_top_text, #resolve_status, #stagger_label_positions, #status_category_color, #to_human_readable, #working_days_annotation, #wrap_and_render

Constructor Details

#initialize(rules_block) ⇒ DependencyChart

Returns a new instance of DependencyChart.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/jirametrics/dependency_chart.rb', line 54

def initialize rules_block
  super()

  # Not the inherited type colours, because these are fills with label text sitting on top of
  # them and those are line colours, judged against the page rather than against the text. See
  # index.css for which colours these are and why.
  @palette_by_type = {
    'Story' => PALETTE[:story],
    'Task' => PALETTE[:task],
    'Bug' => PALETTE[:bug],
    'Defect' => PALETTE[:bug],
    'Epic' => PALETTE[:epic],
    'Spike' => PALETTE[:spike]
  }

  header_text 'Dependencies'
  description_text <<-HTML
    <p>
      These are all the "linked issues" as defined in Jira
    </p>
  HTML

  @rules_block = rules_block

  issue_rules(&default_issue_rules)
  link_rules(&default_link_rules)
end

Class Method Details

.palette_entry(name) ⇒ Object



41
42
43
44
# File 'lib/jirametrics/dependency_chart.rb', line 41

def self.palette_entry name
  Palette.new CssVariable["--dependency-chart-#{name}-color"],
    CssVariable["--dependency-chart-#{name}-label-color"]
end

Instance Method Details

#assemble_dot_graph(visible_issues, link_graph) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/jirametrics/dependency_chart.rb', line 268

def assemble_dot_graph visible_issues, link_graph
  dot_graph = ['digraph mygraph {', 'rankdir=LR', 'bgcolor="transparent"']

  # Sort the keys so they are proccessed in a deterministic order.
  visible_issues.values.sort_by(&:key_as_i).each do |issue|
    rules = IssueRules.new
    @issue_rules_block.call(issue, rules)
    dot_graph << make_dot_issue(issue: issue, issue_rules: rules)
  end

  dot_graph + link_graph + ['}']
end

#build_dot_graphObject



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/jirametrics/dependency_chart.rb', line 216

def build_dot_graph
  issue_links = find_links

  visible_issues = {}
  link_graph = []
  links_to_ignore = []

  issue_links.each do |link|
    next if links_to_ignore.include? link

    link_rules = LinkRules.new
    @link_rules_block.call link, link_rules

    next if link_rules.ignored?
    next if merge_bidirectional_skip?(link, link_rules, issue_links, links_to_ignore)

    link_graph << make_dot_link(issue_link: link, link_rules: link_rules)
    visible_issues[link.origin.key] = link.origin
    visible_issues[link.other_issue.key] = link.other_issue
  end

  return nil if visible_issues.empty?

  assemble_dot_graph(visible_issues, link_graph)
end

#color_for(type:) ⇒ Object



193
194
195
# File 'lib/jirametrics/dependency_chart.rb', line 193

def color_for type:
  palette_for(type).fill
end

#css_variable_placeholdersObject



124
125
126
# File 'lib/jirametrics/dependency_chart.rb', line 124

def css_variable_placeholders
  @css_variable_placeholders ||= {}
end

#default_issue_rulesObject



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/jirametrics/dependency_chart.rb', line 321

def default_issue_rules
  chart = self
  lambda do |issue, rules|
    is_done = issue.done?

    key = issue.key
    key = "<S>#{key} </S> " if is_done
    line2 = +'<BR/>'
    if issue.artificial?
      line2 << '(unknown state)' # Shouldn't happen if we've done a full download but is still possible.
    elsif is_done
      line2 << 'Done'
    else
      started_at = issue.started_stopped_times.first
      if started_at.nil?
        line2 << 'Not started'
      else
        line2 << "Age: #{issue.board.cycletime.age(issue, today: chart.date_range.end)} days"
      end
    end
    rules.label = "<#{key} [#{issue.type}]#{line2}<BR/>#{word_wrap issue.summary}>"
  end
end


201
202
203
# File 'lib/jirametrics/dependency_chart.rb', line 201

def default_link_color
  CssVariable['--dependency-chart-link-color']
end


345
346
347
348
349
350
351
# File 'lib/jirametrics/dependency_chart.rb', line 345

def default_link_rules
  lambda do |link, rules|
    rules.ignore if link.origin.done? && link.other_issue.done?
    rules.ignore if link.name == 'Cloners'
    rules.merge_bidirectional keep: 'outward'
  end
end

#execute_graphviz(dot_graph) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
# File 'lib/jirametrics/dependency_chart.rb', line 281

def execute_graphviz dot_graph
  Open3.popen3('dot -Tsvg') do |stdin, stdout, _stderr, _wait_thread|
    stdin.write dot_graph
    stdin.close
    return stdout.read
  end
rescue # rubocop:disable Style/RescueStandardError
  message = 'Unable to generate the dependency chart because graphviz could not be found in the path.'
  file_system.log message, also_write_to_stderr: true
  message
end


103
104
105
106
107
108
109
# File 'lib/jirametrics/dependency_chart.rb', line 103

def find_links
  result = []
  issues.each do |issue|
    result += issue.issue_links
  end
  result
end


260
261
262
263
264
265
266
# File 'lib/jirametrics/dependency_chart.rb', line 260

def find_opposite_link link, issue_links
  issue_links.find do |candidate|
    candidate.name == link.name &&
      candidate.origin.key == link.other_issue.key &&
      candidate.other_issue.key == link.origin.key
  end
end

#graphviz_color(color) ⇒ Object

Graphviz has never heard of CSS variables. Handed one it emits a warning nobody sees and falls back to black, which is how a node ends up as black text on a black background. So a variable is swapped for a placeholder colour here and mapped back to the variable in the generated SVG, by #restore_css_variables. Anything that isn't a variable is left alone.

The placeholders only need to be colours that nobody would ever choose deliberately, so that the CSS selectors matching them in the SVG cannot hit anything else.



118
119
120
121
122
# File 'lib/jirametrics/dependency_chart.rb', line 118

def graphviz_color color
  return color unless color.is_a? CssVariable

  css_variable_placeholders[color.name] ||= format '#fe00%02x', css_variable_placeholders.size + 1
end

#issue_rules(&block) ⇒ Object



99
100
101
# File 'lib/jirametrics/dependency_chart.rb', line 99

def issue_rules &block
  @issue_rules_block = block
end

#label_color(issue:, issue_rules:) ⇒ Object

A filled node is its own background, so its label is measured against the fill rather than against the page.



183
184
185
186
187
188
189
190
191
# File 'lib/jirametrics/dependency_chart.rb', line 183

def label_color issue:, issue_rules:
  return CssVariable['--default-text-color'] if issue_rules.color == :none

  # A colour somebody configured is one we know nothing about, so guessing that a particular
  # type's label would suit it is worse than falling back to the general one.
  return CssVariable['--dependency-chart-label-color'] if issue_rules.color

  palette_for(issue.type).label
end


95
96
97
# File 'lib/jirametrics/dependency_chart.rb', line 95

def link_rules &block
  @link_rules_block = block
end

#make_dot_issue(issue:, issue_rules:) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/jirametrics/dependency_chart.rb', line 162

def make_dot_issue issue:, issue_rules:
  result = +''
  result << issue.key.inspect
  result << '['
  label = issue_rules.label || "#{issue.key}|#{issue.type}"
  label = label.inspect unless label.match?(/^<.+>$/)
  result << "label=#{label}"
  result << ',shape=Mrecord'
  tooltip = "#{issue.key}: #{issue.summary}"
  result << ",tooltip=#{tooltip[0..80].inspect}"
  unless issue_rules.color == :none
    fill_color = graphviz_color(issue_rules.color || color_for(type: issue.type))
    result << %(,style=filled,fillcolor="#{fill_color}")
  end
  result << %(,fontcolor="#{graphviz_color label_color(issue: issue, issue_rules: issue_rules)}")
  result << ']'
  result
end


147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/jirametrics/dependency_chart.rb', line 147

def make_dot_link issue_link:, link_rules:
  result = +''
  result << issue_link.origin.key.inspect
  result << ' -> '
  result << issue_link.other_issue.key.inspect
  result << '['
  result << 'label=' << (link_rules.label || issue_link.label).inspect
  line_color = graphviz_color(link_rules.line_color || default_link_color)
  result << ',color=' << line_color.inspect
  result << ',fontcolor=' << line_color.inspect
  result << ',dir=both' if link_rules.bidirectional_arrows?
  result << '];'
  result
end

#merge_bidirectional_skip?(link, link_rules, issue_links, links_to_ignore) ⇒ Boolean

For a bidirectional-merge link, collapses the pair into one. When this link is the one to keep, its opposite is added to links_to_ignore; returns true when this link should be skipped in favour of its opposite. Returns false (keep this link) when there's no merge or no matching opposite.

Returns:

  • (Boolean)


245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/jirametrics/dependency_chart.rb', line 245

def merge_bidirectional_skip? link, link_rules, issue_links, links_to_ignore
  merge_direction = link_rules.get_merge_bidirectional
  return false unless merge_direction

  opposite = find_opposite_link(link, issue_links)
  return false unless opposite

  if merge_direction.to_sym == link.direction
    links_to_ignore << opposite # keep this one, discard the opposite
    false
  else
    true # keep the opposite, skip this one
  end
end

#next_palette_entryObject

An issue type we have no colour for cannot come from the shared palette, the way it does on every other chart. That palette holds line colours, judged against the page, and its first slot is Okabe-Ito blue, which leaves black label text at 4.05:1 once it becomes the fill behind it. These rotate this chart's own entries, which are all known to be comfortable. Two unknown types can therefore land on the same colour as each other or as a known type, which costs little: every node already names its type in the label.



211
212
213
214
# File 'lib/jirametrics/dependency_chart.rb', line 211

def next_palette_entry
  @fallback_color_index = (@fallback_color_index || -1) + 1
  PALETTE.values[@fallback_color_index % PALETTE.size]
end

#palette_for(type) ⇒ Object



197
198
199
# File 'lib/jirametrics/dependency_chart.rb', line 197

def palette_for type
  @palette_by_type[type] ||= next_palette_entry
end

#restore_css_variables(svg) ⇒ Object

Turns the placeholders from #graphviz_color back into the variables they stood for, by way of a stylesheet that selects on the placeholder value. Rewriting the attributes in place would be the obvious move, but var() is only legal in a CSS value and not in an SVG presentation attribute, so the colour has to arrive as a real CSS rule. Author rules beat presentation attributes, so the placeholder never wins.

fillcolor and fontcolor come out of graphviz as fill and color comes out as stroke, and an arrowhead uses both, so every placeholder gets a rule for each.



136
137
138
139
140
141
142
143
144
145
# File 'lib/jirametrics/dependency_chart.rb', line 136

def restore_css_variables svg
  return svg if css_variable_placeholders.empty?

  rules = css_variable_placeholders.map do |name, placeholder|
    %([fill="#{placeholder}"]{fill:var(#{name})}[stroke="#{placeholder}"]{stroke:var(#{name})})
  end
  svg.sub(/(?<opening_tag><svg\b[^>]*>)/) do
    "#{Regexp.last_match[:opening_tag]}<style>#{rules.join}</style>"
  end
end

#runObject



82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/jirametrics/dependency_chart.rb', line 82

def run
  instance_eval(&@rules_block) if @rules_block

  dot_graph = build_dot_graph
  if dot_graph.nil?
    return "<h1 class='foldable'>#{@header_text}</h1>" \
      '<div>No data matched the selected criteria. Nothing to show.</div>'
  end

  svg = restore_css_variables execute_graphviz(dot_graph.join("\n"))
  "<h1 class='foldable'>#{@header_text}</h1><div>#{@description_text}#{shrink_svg svg}</div>"
end

#shrink_svg(svg) ⇒ Object



293
294
295
296
297
298
299
300
301
# File 'lib/jirametrics/dependency_chart.rb', line 293

def shrink_svg svg
  scale = 0.8
  svg.sub(/width="(?<width_pt>[\d.]+)pt" height="(?<height_pt>[\d.]+)pt"/) do
    match = Regexp.last_match
    width = match[:width_pt].to_i * scale
    height = match[:height_pt].to_i * scale
    "width=\"#{width.to_i}pt\" height=\"#{height.to_i}pt\""
  end
end

#word_wrap(text, max_width: 50, separator: '<BR/>') ⇒ Object



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/jirametrics/dependency_chart.rb', line 303

def word_wrap text, max_width: 50, separator: '<BR/>'
  text.chomp.lines.collect do |line|
    line.chomp!

    # The following characters all cause problems when passed to graphviz
    line.gsub!(/[{<]/, '[')
    line.gsub!(/[}>]/, ']')
    line.gsub!(/\s*&\s*/, ' and ')
    line.delete!('|')

    if line.length > max_width
      line.gsub(/(.{1,#{max_width}})(\s+|$)/, "\\1#{separator}").strip
    else
      line
    end
  end.join(separator)
end