Class: DiffString

Inherits:
Object
  • Object
show all
Includes:
Colors
Defined in:
lib/diff_string.rb

Overview

An added or removed part of a diff, which can contain both highlighted and not highlighted characters. For multi line strings, each line will be prefixed with prefix and color.

Constant Summary

Constants included from Colors

Colors::BOLD, Colors::CYAN, Colors::DEFAULT_COLOR, Colors::ESC, Colors::GREEN, Colors::NOT_REVERSE, Colors::RED, Colors::RESET, Colors::REVERSE

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Colors

#reversed, #uncolor

Constructor Details

#initialize(prefix, color) ⇒ DiffString

Note that the color argument can be the empty string



11
12
13
14
15
16
17
18
19
20
# File 'lib/diff_string.rb', line 11

def initialize(prefix, color)
  @prefix = prefix
  @base_color = color

  @string = ''

  @reverse = false
  @color = @base_color
  @reset_color = color.empty? ? DEFAULT_COLOR : color
end

Class Method Details

.decorate_string(prefix, color, string) ⇒ Object



62
63
64
65
66
# File 'lib/diff_string.rb', line 62

def self.decorate_string(prefix, color, string)
  decorated = DiffString.new(prefix, color)
  decorated.add(string, false)
  return decorated.to_s
end

Instance Method Details

#add(string, reverse, color = '') ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/diff_string.rb', line 24

def add(string, reverse, color = '')
  color = @reset_color if color.empty?

  if reverse && string == "\n"
    add('', true, color)
    add("\n", false)
    return
  end

  if @string.empty?() || @string.end_with?("\n")
    @string += @base_color
    @string += @prefix
    @color = @reset_color
  end

  if reverse != @reverse
    @string += reverse ? REVERSE : NOT_REVERSE
  end
  @reverse = reverse

  if color != @color
    @string += color
  end
  @color = color

  @string += string
end

#to_sObject



52
53
54
55
56
57
58
59
60
# File 'lib/diff_string.rb', line 52

def to_s()
  return '' if @string.empty?

  string = @string
  string.chomp! if string.end_with? "\n"

  suffix = @base_color.empty? ? '' : RESET
  return string + suffix + "\n"
end