aboutsummaryrefslogtreecommitdiffstats
path: root/guides/rails_guides/generator.rb
blob: b0ddb0e7e07d2f3dd003ec6f41a93d59d5bb1ca5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# frozen_string_literal: true

require "set"
require "fileutils"

require "active_support/core_ext/string/output_safety"
require "active_support/core_ext/object/blank"
require "action_controller"
require "action_view"

require "rails_guides/markdown"
require "rails_guides/indexer"
require "rails_guides/helpers"
require "rails_guides/levenshtein"

module RailsGuides
  class Generator
    GUIDES_RE = /\.(?:erb|md)\z/

    def initialize(edge:, version:, all:, only:, kindle:, language:, direction: "ltr")
      @edge      = edge
      @version   = version
      @all       = all
      @only      = only
      @kindle    = kindle
      @language  = language
      @direction = direction

      if @kindle
        check_for_kindlegen
        register_kindle_mime_types
      end

      initialize_dirs
      create_output_dir_if_needed
      initialize_markdown_renderer
    end

    def generate
      generate_guides
      copy_assets
      generate_mobi if @kindle
    end

    private

      def register_kindle_mime_types
        Mime::Type.register_alias("application/xml", :opf, %w(opf))
        Mime::Type.register_alias("application/xml", :ncx, %w(ncx))
      end

      def check_for_kindlegen
        if `which kindlegen`.blank?
          raise "Can't create a kindle version without `kindlegen`."
        end
      end

      def generate_mobi
        require "rails_guides/kindle"
        out = "#{@output_dir}/kindlegen.out"
        Kindle.generate(@output_dir, mobi, out)
        puts "(kindlegen log at #{out})."
      end

      def mobi
        mobi = +"ruby_on_rails_guides_#{@version || @edge[0, 7]}"
        mobi << ".#{@language}" if @language
        mobi << ".mobi"
      end

      def initialize_dirs
        @guides_dir = File.expand_path("..", __dir__)

        @source_dir  = "#{@guides_dir}/source"
        @source_dir += "/#{@language}" if @language

        @output_dir  = "#{@guides_dir}/output"
        @output_dir += "/kindle"       if @kindle
        @output_dir += "/#{@language}" if @language
      end

      def create_output_dir_if_needed
        FileUtils.mkdir_p(@output_dir)
      end

      def initialize_markdown_renderer
        Markdown::Renderer.edge    = @edge
        Markdown::Renderer.version = @version
      end

      def generate_guides
        guides_to_generate.each do |guide|
          output_file = output_file_for(guide)
          generate_guide(guide, output_file) if generate?(guide, output_file)
        end
      end

      def guides_to_generate
        guides = Dir.entries(@source_dir).grep(GUIDES_RE)

        if @kindle
          Dir.entries("#{@source_dir}/kindle").grep(GUIDES_RE).map do |entry|
            next if entry == "KINDLE.md"
            guides << "kindle/#{entry}"
          end
        end

        @only ? select_only(guides) : guides
      end

      def select_only(guides)
        prefixes = @only.split(",").map(&:strip)
        guides.select do |guide|
          guide.start_with?("kindle", *prefixes)
        end
      end

      def copy_assets
        FileUtils.cp_r(Dir.glob("#{@guides_dir}/assets/*"), @output_dir)

        if @direction == "rtl"
          overwrite_css_with_right_to_left_direction
        end
      end

      def overwrite_css_with_right_to_left_direction
        FileUtils.mv("#{@output_dir}/stylesheets/main.rtl.css", "#{@output_dir}/stylesheets/main.css")
      end

      def output_file_for(guide)
        if guide.end_with?(".md")
          guide.sub(/md\z/, "html")
        else
          guide.sub(/\.erb\z/, "")
        end
      end

      def output_path_for(output_file)
        File.join(@output_dir, File.basename(output_file))
      end

      def generate?(source_file, output_file)
        fin  = File.join(@source_dir, source_file)
        fout = output_path_for(output_file)
        @all || !File.exist?(fout) || File.mtime(fout) < File.mtime(fin)
      end

      def generate_guide(guide, output_file)
        output_path = output_path_for(output_file)
        puts "Generating #{guide} as #{output_file}"
        layout = @kindle ? "kindle/layout" : "layout"

        view = ActionView::Base.with_view_paths(
          [@source_dir],
          edge:     @edge,
          version:  @version,
          mobi:     "kindle/#{mobi}",
          language: @language
        )
        view.extend(Helpers)

        if guide =~ /\.(\w+)\.erb$/
          return if %w[_license _welcome layout].include?($`)

          # Generate the special pages like the home.
          # Passing a template handler in the template name is deprecated. So pass the file name without the extension.
          result = view.render(layout: layout, formats: [$1], file: $`)
        else
          body = File.read("#{@source_dir}/#{guide}")
          result = RailsGuides::Markdown.new(
            view:    view,
            layout:  layout,
            edge:    @edge,
            version: @version
          ).render(body)

          warn_about_broken_links(result)
        end

        File.open(output_path, "w") do |f|
          f.write(result)
        end
      end

      def warn_about_broken_links(html)
        anchors = extract_anchors(html)
        check_fragment_identifiers(html, anchors)
      end

      def extract_anchors(html)
        # Markdown generates headers with IDs computed from titles.
        anchors = Set.new
        html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor|
          if anchors.member?(anchor)
            puts "*** DUPLICATE ID: #{anchor}, please make sure that there're no headings with the same name at the same level."
          else
            anchors << anchor
          end
        end

        # Footnotes.
        anchors += Set.new(html.scan(/<p\s+class="footnote"\s+id="([^"]+)/).flatten)
        anchors += Set.new(html.scan(/<sup\s+class="footnote"\s+id="([^"]+)/).flatten)
        anchors
      end

      def check_fragment_identifiers(html, anchors)
        html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier|
          next if fragment_identifier == "mainCol" # in layout, jumps to some DIV
          unless anchors.member?(CGI.unescape(fragment_identifier))
            guess = anchors.min { |a, b|
              Levenshtein.distance(fragment_identifier, a) <=> Levenshtein.distance(fragment_identifier, b)
            }
            puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}."
          end
        end
      end
  end
end