1

I'm trying to colorize the output of a patch. Setting the color.diff config (via my .gitconfig) doesn't seem to do it.

repo = Rugged::Repository.new('/some/path')
repo.config = Rugged::Config.new("#{ENV['HOME']}/.gitconfig")
log.info repo.config['color.diff']

INFO color.diff: always

And I'm doing the following to show unstaged changes:

repo.index.diff.each do |patch|
  puts patch
end

Can I get a prettier colorized diff?

Nathan Meyer
  • 141
  • 5

2 Answers2

2

Here's how I did it with the colorize gem:

def diff 
  diff = @repo.index
    .diff
    .each_patch
    .to_a

  diff.each do |patch|
    patch.to_s.split("\n").each do |line|
      puts colorize_diff(line)
    end
  end
end

def colorize_diff(line)
  color =
    case line[0, 1]
    when "+"
      :green
    when "-"
      :red
    when "@"
      :cyan
    end
  color ? line.send(color) : line
end
Nathan Meyer
  • 141
  • 5
1

color.diff is an option for the git user-facing tool to put colours on the terminal. There is no equivalent for rugged/libgit2, as they do not handle the user interface or print to the terminal but instead produce the data.

How to generate colour on a terminal (or other device) is its own complex issue that requires its own libraries and workarounds for common problems and it lies completely outside of rugged/libgit2's scope.

I would recommend looking in https://rubygems.org for a gem which knows how to handle the terminals you're interested in.

Carlos Martín Nieto
  • 5,207
  • 1
  • 15
  • 16