|
3 | 3 | module Copyright
|
4 | 4 | module_function
|
5 | 5 |
|
6 |
| - def update(files, options = {}) |
7 |
| - style = options[:style] || '//' |
8 |
| - prefix = options[:prefix] || nil |
9 |
| - |
10 |
| - notice_lines = notice.split(/\n/).map do |line| |
11 |
| - "#{style} #{line}".rstrip + "\n" |
12 |
| - end |
13 |
| - notice_lines = Array(prefix) + notice_lines |
14 |
| - notice = notice_lines.join('') |
| 6 | + def update(files, style: '//', prefix: nil) |
| 7 | + @comment_characters = style |
| 8 | + @prefix = prefix |
15 | 9 |
|
16 | 10 | files.each do |file|
|
17 | 11 | lines = IO.readlines(file)
|
18 | 12 |
|
19 | 13 | index = -1
|
20 | 14 | lines.any? do |line|
|
21 | 15 | done = true
|
22 |
| - if (line.index(style).zero?) || |
23 |
| - (notice_lines[index + 1] && (line.index(notice_lines[index + 1]).zero?)) |
| 16 | + if starts_with_comment_character?(line) || valid_copyright_notice_line?(line, index) |
24 | 17 | index += 1
|
25 | 18 | done = false
|
26 | 19 | end
|
27 | 20 | done
|
28 | 21 | end
|
29 | 22 |
|
30 | 23 | if index == -1
|
31 |
| - write_update_notice(file, lines, notice) |
| 24 | + write_update_notice(file, lines, copyright_notice) |
32 | 25 | else
|
33 | 26 | current = lines.shift(index + 1).join('')
|
34 |
| - if current != notice |
35 |
| - write_update_notice(file, lines, notice) |
| 27 | + if current != copyright_notice |
| 28 | + write_update_notice(file, lines, copyright_notice) |
36 | 29 | end
|
37 | 30 | end
|
38 | 31 | end
|
39 | 32 | end
|
40 | 33 |
|
| 34 | + def starts_with_comment_character?(line) |
| 35 | + line.index(@comment_characters)&.zero? |
| 36 | + end |
| 37 | + |
| 38 | + def valid_copyright_notice_line?(line, index) |
| 39 | + copyright_notice_lines[index + 1] && |
| 40 | + line.index(copyright_notice_lines[index + 1])&.zero? |
| 41 | + end |
| 42 | + |
| 43 | + def copyright_notice |
| 44 | + copyright_notice_lines.join('') |
| 45 | + end |
| 46 | + |
| 47 | + def copyright_notice_lines |
| 48 | + @copyright_notice_lines ||= Array(@prefix) + commented_notice_lines |
| 49 | + end |
| 50 | + |
| 51 | + def commented_notice_lines |
| 52 | + notice_lines.map do |line| |
| 53 | + "#{@comment_characters} #{line}".rstrip + "\n" |
| 54 | + end |
| 55 | + end |
| 56 | + |
| 57 | + def notice_lines |
| 58 | + notice.split(/\n/) |
| 59 | + end |
| 60 | + |
41 | 61 | def write_update_notice(file, lines, notice)
|
42 | 62 | puts "Adding notice to #{file}"
|
43 | 63 | File.open(file, 'w') do |f|
|
|
0 commit comments