Class: CopyrightHeader::Header

Inherits:
Object
  • Object
show all
Defined in:
lib/copyright_header/parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(file, config) ⇒ Header

Returns a new instance of Header.


68
69
70
71
72
# File 'lib/copyright_header/parser.rb', line 68

def initialize(file, config)
  @file = file
  @contents = File.read(@file)
  @config = config
end

Instance Method Details

#add(license) ⇒ Object


78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# 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/)
    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) ⇒ Object


74
75
76
# 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) ⇒ Boolean

Returns:

  • (Boolean)

132
133
134
# 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) ⇒ Object


118
119
120
121
122
123
124
125
126
127
128
129
130
# 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