Created
November 29, 2012 10:52
-
-
Save joakimk/4168172 to your computer and use it in GitHub Desktop.
More sane backtraces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Shortens filepaths, colorizes the lines that run with the application and | |
# excludes everything else unless you specify USE_LONG_BACKTRACES=true. | |
# We have this in: spec/sane_backtraces.rb, loaded from spec_helper.rb. | |
# Rspec shortens expectation errors when you don't use --backtrace, but not | |
# runtime errors like a missing method. | |
class Exception | |
USE_LONG_BACKTRACES = ENV['USE_LONG_BACKTRACES'] | |
alias_method :old_message, :message | |
def message | |
shorten_and_colorize_paths(old_message) | |
end | |
alias_method :old_inspect, :inspect | |
def inspect | |
shorten_and_colorize_paths(old_inspect) | |
end | |
alias_method :old_backtrace, :backtrace | |
def backtrace | |
data = old_backtrace | |
if data | |
if caller.first.match(/rspec.+read_failed_line/) | |
data | |
else | |
backtrace = data.map { |line| shorten_and_colorize_paths(line) } | |
if USE_LONG_BACKTRACES | |
backtrace | |
else | |
backtrace = backtrace.reject { |line| !/\[app\]/.match(line) } | |
# We can't be sure what is shown, rspec shortens too for expectation failures. | |
# So because of this it's "might be shortened" | |
backtrace << dark_gray_text("Backtrace might be shortened (set USE_LONG_BACKTRACES=true to disable)") | |
backtrace | |
end | |
end | |
else | |
nil | |
end | |
end | |
private | |
APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) | |
def shorten_and_colorize_paths(line) | |
line = line.gsub(/.+\.rvm.+gems/, '[gem]'). | |
gsub(APP_ROOT, "[app]"). | |
gsub(/.+\.rvm\/rubies\/.+?\//, "[ruby]/"). | |
gsub(/:in/, "") | |
if line.include?('[app]') | |
green_text(line) | |
else | |
line | |
end | |
end | |
def dark_gray_text(text) | |
"\e[01;30m#{text}\e[00m" | |
end | |
def green_text(text) | |
"\e[00;32m#{text}\e[00m" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment