class CopyrightHeader::Header
Public Class Methods
new(file, config)
click to toggle source
# File lib/copyright_header/parser.rb, line 68 def initialize(file, config) @file = file @contents = File.read(@file) @config = config end
Public Instance Methods
add(license)
click to toggle source
# File lib/copyright_header/parser.rb, line 78 def add(license) if has_copyright? raise ExistingLicenseException.new("detected existing license") end copyright = self.format(license) if copyright.nil? STDERR.puts "Copyright is nil" return nil end text = "" if @config.has_key?(:after) && @config[:after].instance_of?(Array) copyright_written = false lines = @contents.split(/\n/, -1) head = lines.shift(10) while(head.size > 0) line = head.shift text += line + "\n" @config[:after].each do |regex| pattern = Regexp.new(regex) if pattern.match(line) text += copyright copyright_written = true break end end end if copyright_written text += lines.join("\n") else text = copyright + text + lines.join("\n") end else # Simply prepend text text = copyright + @contents end return text end
format(license)
click to toggle source
# File lib/copyright_header/parser.rb, line 74 def format(license) license.format(@config[:comment]['open'], @config[:comment]['close'], @config[:comment]['prefix']) end
has_copyright?(lines = 10)
click to toggle source
# File lib/copyright_header/parser.rb, line 132 def has_copyright?(lines = 10) @contents.split(/\n/)[0..lines].select { |line| line =~ /(?!class\s+)([Cc]opyright|[Ll]icense)\s/ }.length > 0 end
remove(license)
click to toggle source
# File lib/copyright_header/parser.rb, line 118 def remove(license) if has_copyright? text = self.format(license) # Due to editors messing with whitespace, we'll make this more of a fuzzy match and use \s to match whitespace pattern = Regexp.escape(text).gsub(/\\[ n]/, '\s*').gsub(/\\s*$/, '\s') exp = Regexp.new(pattern) @contents.gsub!(exp, '') @contents else STDERR.puts "SKIP #{@file}; copyright not detected" return nil end end