Class: Middleman::Builder

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Contracts
Defined in:
middleman-core/lib/middleman-core/builder.rb

Constant Summary collapse

SORT_ORDER =

Sort order, images, fonts, js/css and finally everything else.

%w[.png .jpeg .jpg .gif .bmp .svg .svgz .webp .ico .woff .woff2 .otf .ttf .eot .js .mjs .css].freeze
SERIALIZED_DEP =

Try to output a resource and capture errors.

{ self_vertex: ::Middleman::Dependencies::Vertex::SERIALIZED_VERTEX, depends_on: ImmutableSetOf[::Middleman::Dependencies::Vertex::SERIALIZED_VERTEX] }.freeze

Constants included from Contracts

Contracts::ImmutableSetOf, Contracts::ImmutableSortedSetOf, Contracts::OldResourceList, Contracts::PATH_MATCHER, Contracts::ResourceList, Contracts::VectorOf

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Contracts

#Contract

Constructor Details

#initialize(app, options_hash = ::Middleman::EMPTY_HASH) ⇒ Builder

Create a new Builder instance.


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'middleman-core/lib/middleman-core/builder.rb', line 31

def initialize(app, options_hash = ::Middleman::EMPTY_HASH)
  @app = app
  @source_dir = Pathname(File.join(@app.root, @app.config[:source]))
  @build_dir = Pathname(@app.config[:build_dir])

  raise ":build_dir (#{@build_dir}) cannot be a parent of :source_dir (#{@source_dir})" if /\A[.\/]+\Z/.match?(@build_dir.expand_path.relative_path_from(@source_dir).to_s)

  @glob = options_hash.fetch(:glob)
  @parallel = options_hash.fetch(:parallel, true)
  @only_changed = options_hash.fetch(:only_changed, false)
  @missing_and_changed = options_hash.fetch(:missing_and_changed, false)
  @track_dependencies = options_hash.fetch(:track_dependencies, false)
  @visualize_graph = @track_dependencies && options_hash.fetch(:visualize_graph, false)
  @dry_run = options_hash.fetch(:dry_run)
  @cleaning = !@dry_run && options_hash.fetch(:clean)

  @callbacks = ::Middleman::CallbackManager.new
  @callbacks.install_methods!(self, [:on_build_event])
end

Instance Attribute Details

#appObject (readonly)

Make app & events available to after_build callbacks.


17
18
19
# File 'middleman-core/lib/middleman-core/builder.rb', line 17

def app
  @app
end

#eventsObject (readonly)

Make app & events available to after_build callbacks.


17
18
19
# File 'middleman-core/lib/middleman-core/builder.rb', line 17

def events
  @events
end

#thorObject

Reference to the Thor class.


20
21
22
# File 'middleman-core/lib/middleman-core/builder.rb', line 20

def thor
  @thor
end

Instance Method Details

#Any

This method returns an undefined value.

Get a list of all the paths in the destination folder and save them for comparison against the files we build in this cycle


391
# File 'middleman-core/lib/middleman-core/builder.rb', line 391

Contract Any

#binary_encode(string) ⇒ Object


429
430
431
432
# File 'middleman-core/lib/middleman-core/builder.rb', line 429

def binary_encode(string)
  string.force_encoding('ascii-8bit') if string.respond_to?(:force_encoding)
  string
end

#BoolBoolean

Run the build phase.


53
# File 'middleman-core/lib/middleman-core/builder.rb', line 53

Contract Bool

#clean!Object


417
418
419
420
421
422
423
424
425
426
# File 'middleman-core/lib/middleman-core/builder.rb', line 417

def clean!
  to_remove = @to_clean.reject do |f|
    app.config[:skip_build_clean].call(f.to_s)
  end

  to_remove.each do |f|
    FileUtils.rm(f)
    trigger(:deleted, f)
  end
end

#export_file!(output_file, source, binary = false) ⇒ Object


298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'middleman-core/lib/middleman-core/builder.rb', line 298

def export_file!(output_file, source, binary = false)
  return if @dry_run

  ::Middleman::Util.instrument 'write_file', output_file: output_file do
    source = write_tempfile(output_file, source.to_s) if source.is_a? String

    method, source_path = if source.is_a? Tempfile
                            [::FileUtils.method(:mv), source.path]
                          else
                            [::FileUtils.method(:cp), source.to_s]
                          end

    mode = which_mode(output_file, source_path, binary)

    if %i[created updated].include?(mode)
      ::FileUtils.mkdir_p(output_file.dirname)
      method.call(source_path, output_file.to_s)
      ::File.chmod(0o644, output_file.to_s)
    end

    source.unlink if source.is_a? Tempfile

    trigger(mode, output_file)
  end
end

#output_filesObject


169
170
171
172
173
174
175
176
177
178
# File 'middleman-core/lib/middleman-core/builder.rb', line 169

def output_files
  logger.debug '== Building files'

  non_css_resources = @app.sitemap.without_ignored - @app.sitemap.by_extension('.css')

  resources = non_css_resources
              .sort_by { |resource| SORT_ORDER.index(resource.ext) || 100 }

  output_resources(resources.to_a)
end

#output_resource(resource, serialize_deps = false) ⇒ Object


329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'middleman-core/lib/middleman-core/builder.rb', line 329

def output_resource(resource, serialize_deps = false)
  ::Middleman::Util.instrument 'builder.output.resource', path: File.basename(resource.destination_path) do
    begin
      output_file = @build_dir + resource.destination_path.gsub('%20', ' ')

      if @track_dependencies && (@only_changed || @missing_and_changed)
        invalidated_resource = @graph.invalidates_resource?(resource)
        if @only_changed && !invalidated_resource
          trigger(:skipped, output_file)
          return [output_file, nil]
        elsif @missing_and_changed && File.exist?(output_file) && !invalidated_resource
          trigger(:skipped, output_file)
          return [output_file, nil]
        end
      elsif @glob
        did_match = if defined?(::File::FNM_EXTGLOB)
                      File.fnmatch(@glob, resource.destination_path, ::File::FNM_EXTGLOB)
                    else
                      File.fnmatch(@glob, resource.destination_path)
                    end

        unless did_match
          trigger(:skipped, output_file)
          return [output_file, nil]
        end
      end

      edge = nil

      if resource.binary? || resource.static_file?
        export_file!(output_file, resource.file_descriptor[:full_path], true)
      else
        content = resource.render({}, {})

        self_vertex = ::Middleman::Dependencies::FileVertex.from_resource(resource)

        edge = if serialize_deps
                 {
                   self_vertex: self_vertex.serialize,
                   depends_on: resource.vertices.map(&:serialize)
                 }
               else
                 ::Middleman::Dependencies::Edge.new(
                   self_vertex,
                   resource.vertices << self_vertex
                 )
               end

        export_file!(output_file, binary_encode(content))
      end
    rescue StandardError => e
      trigger(:error, output_file, "#{e}\n#{e.backtrace.join("\n")}")
      return false
    end

    [output_file, edge]
  end
end

#output_resources(resources) ⇒ Object


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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'middleman-core/lib/middleman-core/builder.rb', line 181

def output_resources(resources)
  res_count = resources.count

  return resources if res_count.zero?

  results = if @parallel
              processes = ::Parallel.processor_count
              processes = processes < res_count ? processes : res_count
              min_parts = res_count / processes
              remainder = res_count % processes
              offset = 0
              ranges = []

              while offset < res_count
                end_r = offset + min_parts

                if remainder.positive?
                  end_r += 1
                  remainder -= 1
                end

                range = offset...end_r
                offset = end_r
                ranges << range
              end

              outputs = Parallel.map(ranges, in_processes: processes) do |r|
                resources[r].map! { |res| output_resource(res, true) }
              end

              outputs.flatten!(1)
              outputs.map do |pair|
                if pair == false
                  false
                else
                  output_file = pair[0]

                  serialized_dep = pair[1]

                  edge = if serialized_dep.nil?
                           nil
                         else
                           self_vertex = ::Middleman::Dependencies.deserialize_vertex(@app, serialized_dep[:self_vertex])
                           depends_on = serialized_dep[:depends_on].map { |d| ::Middleman::Dependencies.deserialize_vertex(@app, d) }

                           ::Middleman::Dependencies::Edge.new(
                             self_vertex,
                             depends_on << self_vertex
                           )
                         end

                  [output_file, edge]
                end
              end
            else
              resources.map(&method(:output_resource))
            end

  without_errors = results.reject { |r| r == false }

  @has_error = results.size > without_errors.size

  if @cleaning && !@has_error
    results.each do |r|
      p = r[0]
      next unless p.exist?

      # handle UTF-8-MAC filename on MacOS
      cleaned_name = if RUBY_PLATFORM.match?(/darwin/)
                       p.to_s.encode('UTF-8', 'UTF-8-MAC')
                     else
                       p
                     end

      @to_clean.delete(Pathname(cleaned_name))
    end
  end

  without_errors
end

#Pathname

This method returns an undefined value.

Actually export the file.


266
# File 'middleman-core/lib/middleman-core/builder.rb', line 266

Contract Pathname, String, Bool => Symbol

#prerender_cssObject


146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'middleman-core/lib/middleman-core/builder.rb', line 146

def prerender_css
  logger.debug '== Prerendering CSS'

  resources = @app.sitemap.by_extension('.css').to_a

  css_files = ::Middleman::Util.instrument 'builder.prerender.output' do
    output_resources(resources)
  end

  ::Middleman::Util.instrument 'builder.prerender.check-files' do
    # Double-check for compass sprites
    unless @app.files.find_new_files!.empty?
      logger.debug '== Checking for Compass sprites'
      @app.sitemap.ensure_resource_list_updated!
    end
  end

  css_files
end

#queue_current_pathsObject


392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'middleman-core/lib/middleman-core/builder.rb', line 392

def queue_current_paths
  @to_clean = []

  return unless File.exist?(@app.config[:build_dir])

  paths = ::Middleman::Util.all_files_under(@app.config[:build_dir]).map do |path|
    Pathname(path)
  end

  @to_clean = paths.select do |path|
    path.realpath.relative_path_from(@build_dir.realpath).to_s !~ /\/\./ || path.to_s =~ /\.(htaccess|htpasswd)/
  end

  # handle UTF-8-MAC filename on MacOS
  @to_clean = @to_clean.map do |path|
    if RUBY_PLATFORM.match?(/darwin/)
      Pathname(path.to_s.encode('UTF-8', 'UTF-8-MAC'))
    else
      Pathname(path)
    end
  end
end

#run!Object


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
# File 'middleman-core/lib/middleman-core/builder.rb', line 54

def run!
  @has_error = false
  @events = {}

  if @track_dependencies
    begin
      ::Middleman::Util.instrument 'dependencies.load_and_deserialize' do
        @graph = ::Middleman::Dependencies.load_and_deserialize(@app)
      end
    rescue ::Middleman::Dependencies::InvalidDepsYAML
      logger.error 'dep.yml was corrupt. Dependency graph must be rebuilt.'
      @graph = ::Middleman::Dependencies::Graph.new
      @only_changed = @missing_and_changed = false
    rescue ::Middleman::Dependencies::ChangedDepth
      logger.error ':data_collection_depth changed. Dependency graph must be rebuilt.'
      @graph = ::Middleman::Dependencies::Graph.new
      @only_changed = @missing_and_changed = false
    rescue ::Middleman::Dependencies::InvalidatedGlobalFiles => e
      changed = e.invalidated.join(', ')
      logger.error "Some global files (#{changed}) have changed since last run. Dependency graph must be rebuilt."

      @graph = ::Middleman::Dependencies::Graph.new
      @only_changed = @missing_and_changed = false
    end
  end

  if @only_changed || @missing_and_changed
    @invalidated_files = @graph.invalidated

    if @invalidated_files.empty?
      logger.debug '== No invalidated files'
    else
      @invalidated_files.each do |v|
        logger.debug "== Invalidated: #{v}"
      end
    end
  end

  ::Middleman::Util.instrument 'builder.before' do
    @app.execute_callbacks(:before_build, [self])
  end

  ::Middleman::Util.instrument 'builder.queue' do
    queue_current_paths if @cleaning
  end

  ::Middleman::Util.instrument 'builder.prerender' do
    prerender_css.tap do |resources|
      if @track_dependencies
        resources.each do |r|
          @graph.add_edge_set(r[1]) unless r[1].nil?
        end
      end
    end
  end

  ::Middleman::Profiling.start

  ::Middleman::Util.instrument 'builder.output' do
    output_files.tap do |resources|
      if @track_dependencies
        resources.each do |r|
          @graph.add_edge_set(r[1]) unless r[1].nil?
        end
      end
    end
  end

  ::Middleman::Profiling.report('build')

  unless @has_error
    partial_update_with_no_changes = (@only_changed || @missing_and_changed) && @invalidated_files.empty?

    ::Middleman::Dependencies.serialize_and_save(@app, @graph) if @track_dependencies && !partial_update_with_no_changes

    ::Middleman::Dependencies.visualize_graph(@app, @graph) if @track_dependencies && @visualize_graph

    ::Middleman::Util.instrument 'builder.clean' do
      clean! if @cleaning
    end

    ::Middleman::Util.instrument 'builder.after' do
      @app.execute_callbacks(:after_build, [self])
    end
  end

  !@has_error
end

#trigger(event_type, target, extra = nil) ⇒ Object


435
436
437
438
439
440
# File 'middleman-core/lib/middleman-core/builder.rb', line 435

def trigger(event_type, target, extra = nil)
  @events[event_type] ||= []
  @events[event_type] << target

  execute_callbacks(:on_build_event, [event_type, target, extra])
end

#which_mode(output_file, source, binary) ⇒ Object


267
268
269
270
271
272
273
274
275
# File 'middleman-core/lib/middleman-core/builder.rb', line 267

def which_mode(output_file, source, binary)
  if !output_file.exist?
    :created
  elsif FileUtils.compare_file(source.to_s, output_file.to_s)
    binary ? :skipped : :identical
  else
    :updated
  end
end

#write_tempfile(output_file, contents) ⇒ Object


282
283
284
285
286
287
288
289
290
291
# File 'middleman-core/lib/middleman-core/builder.rb', line 282

def write_tempfile(output_file, contents)
  file = Tempfile.new([
                        File.basename(output_file),
                        File.extname(output_file)
                      ])
  file.binmode
  file.write(contents)
  file.close
  file
end