Class: Freyia::Automations::InjectIntoFile

Inherits:
EmptyDirectory show all
Defined in:
lib/freyia/automations/inject_into_file.rb

Overview

:nodoc:

Instance Attribute Summary collapse

Attributes inherited from EmptyDirectory

#base, #config, #destination, #given_destination, #relative_destination

Instance Method Summary collapse

Methods inherited from EmptyDirectory

#exists?

Constructor Details

#initialize(base, destination, data, config) ⇒ InjectIntoFile

Returns a new instance of InjectIntoFile.



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/freyia/automations/inject_into_file.rb', line 76

def initialize(base, destination, data, config)
  super(base, destination, { verbose: true }.merge(config))

  @behavior, @flag = if @config.key?(:after)
                       [:after, @config.delete(:after)]
                     else
                       [:before, @config.delete(:before)]
                     end

  @replacement = data.is_a?(Proc) ? data.() : data
  @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp)
  @error_on_no_change = @config.fetch(:error_on_no_change, false)
end

Instance Attribute Details

#behaviorObject (readonly)

Returns the value of attribute behavior.



74
75
76
# File 'lib/freyia/automations/inject_into_file.rb', line 74

def behavior
  @behavior
end

#flagObject (readonly)

Returns the value of attribute flag.



74
75
76
# File 'lib/freyia/automations/inject_into_file.rb', line 74

def flag
  @flag
end

#replacementObject (readonly)

Returns the value of attribute replacement.



74
75
76
# File 'lib/freyia/automations/inject_into_file.rb', line 74

def replacement
  @replacement
end

Instance Method Details

#callObject

rubocop:todo Metrics



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/freyia/automations/inject_into_file.rb', line 90

def call # rubocop:todo Metrics
  content = if @behavior == :after
              "\\0#{replacement}"
            else
              "#{replacement}\\0"
            end

  if exists?
    if replace!(%r{#{flag}}, content, config[:force])
      say_status(:invoke)
    elsif @error_on_no_change
      raise Freyia::Error, "The content of #{destination} did not change"
    elsif replacement_present?
      say_status(:unchanged, color: :blue)
    else
      say_status(:unchanged, warning: WARNINGS[:unchanged_no_flag], color: :red)
    end
  else
    raise Freyia::Error, "The file #{destination} does not appear to exist" unless pretend?
  end
end

#revoke!Object



112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/freyia/automations/inject_into_file.rb', line 112

def revoke!
  say_status :revoke

  regexp = if @behavior == :after
             content = '\1\2'
             %r{(#{flag})(.*)(#{Regexp.escape(replacement)})}m
           else
             content = '\2\3'
             %r{(#{Regexp.escape(replacement)})(.*)(#{flag})}m
           end

  replace!(regexp, content, true)
end