Skip to content

Instantly share code, notes, and snippets.

@vlas-voloshin
Last active April 18, 2024 19:04
Show Gist options
  • Save vlas-voloshin/f9982128200345cd3fb7 to your computer and use it in GitHub Desktop.
Save vlas-voloshin/f9982128200345cd3fb7 to your computer and use it in GitHub Desktop.
Script for deleting duplicate iOS simulators and fixing simulators list in Xcode
#!/usr/bin/env ruby
# What is this for?
# This script fixes an issue appeared for some Xcode users where it would show long identifiers
# in the list of simulators instead of usual short names. This is caused by duplicate simulators
# being sometimes created after switching between Xcode versions, with the same
# device type + runtime pair occurring more than once in your list of available simulators.
# Instead of showing the same simulator name twice, Xcode defaults to simulator identifiers.
#
# What it does?
# The script queries Xcode's `simctl` utility for all simulators you have, finds duplicate type + runtime pairs,
# and offers you to delete them. After that, Xcode should return to displaying the list of simulators normally.
# When searching for duplicates, the script sorts simulators by their creation time to make sure it deletes
# the copy that was created more recently.
require 'json'
class SimDevice
attr_accessor :runtime
attr_accessor :name
attr_accessor :deviceType
attr_accessor :identifier
attr_accessor :timestamp
def initialize(runtime, name, deviceType, identifier, timestamp)
@runtime = runtime
@name = name
@identifier = identifier
@deviceType = deviceType
@timestamp = timestamp
end
def to_s
clean_runtime = @runtime.gsub("com.apple.CoreSimulator.SimRuntime.", "") rescue "[unknown runtime]"
clean_type = @deviceType.gsub("com.apple.CoreSimulator.SimDeviceType.", "") rescue "[unknown device type]"
return "#{@name} (#{clean_runtime}) – #{clean_type} #{@identifier} [#{@timestamp}]"
end
def equivalent_to_device(device)
return @runtime != nil && @deviceType != nil && @runtime == device.runtime && @deviceType == device.deviceType
end
end
# Executes a shell command and returns the result from stdout
def execute_simctl_command(command)
return %x[xcrun simctl #{command}]
end
# Retrieves the creation date/time of simulator with specified identifier
def simulator_creation_date(identifier)
directory = Dir.home() + "/Library/Developer/CoreSimulator/Devices/" + identifier
if (Dir.exists?(directory))
if (File::Stat.method_defined?(:birthtime))
return File.stat(directory).birthtime
else
return File.stat(directory).ctime
end
else
# Simulator directory is not yet created - treat it as if it was created right now (happens with newer sims)
return Time.now
end
end
# Deletes specified simulator
def delete_device(device)
execute_simctl_command("delete #{device.identifier}")
end
puts(" 💬 Searching for simulators...")
# Retrieve the list of existing simulators and sort by their creation timestamp, ascending
json = JSON.parse(execute_simctl_command("list -j devices"))
devices = json["devices"].flat_map { |runtime, devices|
devices.map { |device|
identifier = device["udid"]
timestamp = simulator_creation_date(identifier)
SimDevice.new(runtime, device["name"], device["deviceTypeIdentifier"], identifier, timestamp)
}
}.sort { |a, b| a.timestamp <=> b.timestamp }
duplicates = {}
# Enumerate all devices except for the last one
for i in 0..devices.count-2
device = devices[i]
# Enumerate all devices *after* this one (created *later*)
for j in i+1..devices.count-1
potential_duplicate = devices[j]
if potential_duplicate.equivalent_to_device(device)
duplicates[potential_duplicate] = device
# Break out of the inner loop if a duplicate is found - if another duplicate exists,
# it will be found when this one is reached in the outer loop
break
end
end
end
if duplicates.count == 0
puts(" 🎉 You don't have duplicate simulators!")
puts(" ℹ️ If you believe this is incorrect, try changing Xcode version used for Command Line Tools (Settings → Locations) and running this script again.")
exit()
end
puts(" ⚠️ Looks like you have #{duplicates.count} duplicate simulator#{duplicates.count > 1 ? "s" : ""}:")
duplicates.each_pair do |duplicate, original|
puts
puts("#{duplicate}")
puts("--- duplicate of ---")
puts("#{original}")
end
puts
puts(" ℹ️ Each duplicate was determined as the one created later than the 'original'.")
puts(" ⚠️ Would you like to delete #{duplicates.count > 1 ? "them" : "it"}? (y/n and return)")
answer = gets.strip
if (answer != "y" && answer != "yes")
puts(" 🚫 Aborting.")
exit()
end
puts(" 💬 Deleting...")
duplicates.each_key do |duplicate|
delete_device(duplicate)
end
puts(" ✅ Done!")
puts(" ℹ️ You may need to restart Xcode to see the changes.")
MIT License
Copyright (c) 2015-2021 Vlas Voloshin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@vlas-voloshin
Copy link
Author

This is the second revision of this script, now featuring smarter duplicate selection and cleaner preview of duplicates list.

@vlas-voloshin
Copy link
Author

The script has been updated to account for the fact that iOS 9 simulators are initially created without a directory. Such simulators are now treated as if they were created "right now".

@vlas-voloshin
Copy link
Author

The script has been updated to correctly handle device names with parentheses, e.g. "iPad Pro (12.9 inch)".

@friguron
Copy link

friguron commented Apr 22, 2021

As of now (April 2021), the script fails with the "iPad Pro (11-inch)" devices because this inch definition string has no "dot" character on it.
What happens then? That the regex interprets the "11-inch" as the UUID, because it also matches the "letters, numbers and dashes" of the current regex.
Changing the regex to something more hex oriented (ABCDEFabcedef, numbers and dashses) should do the trick, but then I'm no regex expert, so... I can't really suggest a proper change
Maybe inch numbers without a dot should also be accepted...

@vlas-voloshin
Copy link
Author

vlas-voloshin commented Apr 24, 2021

@friguron This script was long overdue to be updated to use simctl's JSON output format (supported since at least Xcode 10, or possibly even earlier) instead of regex-parsing its plain-text output, which, as you noticed, is not very reliable. This is now done – hopefully that fixes your problem.
I also renamed the license file so that it doesn't show up as the gist's own name 😬

@hroland
Copy link

hroland commented Jun 23, 2021

Thank u for this 🥰

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment