Skip to content

Instantly share code, notes, and snippets.

@breeno
Created February 2, 2011 03:28
Show Gist options
  • Save breeno/807199 to your computer and use it in GitHub Desktop.
Save breeno/807199 to your computer and use it in GitHub Desktop.
Simple script for detecting unreferenced images in an Xcode directory structure
#!/usr/bin/env ruby
#delete flag
should_delete = false
if ARGV.length >= 1
ARGV.each do |arg|
if arg.downcase.eql?('--delete')
should_delete = true
puts "--delete detected; will delete unreferenced image files.\n"
end
end
end
# get all the file names we are interested in
source_filenames = Dir['**/*.m']
source_filenames.concat( Dir['**/*.xib'] )
source_filenames.concat( Dir['**/*.plist'] )
png_filenames = Dir['**/*.png']
image_references = Hash.new
png_filenames.each { |filename| image_references[File.basename(filename.downcase)] = 0 }
# add our 'Known Good' images
image_references['default.png'] = 1
image_references['default-landscape.png']
['default-portraitupsidedown.png',
'default-landscapeleft.png',
'Default-LandscapeRight.png',
'Default-Portrait.png',
'Default-Landscape.png',
'Default.png'].each do |filename|
image_references[filename.downcase] = 1
end
# find all references to images in souces
source_filenames.each do |filename|
begin
file = File.open("#{filename}", "r")
contents = file.read.downcase
png_filenames.each do |image_filename|
base_image_filename = File.basename(image_filename).downcase
if contents.index(base_image_filename) != nil
image_references[base_image_filename] += 1 if image_references.has_key?(base_image_filename)
# check for the 2x version as well
retina_base_image_filename = "#{File.basename(base_image_filename,File.extname(base_image_filename))}@2x#{File.extname(base_image_filename)}"
image_references[retina_base_image_filename] += 1 if image_references.has_key?(retina_base_image_filename)
end
end
file.close
rescue Exception => ex
puts "Error opening #{filename} - #{ex}\n"
end
end
# show results
unused_image_count = 0
image_references.each do |filename,refcount|
if refcount == 0
puts "#{filename}\n"
unused_image_count += 1
end
end
puts " #{unused_image_count} unreferenced images out of #{png_filenames.count}.\n"
if should_delete
delete_count = 0
png_filenames.each do |image_filename|
begin
base_image_filename = File.basename(image_filename).downcase
if image_references[base_image_filename] == 0
File.delete( image_filename )
delete_count += 1
end
rescue
puts "Failed to delete #{image_filename}\n"
end
end
puts "\n deleted #{delete_count} unreferenced image files.\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment