-
Notifications
You must be signed in to change notification settings - Fork 0
/
scratch_s3_prune
executable file
·74 lines (60 loc) · 1.52 KB
/
scratch_s3_prune
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env ruby
require 'aws-sdk'
require 'userinput'
##
# Pruner checks for scratch files and prunes them
class Pruner
def client
@client ||= Aws::S3::Client.new
end
def prune!
sorted_folders.each do |hash, files|
print_folder(hash, files)
next unless prompt.ask
delete_folder(files)
end
end
def print_folder(hash, files)
puts "#{hash}/"
files.map do |file, timestamp|
puts " #{timestamp.strftime('%Y/%m/%d')} #{url(file)}"
end
end
def prompt
@prompt ||= UserInput::Boolean.new(
message: 'Do you want to prune this folder',
default: 'n'
)
end
def delete_folder(files)
puts "Pruning #{files.size} files"
resp = client.delete_objects(
bucket: bucket,
delete: {
objects: files.map { |key, _| { key: key } }
}
)
raise("Delete failed: #{resp.errors}") unless resp.errors.empty?
end
def url(file)
"#{hostname}/#{file}"
end
def bucket
@bucket ||= ENV['SCRATCH_BUCKET'] || raise('SCRATCH_BUCKET not set')
end
def hostname
@hostname ||= ENV['SCRATCH_HOSTNAME'] || raise('SCRATCH_HOSTNAME not set')
end
def all_objects
@all_objects ||= client.list_objects(bucket: bucket).flat_map do |resp|
resp.contents.map { |x| [x.key, x.last_modified] }
end
end
def all_folders
@all_folders ||= all_objects.group_by { |key, _| key.split('/').first }
end
def sorted_folders
@sorted_folders ||= all_folders.to_a.sort_by { |x| x.last.map(&:last).max }
end
end
Pruner.new.prune!