Sha256: b2a20dc0791eb7bfc76092569753d039aebef083f92073d7e7a546bcaa753719

Contents?: true

Size: 1.72 KB

Versions: 15

Compression:

Stored size: 1.72 KB

Contents

require "propshaft/asset"

class Propshaft::OutputPath
  attr_reader :path, :manifest

  def initialize(path, manifest)
    @path, @manifest = path, manifest
  end

  def clean(count, age)
    asset_versions = files.group_by { |_, attrs| attrs[:logical_path] }
    asset_versions.each do |logical_path, versions|
      current = manifest[logical_path]

      versions
        .reject { |path, _| current && path == current }
        .sort_by { |_, attrs| attrs[:mtime] }
        .reverse
        .each_with_index
        .drop_while { |(_, attrs), index| fresh_version_within_limit(attrs[:mtime], count, expires_at: age, limit: index) }
        .each { |(path, _), _| remove(path) }
    end
  end

  def files
    Hash.new.tap do |files|
      all_files_from_tree(path).each do |file|
        digested_path = file.relative_path_from(path)
        logical_path, digest = extract_path_and_digest(digested_path)

        files[digested_path.to_s] = {
          logical_path: logical_path.to_s,
          digest: digest,
          mtime: File.mtime(file)
        }
      end
    end
  end

  private
    def fresh_version_within_limit(mtime, count, expires_at:, limit:)
      modified_at = [ 0, Time.now - mtime ].max
      modified_at < expires_at || limit < count
    end
  
    def remove(path)
      FileUtils.rm(@path.join(path))
      Propshaft.logger.info "Removed #{path}"
    end

    def all_files_from_tree(path)
      path.children.flat_map { |child| child.directory? ? all_files_from_tree(child) : child }
    end

    def extract_path_and_digest(digested_path)
      digest = digested_path.to_s[/-([0-9a-f]{7,128})\.(?!digested)[^.]+\z/, 1]
      path = digest ? digested_path.sub("-#{digest}", "") : digested_path

      [path, digest]
    end
end

Version data entries

15 entries across 15 versions & 2 rubygems

Version Path
propshaft-0.9.1 lib/propshaft/output_path.rb
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/propshaft-0.6.4/lib/propshaft/output_path.rb
propshaft-0.8.0 lib/propshaft/output_path.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/propshaft-0.6.4/lib/propshaft/output_path.rb
propshaft-0.6.4 lib/propshaft/output_path.rb
propshaft-0.6.3 lib/propshaft/output_path.rb
propshaft-0.6.2 lib/propshaft/output_path.rb
propshaft-0.6.1 lib/propshaft/output_path.rb
propshaft-0.6.0 lib/propshaft/output_path.rb
propshaft-0.5.0 lib/propshaft/output_path.rb
propshaft-0.4.4 lib/propshaft/output_path.rb
propshaft-0.4.3 lib/propshaft/output_path.rb
propshaft-0.4.2 lib/propshaft/output_path.rb
propshaft-0.4.1 lib/propshaft/output_path.rb
propshaft-0.4.0 lib/propshaft/output_path.rb