Module: Jekyll::Assets::Utils

Included in:
Env, Patches::CachedEnv
Defined in:
lib/jekyll/assets/utils.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.activate(gem) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/jekyll/assets/utils.rb', line 25

def self.activate(gem)
  spec = Gem::Specification
  return unless spec.find_all_by_name(gem)&.any? || \
      spec.find_by_path(gem)&.any?

  require gem
  if block_given?
    yield
  end

  true
end

.html(*a) ⇒ Object



47
48
49
50
51
52
# File 'lib/jekyll/assets/utils.rb', line 47

def self.html(*a)
  Nokogiri::HTML.parse(*a) do |c|
    c.options = Nokogiri::XML::ParseOptions::NONET | \
      Nokogiri::XML::ParseOptions::NOENT
  end
end

.html_fragment(*a) ⇒ Object



39
40
41
42
43
44
# File 'lib/jekyll/assets/utils.rb', line 39

def self.html_fragment(*a)
  Nokogiri::HTML.fragment(*a) do |c|
    c.options = Nokogiri::XML::ParseOptions::NONET | \
      Nokogiri::XML::ParseOptions::NOENT
  end
end

.javascript? { ... } ⇒ nil

– Either require exec.js, and the file or move along. –

Parameters:

  • file (String)

    the file to require.

Yields:

  • a blockof code if the require works out.

Returns:

  • (nil)


333
334
335
336
337
338
339
340
341
# File 'lib/jekyll/assets/utils.rb', line 333

def self.javascript?
  activate "execjs" do
    if block_given?
      yield
    end
  end
rescue ExecJS::RuntimeUnavailable
  false
end

.make_https(url) ⇒ Object



294
295
296
297
298
# File 'lib/jekyll/assets/utils.rb', line 294

def make_https(url)
  return if url.nil? || url == ""
  url.gsub(%r!(https?:)?//!,
    "https://")
end

.manifest_files(env) ⇒ Object



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/jekyll/assets/utils.rb', line 307

def manifest_files(env)
  manifest = env.manifest.data.values_at(*Manifest.keep_keys).map(&:to_a)
  out = manifest.flatten.each_with_object([]) do |v, a|
    path = Pathutil.new(env.in_dest_dir(v))
    a << path.to_s + ".gz" if path.exist? && !env.skip_gzip?
    a << path.to_s if path.exist?
    v = Pathutil.new(v)

    next if v.dirname == "."
    v.dirname.descend.each do |vv|
      vv = env.in_dest_dir(vv)
      unless a.include?(vv)
        a << vv
      end
    end
  end

  out
end

.new_uglifier?Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
# File 'lib/jekyll/assets/utils.rb', line 15

def self.new_uglifier?
  require "uglifier"
  modern_supported_version = "4.0.0"
  Gem::Version.new(Uglifier::VERSION) >= Gem::Version
    .new(modern_supported_version)
rescue LoadError
  return true
end

.old_sprockets?Boolean

Returns:

  • (Boolean)


8
9
10
11
12
# File 'lib/jekyll/assets/utils.rb', line 8

def self.old_sprockets?
  @old_sprockets ||= begin
    Gem::Version.new(Sprockets::VERSION) < Gem::Version.new("4.0.beta")
  end
end

.strip_secondary_content_type(str) ⇒ Object

Raises:

  • (ArgumentError)


271
272
273
274
275
# File 'lib/jekyll/assets/utils.rb', line 271

def strip_secondary_content_type(str)
  str = str.split("/")
  raise ArgumentError, "#{str.join('/')} is invalid." if str.size > 2
  File.join(str[0], str[1].rpartition(%r!\+!).last)
end

.strip_slashes(path) ⇒ Object



283
284
285
286
# File 'lib/jekyll/assets/utils.rb', line 283

def strip_slashes(path)
  return if path.nil? || path == ""
  path.gsub(%r!^/|/$!, "")
end

.xml(*a) ⇒ Object



55
56
57
58
59
# File 'lib/jekyll/assets/utils.rb', line 55

def self.xml(*a)
  Nokogiri::XML.parse(*a) do |c|
    c.options = Nokogiri::XML::ParseOptions::NONET
  end
end

Instance Method Details

#external?(args) ⇒ nil, ...

– Tells you if a url… or asset is external. –

Parameters:

Returns:

  • (nil, true, false)


156
157
158
159
160
161
162
# File 'lib/jekyll/assets/utils.rb', line 156

def external?(args)
  return true  if args.is_a?(Url)
  return false if args.is_a?(Sprockets::Asset)
  return args =~ %r!^(https?:)?//! if args.is_a?(String)
  return args[:external] if args.key?(:external)
  args[:argv1] !~ %r!^(?\!(https?:)?//)!
end

#external_asset(url, args:) ⇒ Sprockets::Asset

– Wraps around an external url and so it can be wrapped into

the rest of Jekyll-Assets with little trouble.

Parameters:

  • url (String)

Returns:



136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/jekyll/assets/utils.rb', line 136

def external_asset(url, args:)
  if args[:asset]&.key?(:type)
    url_asset(url, {
      type: args[:asset][:type],
    })

  else
    _, type = Sprockets.match_path_extname(url, Sprockets.mime_exts)
    logger.debug "no type for #{url}, assuming image/*" unless type
    url_asset(url, {
      type: type || "image/jpeg",
    })
  end
end

#find_assets_by_glob(glob) ⇒ Object



92
93
94
95
96
# File 'lib/jekyll/assets/utils.rb', line 92

def find_assets_by_glob(glob)
  glob_paths(glob).map do |v|
    find_asset!(v.to_s)
  end
end

#glob_paths(glob) ⇒ Object



99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/jekyll/assets/utils.rb', line 99

def glob_paths(glob)
  out = []

  paths.each do |sv|
    sv = Pathutil.new(sv)

    if sv.directory?
      out.concat(sv.glob(glob).to_a)
    end
  end

  out
end

#in_cache_dir(*paths) ⇒ String

Note:

configurable with ‘caching: { path: “dir_name”` }

– Lands your path inside of the cache directory. –

Returns:

  • (String)


214
215
216
217
218
219
# File 'lib/jekyll/assets/utils.rb', line 214

def in_cache_dir(*paths)
  path = Pathutil.pwd.join(strip_slashes(asset_config[:caching][:path]))
  Pathutil.new(paths.reduce(path.to_s) do |b, p|
    Jekyll.sanitized_path(b, p)
  end)
end

#in_dest_dir(*paths) ⇒ String

Note:

this is configurable with ‘:destination`

– Lands your path inside of the destination directory. –

Parameters:

  • paths (Array<String>)

    the paths.

Returns:

  • (String)


227
228
229
230
231
232
233
234
# File 'lib/jekyll/assets/utils.rb', line 227

def in_dest_dir(*paths)
  destination = strip_slashes(asset_config[:destination])

  paths.unshift(destination)
  paths = paths.flatten.compact
  Pathutil.new(jekyll
    .in_dest_dir(*paths))
end

#parse_liquid(obj, ctx:) ⇒ String

– Parses the Liquid that’s being passed, with Jekyll’s context. rubocop:disable Lint/LiteralAsCondition –

Parameters:

  • obj (String, Hash<>, Array<>)

    the liquid to parse.

Returns:

  • (String)


170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/jekyll/assets/utils.rb', line 170

def parse_liquid(obj, ctx:)
  case true
  when obj.is_a?(Hash) || obj.is_a?(Liquid::Tag::Parser)
    obj.each_key.with_object(obj) do |k, o|
      o[k] = parse_liquid(o[k], {
        ctx: ctx,
      })
    end
  when obj.is_a?(Array)
    obj.map do |v|
      parse_liquid(v, {
        ctx: ctx,
      })
    end
  when obj.is_a?(String)
    k = Digest::SHA256.hexdigest(obj)[0, 6]
    ctx.registers[:site].liquid_renderer.file("(asset:var:#{k})")
      .parse(obj).render!(ctx)
  else
    obj
  end
end

#prefix_url(user_path = nil) ⇒ String

Note:

this should only be used for urls

– rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity rubocop:disable Metrics/AbcSize Builds a url path for HTML. –

Parameters:

  • the (String)

    path.

Returns:

  • (String)


245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/jekyll/assets/utils.rb', line 245

def prefix_url(user_path = nil)
  dest = strip_slashes(asset_config[:destination])
  cdn = make_https(strip_slashes(asset_config[:cdn][:url]))
  base = strip_slashes(jekyll.config["baseurl"])
  cfg = asset_config

  path = []
  path << cdn  if Jekyll.production? && cdn
  path << base if Jekyll.dev? || !cdn || (cdn && cfg[:cdn][:baseurl])
  path << dest if Jekyll.dev? || !cdn || (cdn && cfg[:cdn][:destination])
  path << user_path unless user_path.nil? || user_path == ""

  path = File.join(path.flatten.compact)
  return path if cdn && Jekyll.production?
  "/" + path
end

#raw_precompilesObject



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
# File 'lib/jekyll/assets/utils.rb', line 62

def raw_precompiles
  asset_config[:raw_precompile].each_with_object([]) do |v, a|
    if v.is_a?(Hash)
      dst, src = in_dest_dir.join(v[:dst]).tap(&:mkdir_p), v[:src]
      glob_paths(src).each do |sv|
        a << {
          src: sv,
          full_dst: dst.join(sv.basename),
          dst: dst,
        }
      end
    else
      glob_paths(v).each do |p|
        next unless p

        dst = strip_paths(p)
        dst = in_dest_dir(dst)
        dst.parent.mkdir_p

        a << {
          src: p,
          full_dst: dst,
          dst: dst,
        }
      end
    end
  end
end

#strip_paths(path) ⇒ String

– Strips most source paths from the given path path. rubocop:enable Lint/LiteralAsCondition –

Parameters:

  • path (String)

    the path to strip.

Returns:

  • (String)


199
200
201
202
203
204
205
206
207
# File 'lib/jekyll/assets/utils.rb', line 199

def strip_paths(path)
  paths.map do |v|
    if path.start_with?(v)
      return path.sub(v + "/", "")
    end
  end

  path
end

#url_asset(url, type:) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/jekyll/assets/utils.rb', line 114

def url_asset(url, type:)
  name = File.basename(url)

  Url.new(*[Utils.old_sprockets? ? self : nil, {
    name: name,
    filename: url,
    content_type: type,
    load_path: File.dirname(url),
    id: Digest::SHA256.hexdigest(url),
    logical_path: name,
    metadata: {},
    source: "",
    uri: url,
  }].compact)
end