Sha256: 95b7de0f6c824385464f4cb09bbd4dc8783b34cebb59b1d52dde543d744a3563

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

require "trace_tree/version"
require 'binding_of_callers/pry'
require 'trace_tree/node'
require 'trace_tree/short_gem_path'
require 'trace_tree/color'
require 'trace_tree/tmp_file'
require 'trace_tree/timer'

class Binding
  def trace_tree *log, **opt, &to_do
    TraceTree.new(self).generate *log, **opt, &to_do
  end
end

class TraceTree

  def initialize bi
    @bi = bi
    @trace_points = []
    @timer = Timer.new
  end

  def generate *log, **opt, &to_do
    @opt = opt
    @log = dump_location *log
    @node_class = optional_node **opt
    @build_command = opt[:html] ? :tree_html_full : :tree_graph
    start_trace
    bi.eval('self').instance_eval &to_do
  ensure
    stop_trace
  end

  private

  attr_reader :bi, :trace_points, :log, :build_command, :timer, :opt

  def start_trace
    timer[:trace]
    @tp = TracePoint.trace(:call, :b_call, :raise, :c_call) do |point|
      trace_points << @node_class.new(point) if wanted? point
    end
  end

  def stop_trace
    return unless @tp
    @tp.disable
    timer[:trace]
    dump_trace_tree
  end

  def dump_location *log
    return TmpFile.new opt[:tmp] if opt[:tmp]
    log.empty? ? STDOUT : log[0]
  end

  def optional_node opt
    Class.new TraceTree::Node do
      prepend TraceTree::ShortGemPath unless opt[:gem] == false
      prepend TraceTree::Color unless opt[:color] == false
    end
  end

  def dump_trace_tree
    timer[:tree]
    tree = sort(trace_points).send build_command
    timer[:tree]
    log.puts tree
    log.puts timer.to_s if opt[:timer]
  end

  def wanted? trace_point
    trace_point.event != :c_call or trace_point.method_id == :throw
  end

  def sort stack
    hash = {}
    stack.each do |call|
      unless hash.empty?
        parent = hash[call.parent_stack]
        parent << call if parent
      end
      hash[call.whole_stack] = call
    end
    stack[0]
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
trace_tree-0.1.5 lib/trace_tree.rb