Skip to content

Instantly share code, notes, and snippets.

@dhgwilliam
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhgwilliam/aa207a9101e064081f2e to your computer and use it in GitHub Desktop.
Save dhgwilliam/aa207a9101e064081f2e to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'fileutils'
class VmList
@@cache_file = ENV['vm_list_cache_file'] || '/tmp/vm_list_cache'
@@cache_ttl = ENV['vm_list_cache_ttl'] || 60
def self.get_vm_list
vmware = %x{"/Applications/VMware\ Fusion.app/Contents/Library/vmrun" list | grep -v Total}.split("\n")
vbox = %x{VBoxManage list runningvms}.split("\n")
vmware + vbox
end
def self.age_of_cache?(file = @@cache_file)
FileUtils.touch(file) unless File.exist?(file)
Time.now - File.mtime(file)
end
def self.invalidate_cache
cache_result if age_of_cache? > @@cache_ttl
end
def self.cache_result(file = @@cache_file)
machines = get_vm_list
cache = File.open(file, 'w')
machines.each{|m| cache << m }
cache.close
end
def self.get_from_cache(file = @@cache_file)
invalidate_cache
File.readlines(file)
end
end
machines = VmList.get_from_cache
if ARGV.include?('-c')
vm_word = machines.count == 1 ? "VM" : "VMs"
puts "#{machines.count} #{vm_word}"
else
puts machines.join("\n") unless machines.empty?
end
# vi:ft=ruby
@dhgwilliam
Copy link
Author

Now with less flickering and much lower resource usage

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