module TestProf

def activate(env_var, val = nil)

Contains workaround for applications using Spring.
equal to the provided value (if any).
Run block only if provided env var is present and
def activate(env_var, val = nil)
  if spring?
    notify_spring_detected
    ::Spring.after_fork do
      activate!(env_var, val) do
        notify_spring_activate env_var
        yield
      end
    end
  else
    activate!(env_var, val) { yield }
  end
end

def activate!(env_var, val)

def activate!(env_var, val)
  yield if ENV[env_var] && (val.nil? || val === ENV[env_var])
end

def artifact_path(filename)

Return a path to store artifact
def artifact_path(filename)
  create_artifact_dir
  with_timestamps(
    ::File.join(
      config.output_dir,
      with_report_suffix(
        filename
      )
    )
  )
end

def asset_path(filename)

Return absolute path to asset
def asset_path(filename)
  ::File.expand_path(filename, ::File.join(::File.dirname(__FILE__), "..", "..", "assets"))
end

def config

def config
  @config ||= Configuration.new
end

def configure

def configure
  yield config
end

def create_artifact_dir

def create_artifact_dir
  FileUtils.mkdir_p(config.output_dir)[0]
end

def minitest?

Returns true if we're inside Minitest
def minitest?
  defined?(Minitest)
end

def notify_spring_activate(env_var)

def notify_spring_activate(env_var)
  log :info, "Activating #{env_var} with `Spring.after_fork`"
end

def notify_spring_detected

def notify_spring_detected
  return if instance_variable_defined?(:@spring_notified)
  log :info, "Spring detected"
  @spring_notified = true
end

def now

Returns the current process time
def now
  Process.clock_gettime_for_test_prof(Process::CLOCK_MONOTONIC)
end

def require(gem_name, msg = nil)

message if it fails to load
Require gem and shows a custom
def require(gem_name, msg = nil)
  Kernel.require gem_name
  block_given? ? yield : true
rescue LoadError
  log(:error, msg) if msg
  false
end

def rspec?

Returns true if we're inside RSpec
def rspec?
  defined?(RSpec::Core)
end

def spring?

Returns true if Spring is used and not disabled
def spring?
  # See https://github.com/rails/spring/blob/577cf01f232bb6dbd0ade7df2df2ac209697e741/lib/spring/binstub.rb
  disabled = ENV["DISABLE_SPRING"]
  defined?(::Spring::Application) && (disabled.nil? || disabled.empty? || disabled == "0")
end

def with_report_suffix(path)

def with_report_suffix(path)
  return path if config.report_suffix.nil?
  "#{path.sub(/\.\w+$/, "")}-#{config.report_suffix}#{::File.extname(path)}"
end

def with_timestamps(path)

def with_timestamps(path)
  return path unless config.timestamps?
  timestamps = "-#{now.to_i}"
  "#{path.sub(/\.\w+$/, "")}#{timestamps}#{::File.extname(path)}"
end