File: manifest_utils.rb

package info (click to toggle)
ruby-sprockets 4.2.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,964 kB
  • sloc: ruby: 13,014; javascript: 157; makefile: 4
file content (48 lines) | stat: -rw-r--r-- 1,721 bytes parent folder | download | duplicates (2)
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
# frozen_string_literal: true
require 'securerandom'
require 'logger'

module Sprockets
  # Public: Manifest utilities.
  module ManifestUtils
    extend self

    MANIFEST_RE = /^\.sprockets-manifest-[0-9a-f]{32}.json$/

    # Public: Generate a new random manifest path.
    #
    # Manifests are not intended to be accessed publicly, but typically live
    # alongside public assets for convenience. To avoid being served, the
    # filename is prefixed with a "." which is usually hidden by web servers
    # like Apache. To help in other environments that may not control this,
    # a random hex string is appended to the filename to prevent people from
    # guessing the location. If directory indexes are enabled on the server,
    # all bets are off.
    #
    # Return String path.
    def generate_manifest_path
      ".sprockets-manifest-#{SecureRandom.hex(16)}.json"
    end

    # Public: Find or pick a new manifest filename for target build directory.
    #
    # dirname - String dirname
    #
    # Examples
    #
    #     find_directory_manifest("/app/public/assets")
    #     # => "/app/public/assets/.sprockets-manifest-abc123.json"
    #
    # Returns String filename.
    def find_directory_manifest(dirname, logger = Logger.new($stderr))
      entries = File.directory?(dirname) ? Dir.entries(dirname) : []
      manifest_entries = entries.select { |e| e =~ MANIFEST_RE }
      if manifest_entries.length > 1
        manifest_entries.sort!
        logger.warn("Found multiple manifests: #{manifest_entries}. Choosing the first alphabetically: #{manifest_entries.first}")
      end
      entry = manifest_entries.first || generate_manifest_path
      File.join(dirname, entry)
    end
  end
end