68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
# File 'lib/cloudinary/static.rb', line 68
def self.sync(options={})
options = options.clone
delete_missing = options.delete(:delete_missing)
metadata = self.metadata
found_paths = Set.new
found_public_ids = Set.new
metadata_lines = []
counts = { :not_changed => 0, :uploaded => 0, :deleted => 0, :not_found => 0}
self.discover do
|path, public_path|
next if found_paths.include?(path)
found_paths << path
data = self.root.join(path).read(:mode=>"rb")
ext = path.extname
format = ext[1..-1]
md5 = Digest::MD5.hexdigest(data)
public_id = "#{public_path.basename(ext)}-#{md5}"
found_public_ids << public_id
current_metadata = metadata.delete(public_path.to_s)
if current_metadata && current_metadata["public_id"] == public_id counts[:not_changed] += 1
$stderr.print "#{public_path} - #{public_id} - Not changed\n"
result = current_metadata
else
counts[:uploaded] += 1
$stderr.print "#{public_path} - #{public_id} - Uploading\n"
result = Cloudinary::Uploader.upload(Cloudinary::Blob.new(data, :original_filename=>path.to_s),
options.merge(:format=>format, :public_id=>public_id, :type=>:asset)
).merge("upload_time"=>Time.now)
end
metadata_lines << [public_path, public_id, result["upload_time"].to_i, result["version"], result["width"], result["height"]].join("\t")+"\n"
end
File.open(self.metadata_file_path, "w"){|f| f.print(metadata_lines.join)}
metadata.to_a.each do |path, info|
counts[:not_found] += 1
$stderr.print "#{path} - #{info["public_id"]} - Not found\n"
end
trash = metadata.to_a + self.metadata(metadata_trash_file_path, false).reject{|public_path, info| found_public_ids.include?(info["public_id"])}
if delete_missing
trash.each do
|path, info|
counts[:deleted] += 1
$stderr.print "#{path} - #{info["public_id"]} - Deleting\n"
Cloudinary::Uploader.destroy(info["public_id"], options.merge(:type=>:asset))
end
FileUtils.rm_f(self.metadata_trash_file_path)
else
metadata_lines = trash.map do
|public_path, info|
[public_path, info["public_id"], info["upload_time"].to_i, info["version"], info["width"], info["height"]].join("\t")+"\n"
end
File.open(self.metadata_trash_file_path, "w"){|f| f.print(metadata_lines.join)}
end
$stderr.print "\nCompleted syncing static resources to Cloudinary\n"
$stderr.print counts.sort.reject{|k,v| v == 0}.map{|k,v| "#{v} #{k.to_s.gsub('_', ' ').capitalize}"}.join(", ") + "\n"
end
|