#!/usr/bin/env ruby DockerBinaryLocation = `which docker`.chomp def cmd(*args) io = IO.popen(args, err: '/dev/null') io.read.split("\n") end def docker(*args) cmd(DockerBinaryLocation, *args) end tasks = [:remove_containers, :remove_volumes, :remove_images] container_filter = [:running] image_filter = [:untagged] while task_pattern = ARGV.shift case task_pattern.intern when :all container_filter = [] image_filter = [] when :running container_filter -= [:running] when :volumes # when :images image_filter -= [:untagged] end end containers = docker('ps', '-a', '-q').sort if container_filter.include? :running running_containers = docker('ps', '-q').sort containers = containers - running_containers end images = docker('images')[1..-1].map do |ln| parts = ln.split(' ').map{ |part| part unless part == '' } image_name = (parts[0] and parts[1]) ? "#{parts[0]}:#{parts[1]}" : nil {id: parts[2], name: image_name} end if image_filter.include? :untagged images = images.delete_if{ |image| image[:name] } end if tasks.include? :remove_containers and containers.length.nonzero? puts "removing containers" containers.each do |cid| docker 'kill', cid docker 'rm', cid puts " #{cid}" end end if tasks.include? :remove_images and images.length.nonzero? puts "removing image layers" images.each do |image| docker 'rmi', '-f', image[:id] puts " #{image[:name]} #{image[:id]}" end end