module TextFileMutator def self.has_multiple_content_before?(file_content, content, before) res = file_content =~ /(#{content}\s*#{content})\s*#{before}/ !res.nil? end def self.has_content_before?(file_content, content, before) res = file_content =~ /(#{content})\s*#{before}/ !res.nil? end def self.has_multiple_content_after?(file_content, content, after) res = file_content =~ /#{after}\s*(#{content}\s*#{content})/ !res.nil? end def self.has_content_after?(file_content, content, after) res = file_content =~ /#{after}\s*(#{content})/ !res.nil? end def self.insert_before(file, line, txt_before, exist_check=true) content = File.read(file) if exist_check return if has_content_before?(content, txt_before, line) end gsub_content_file content, file, /(#{Regexp.escape(line)})/ do |match| "#{txt_before}\n#{match}" end end def self.insert_after(file, line, txt_after, exist_check=true) content = File.read(file) if exist_check return if has_content_after?(content, txt_after, line) end gsub_content_file file, /(#{Regexp.escape(line)})/ do |match| "#{match}\n#{txt_after}" end end def self.remove_duplicate_lines(file) content = File.read(file) content.gsub!(/^(.*)(\r?\n\1)+$/, '\1') File.open(path, 'wb') { |file| file.write(content) } end def self.comment_gem_config(file, line) gsub_file file, /^\s*[^#]\s*config.gem.+'#{Regexp.escape(line)}'$/ do |match| "# " + "#{match}" end end def self.remove_require(file, line) gsub_file file, /^\s*require\s+'#{Regexp.escape(line)}'$/ do |match| "" end end def self.comment_line(file, line) gsub_file file, /^\s*[^#]\s*(#{Regexp.escape(line)}$)/i do |match| "# " + "#{match}" end end def self.remove_content(file, line) gsub_file file, /(#{Regexp.escape(line)})/i do |match| "" end end def self.remove_line(file, line) gsub_file file, /^.*#{Regexp.escape(line)}.*$)/i do |match| "" end end protected def self.gsub_content_file(content, path, regexp, *args, &block) content.gsub!(regexp, *args, &block) File.open(path, 'wb') { |file| file.write(content) } end def self.gsub_file(path, regexp, *args, &block) content = File.read(path).gsub(regexp, *args, &block) File.open(path, 'wb') { |file| file.write(content) } end end