|
| 1 | +require_relative './helpers' |
| 2 | +require_relative './header_generator' |
| 3 | + |
| 4 | +module AnnotateRoutes |
| 5 | + # Class to add and update annotations in routes.rb |
| 6 | + module AnnotationProcessor |
| 7 | + class << self |
| 8 | + # @param [Boolean] |
| 9 | + def update(routes_file, existing_text, options = {}) |
| 10 | + header = HeaderGenerator.generate(options) |
| 11 | + content, header_position = Helpers.strip_annotations(existing_text) |
| 12 | + new_content = annotate_routes(header, content, header_position, options) |
| 13 | + new_text = new_content.join("\n") |
| 14 | + rewrite_contents(routes_file, existing_text, new_text, options) |
| 15 | + end |
| 16 | + |
| 17 | + private |
| 18 | + |
| 19 | + def annotate_routes(header, content, header_position, options = {}) |
| 20 | + magic_comments_map, content = Helpers.extract_magic_comments_from_array(content) |
| 21 | + if %w[before top].include?(options[:position_in_routes]) |
| 22 | + header = header << '' if content.first != '' |
| 23 | + magic_comments_map << '' if magic_comments_map.any? |
| 24 | + new_content = magic_comments_map + header + content |
| 25 | + else |
| 26 | + # Ensure we have adequate trailing newlines at the end of the file to |
| 27 | + # ensure a blank line separating the content from the annotation. |
| 28 | + content << '' unless content.last == '' |
| 29 | + |
| 30 | + # We're moving something from the top of the file to the bottom, so ditch |
| 31 | + # the spacer we put in the first time around. |
| 32 | + content.shift if header_position == :before && content.first == '' |
| 33 | + |
| 34 | + new_content = magic_comments_map + content + header |
| 35 | + end |
| 36 | + |
| 37 | + # Make sure we end on a trailing newline. |
| 38 | + new_content << '' unless new_content.last == '' |
| 39 | + |
| 40 | + new_content |
| 41 | + end |
| 42 | + |
| 43 | + # @param routes_file [String] |
| 44 | + # @param existing_text [String] |
| 45 | + # @param new_text [String] |
| 46 | + # @param options [Hash] |
| 47 | + # @return [Boolean] |
| 48 | + def rewrite_contents(routes_file, existing_text, new_text, options) |
| 49 | + content_changed = existing_text != new_text |
| 50 | + frozen = options[:frozen] |
| 51 | + |
| 52 | + abort "annotate error. #{routes_file} needs to be updated, but annotate was run with `--frozen`." if content_changed && frozen |
| 53 | + |
| 54 | + if content_changed |
| 55 | + File.open(routes_file, 'wb') { |f| f.puts(new_text) } |
| 56 | + true |
| 57 | + else |
| 58 | + false |
| 59 | + end |
| 60 | + end |
| 61 | + end |
| 62 | + end |
| 63 | +end |
0 commit comments