Last active
November 20, 2019 09:53
-
-
Save ericboehs/7121c96eab1d1041b8a7000ed2418e7c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
if Rake::Task.task_defined?('webpacker:clean') | |
puts %(Task webpacker:clean has already been defined. The monkey patch located in "#{__FILE__}" can be removed.) | |
else | |
module WebPackerClean | |
def clean | |
return if !config.public_output_path.exist? || !config.public_manifest_path.exist? | |
count_to_keep = 2 | |
files_in_manifest = manifest.refresh.values.map { |f| File.join config.root_path, 'public', f } | |
files_to_be_removed = files_in_manifest.flat_map do |file_in_manifest| | |
file_prefix, file_ext = file_in_manifest.scan(/(.*)[0-9a-f]{20}(.*)/).first | |
versions_of_file = Dir.glob("#{file_prefix}*#{file_ext}").grep(/#{file_prefix}[0-9a-f]{20}#{file_ext}/) | |
versions_of_file.map do |version_of_file| | |
next if version_of_file == file_in_manifest | |
[version_of_file, File.mtime(version_of_file).utc.to_i] | |
end.compact.sort_by(&:last).reverse.drop(count_to_keep)].map(&:first) | |
end | |
files_to_be_removed.each { |f| File.delete f } | |
end | |
end | |
Webpacker::Commands.class_eval { include WebPackerClean } | |
module Webpacker | |
class Commands | |
include WebPackerClean | |
end | |
end | |
namespace :webpacker do | |
desc 'Remove old compiled webpacks' | |
task clean: ['webpacker:verify_install', :environment] do | |
Webpacker.commands.clean | |
end | |
end | |
# Run clean if the assets:clean is run | |
if Rake::Task.task_defined?('assets:clean') | |
Rake::Task['assets:clean'].enhance do | |
Rake::Task['webpacker:clean'].invoke | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I placed this file in
lib/tasks/webpacker_clean.rake
in my Rails project to backport rails/webpacker#1744.