Skip to content

Commit 8630f12

Browse files
authored
Update clean task (#2443)
1 parent cb8c079 commit 8630f12

File tree

2 files changed

+35
-11
lines changed

2 files changed

+35
-11
lines changed

lib/tasks/webpacker/clean.rake

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ require "webpacker/configuration"
44

55
namespace :webpacker do
66
desc "Remove old compiled webpacks"
7-
task :clean, [:keep] => ["webpacker:verify_install", :environment] do |_, args|
7+
task :clean, [:keep, :age] => ["webpacker:verify_install", :environment] do |_, args|
88
Webpacker.ensure_log_goes_to_stdout do
9-
Webpacker.clean(Integer(args.keep || 2))
9+
Webpacker.clean(Integer(args.keep || 2), Integer(args.age || 3600))
1010
end
1111
end
1212
end

lib/webpacker/commands.rb

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,34 @@ def initialize(webpacker)
55
@webpacker = webpacker
66
end
77

8-
def clean(count = 2)
9-
if config.public_output_path.exist? && config.public_manifest_path.exist? && versions.count > count
10-
versions.drop(count).flat_map(&:last).each do |file|
11-
File.delete(file) if File.file?(file)
12-
logger.info "Removed #{file}"
13-
end
8+
# Cleanup old assets in the compile directory. By default it will
9+
# keep the latest version, 2 backups created within the past hour.
10+
#
11+
# Examples
12+
#
13+
# To force only 1 backup to be kept, set count=1 and age=0.
14+
#
15+
# To only keep files created within the last 10 minutes, set count=0 and
16+
# age=600.
17+
#
18+
def clean(count = 2, age = 3600)
19+
if config.public_output_path.exist? && config.public_manifest_path.exist?
20+
versions
21+
.sort
22+
.reverse
23+
.each_with_index
24+
.drop_while do |(mtime, _), index|
25+
max_age = [0, Time.now - Time.at(mtime)].max
26+
max_age < age && index < count
27+
end
28+
.each do |(_, files), index|
29+
files.each do |file|
30+
if File.file?(file)
31+
File.delete(file)
32+
logger.info "Removed #{file}"
33+
end
34+
end
35+
end
1436
end
1537

1638
true
@@ -37,14 +59,16 @@ def versions
3759
manifest_config = Dir.glob("#{config.public_manifest_path}*")
3860

3961
packs = all_files - manifest_config - current_version
40-
packs.group_by { |file| File.mtime(file).utc.to_i }.sort.reverse
62+
packs.reject { |file| File.directory?(file) }.group_by { |file| File.mtime(file).utc.to_i }
4163
end
4264

4365
def current_version
44-
manifest.refresh.values.map do |value|
66+
packs = manifest.refresh.values.map do |value|
4567
next if value.is_a?(Hash)
4668

47-
File.join(config.root_path, "public", value)
69+
File.join(config.root_path, "public", "#{value}*")
4870
end.compact
71+
72+
Dir.glob(packs).uniq
4973
end
5074
end

0 commit comments

Comments
 (0)